1*67e74705SXin Li //=- LiveVariables.cpp - Live Variable Analysis for Source CFGs ----------*-==//
2*67e74705SXin Li //
3*67e74705SXin Li // The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements Live Variables analysis for source-level CFGs.
11*67e74705SXin Li //
12*67e74705SXin Li //===----------------------------------------------------------------------===//
13*67e74705SXin Li
14*67e74705SXin Li #include "clang/Analysis/Analyses/LiveVariables.h"
15*67e74705SXin Li #include "clang/AST/Stmt.h"
16*67e74705SXin Li #include "clang/AST/StmtVisitor.h"
17*67e74705SXin Li #include "clang/Analysis/Analyses/PostOrderCFGView.h"
18*67e74705SXin Li #include "clang/Analysis/AnalysisContext.h"
19*67e74705SXin Li #include "clang/Analysis/CFG.h"
20*67e74705SXin Li #include "llvm/ADT/DenseMap.h"
21*67e74705SXin Li #include "llvm/ADT/PostOrderIterator.h"
22*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
23*67e74705SXin Li #include <algorithm>
24*67e74705SXin Li #include <vector>
25*67e74705SXin Li
26*67e74705SXin Li using namespace clang;
27*67e74705SXin Li
28*67e74705SXin Li namespace {
29*67e74705SXin Li
30*67e74705SXin Li class DataflowWorklist {
31*67e74705SXin Li SmallVector<const CFGBlock *, 20> worklist;
32*67e74705SXin Li llvm::BitVector enqueuedBlocks;
33*67e74705SXin Li PostOrderCFGView *POV;
34*67e74705SXin Li public:
DataflowWorklist(const CFG & cfg,AnalysisDeclContext & Ctx)35*67e74705SXin Li DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
36*67e74705SXin Li : enqueuedBlocks(cfg.getNumBlockIDs()),
37*67e74705SXin Li POV(Ctx.getAnalysis<PostOrderCFGView>()) {}
38*67e74705SXin Li
39*67e74705SXin Li void enqueueBlock(const CFGBlock *block);
40*67e74705SXin Li void enqueuePredecessors(const CFGBlock *block);
41*67e74705SXin Li
42*67e74705SXin Li const CFGBlock *dequeue();
43*67e74705SXin Li
44*67e74705SXin Li void sortWorklist();
45*67e74705SXin Li };
46*67e74705SXin Li
47*67e74705SXin Li }
48*67e74705SXin Li
enqueueBlock(const clang::CFGBlock * block)49*67e74705SXin Li void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
50*67e74705SXin Li if (block && !enqueuedBlocks[block->getBlockID()]) {
51*67e74705SXin Li enqueuedBlocks[block->getBlockID()] = true;
52*67e74705SXin Li worklist.push_back(block);
53*67e74705SXin Li }
54*67e74705SXin Li }
55*67e74705SXin Li
enqueuePredecessors(const clang::CFGBlock * block)56*67e74705SXin Li void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
57*67e74705SXin Li const unsigned OldWorklistSize = worklist.size();
58*67e74705SXin Li for (CFGBlock::const_pred_iterator I = block->pred_begin(),
59*67e74705SXin Li E = block->pred_end(); I != E; ++I) {
60*67e74705SXin Li enqueueBlock(*I);
61*67e74705SXin Li }
62*67e74705SXin Li
63*67e74705SXin Li if (OldWorklistSize == 0 || OldWorklistSize == worklist.size())
64*67e74705SXin Li return;
65*67e74705SXin Li
66*67e74705SXin Li sortWorklist();
67*67e74705SXin Li }
68*67e74705SXin Li
sortWorklist()69*67e74705SXin Li void DataflowWorklist::sortWorklist() {
70*67e74705SXin Li std::sort(worklist.begin(), worklist.end(), POV->getComparator());
71*67e74705SXin Li }
72*67e74705SXin Li
dequeue()73*67e74705SXin Li const CFGBlock *DataflowWorklist::dequeue() {
74*67e74705SXin Li if (worklist.empty())
75*67e74705SXin Li return nullptr;
76*67e74705SXin Li const CFGBlock *b = worklist.pop_back_val();
77*67e74705SXin Li enqueuedBlocks[b->getBlockID()] = false;
78*67e74705SXin Li return b;
79*67e74705SXin Li }
80*67e74705SXin Li
81*67e74705SXin Li namespace {
82*67e74705SXin Li class LiveVariablesImpl {
83*67e74705SXin Li public:
84*67e74705SXin Li AnalysisDeclContext &analysisContext;
85*67e74705SXin Li llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
86*67e74705SXin Li llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
87*67e74705SXin Li llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
88*67e74705SXin Li llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
89*67e74705SXin Li llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
90*67e74705SXin Li llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
91*67e74705SXin Li const bool killAtAssign;
92*67e74705SXin Li
93*67e74705SXin Li LiveVariables::LivenessValues
94*67e74705SXin Li merge(LiveVariables::LivenessValues valsA,
95*67e74705SXin Li LiveVariables::LivenessValues valsB);
96*67e74705SXin Li
97*67e74705SXin Li LiveVariables::LivenessValues
98*67e74705SXin Li runOnBlock(const CFGBlock *block, LiveVariables::LivenessValues val,
99*67e74705SXin Li LiveVariables::Observer *obs = nullptr);
100*67e74705SXin Li
101*67e74705SXin Li void dumpBlockLiveness(const SourceManager& M);
102*67e74705SXin Li
LiveVariablesImpl(AnalysisDeclContext & ac,bool KillAtAssign)103*67e74705SXin Li LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
104*67e74705SXin Li : analysisContext(ac),
105*67e74705SXin Li SSetFact(false), // Do not canonicalize ImmutableSets by default.
106*67e74705SXin Li DSetFact(false), // This is a *major* performance win.
107*67e74705SXin Li killAtAssign(KillAtAssign) {}
108*67e74705SXin Li };
109*67e74705SXin Li }
110*67e74705SXin Li
getImpl(void * x)111*67e74705SXin Li static LiveVariablesImpl &getImpl(void *x) {
112*67e74705SXin Li return *((LiveVariablesImpl *) x);
113*67e74705SXin Li }
114*67e74705SXin Li
115*67e74705SXin Li //===----------------------------------------------------------------------===//
116*67e74705SXin Li // Operations and queries on LivenessValues.
117*67e74705SXin Li //===----------------------------------------------------------------------===//
118*67e74705SXin Li
isLive(const Stmt * S) const119*67e74705SXin Li bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
120*67e74705SXin Li return liveStmts.contains(S);
121*67e74705SXin Li }
122*67e74705SXin Li
isLive(const VarDecl * D) const123*67e74705SXin Li bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
124*67e74705SXin Li return liveDecls.contains(D);
125*67e74705SXin Li }
126*67e74705SXin Li
127*67e74705SXin Li namespace {
128*67e74705SXin Li template <typename SET>
mergeSets(SET A,SET B)129*67e74705SXin Li SET mergeSets(SET A, SET B) {
130*67e74705SXin Li if (A.isEmpty())
131*67e74705SXin Li return B;
132*67e74705SXin Li
133*67e74705SXin Li for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
134*67e74705SXin Li A = A.add(*it);
135*67e74705SXin Li }
136*67e74705SXin Li return A;
137*67e74705SXin Li }
138*67e74705SXin Li }
139*67e74705SXin Li
anchor()140*67e74705SXin Li void LiveVariables::Observer::anchor() { }
141*67e74705SXin Li
142*67e74705SXin Li LiveVariables::LivenessValues
merge(LiveVariables::LivenessValues valsA,LiveVariables::LivenessValues valsB)143*67e74705SXin Li LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
144*67e74705SXin Li LiveVariables::LivenessValues valsB) {
145*67e74705SXin Li
146*67e74705SXin Li llvm::ImmutableSetRef<const Stmt *>
147*67e74705SXin Li SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
148*67e74705SXin Li SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
149*67e74705SXin Li
150*67e74705SXin Li
151*67e74705SXin Li llvm::ImmutableSetRef<const VarDecl *>
152*67e74705SXin Li DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
153*67e74705SXin Li DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
154*67e74705SXin Li
155*67e74705SXin Li
156*67e74705SXin Li SSetRefA = mergeSets(SSetRefA, SSetRefB);
157*67e74705SXin Li DSetRefA = mergeSets(DSetRefA, DSetRefB);
158*67e74705SXin Li
159*67e74705SXin Li // asImmutableSet() canonicalizes the tree, allowing us to do an easy
160*67e74705SXin Li // comparison afterwards.
161*67e74705SXin Li return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
162*67e74705SXin Li DSetRefA.asImmutableSet());
163*67e74705SXin Li }
164*67e74705SXin Li
equals(const LivenessValues & V) const165*67e74705SXin Li bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
166*67e74705SXin Li return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
167*67e74705SXin Li }
168*67e74705SXin Li
169*67e74705SXin Li //===----------------------------------------------------------------------===//
170*67e74705SXin Li // Query methods.
171*67e74705SXin Li //===----------------------------------------------------------------------===//
172*67e74705SXin Li
isAlwaysAlive(const VarDecl * D)173*67e74705SXin Li static bool isAlwaysAlive(const VarDecl *D) {
174*67e74705SXin Li return D->hasGlobalStorage();
175*67e74705SXin Li }
176*67e74705SXin Li
isLive(const CFGBlock * B,const VarDecl * D)177*67e74705SXin Li bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
178*67e74705SXin Li return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
179*67e74705SXin Li }
180*67e74705SXin Li
isLive(const Stmt * S,const VarDecl * D)181*67e74705SXin Li bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
182*67e74705SXin Li return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
183*67e74705SXin Li }
184*67e74705SXin Li
isLive(const Stmt * Loc,const Stmt * S)185*67e74705SXin Li bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
186*67e74705SXin Li return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
187*67e74705SXin Li }
188*67e74705SXin Li
189*67e74705SXin Li //===----------------------------------------------------------------------===//
190*67e74705SXin Li // Dataflow computation.
191*67e74705SXin Li //===----------------------------------------------------------------------===//
192*67e74705SXin Li
193*67e74705SXin Li namespace {
194*67e74705SXin Li class TransferFunctions : public StmtVisitor<TransferFunctions> {
195*67e74705SXin Li LiveVariablesImpl &LV;
196*67e74705SXin Li LiveVariables::LivenessValues &val;
197*67e74705SXin Li LiveVariables::Observer *observer;
198*67e74705SXin Li const CFGBlock *currentBlock;
199*67e74705SXin Li public:
TransferFunctions(LiveVariablesImpl & im,LiveVariables::LivenessValues & Val,LiveVariables::Observer * Observer,const CFGBlock * CurrentBlock)200*67e74705SXin Li TransferFunctions(LiveVariablesImpl &im,
201*67e74705SXin Li LiveVariables::LivenessValues &Val,
202*67e74705SXin Li LiveVariables::Observer *Observer,
203*67e74705SXin Li const CFGBlock *CurrentBlock)
204*67e74705SXin Li : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
205*67e74705SXin Li
206*67e74705SXin Li void VisitBinaryOperator(BinaryOperator *BO);
207*67e74705SXin Li void VisitBlockExpr(BlockExpr *BE);
208*67e74705SXin Li void VisitDeclRefExpr(DeclRefExpr *DR);
209*67e74705SXin Li void VisitDeclStmt(DeclStmt *DS);
210*67e74705SXin Li void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
211*67e74705SXin Li void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
212*67e74705SXin Li void VisitUnaryOperator(UnaryOperator *UO);
213*67e74705SXin Li void Visit(Stmt *S);
214*67e74705SXin Li };
215*67e74705SXin Li }
216*67e74705SXin Li
FindVA(QualType Ty)217*67e74705SXin Li static const VariableArrayType *FindVA(QualType Ty) {
218*67e74705SXin Li const Type *ty = Ty.getTypePtr();
219*67e74705SXin Li while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
220*67e74705SXin Li if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
221*67e74705SXin Li if (VAT->getSizeExpr())
222*67e74705SXin Li return VAT;
223*67e74705SXin Li
224*67e74705SXin Li ty = VT->getElementType().getTypePtr();
225*67e74705SXin Li }
226*67e74705SXin Li
227*67e74705SXin Li return nullptr;
228*67e74705SXin Li }
229*67e74705SXin Li
LookThroughStmt(const Stmt * S)230*67e74705SXin Li static const Stmt *LookThroughStmt(const Stmt *S) {
231*67e74705SXin Li while (S) {
232*67e74705SXin Li if (const Expr *Ex = dyn_cast<Expr>(S))
233*67e74705SXin Li S = Ex->IgnoreParens();
234*67e74705SXin Li if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S)) {
235*67e74705SXin Li S = EWC->getSubExpr();
236*67e74705SXin Li continue;
237*67e74705SXin Li }
238*67e74705SXin Li if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
239*67e74705SXin Li S = OVE->getSourceExpr();
240*67e74705SXin Li continue;
241*67e74705SXin Li }
242*67e74705SXin Li break;
243*67e74705SXin Li }
244*67e74705SXin Li return S;
245*67e74705SXin Li }
246*67e74705SXin Li
AddLiveStmt(llvm::ImmutableSet<const Stmt * > & Set,llvm::ImmutableSet<const Stmt * >::Factory & F,const Stmt * S)247*67e74705SXin Li static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
248*67e74705SXin Li llvm::ImmutableSet<const Stmt *>::Factory &F,
249*67e74705SXin Li const Stmt *S) {
250*67e74705SXin Li Set = F.add(Set, LookThroughStmt(S));
251*67e74705SXin Li }
252*67e74705SXin Li
Visit(Stmt * S)253*67e74705SXin Li void TransferFunctions::Visit(Stmt *S) {
254*67e74705SXin Li if (observer)
255*67e74705SXin Li observer->observeStmt(S, currentBlock, val);
256*67e74705SXin Li
257*67e74705SXin Li StmtVisitor<TransferFunctions>::Visit(S);
258*67e74705SXin Li
259*67e74705SXin Li if (isa<Expr>(S)) {
260*67e74705SXin Li val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
261*67e74705SXin Li }
262*67e74705SXin Li
263*67e74705SXin Li // Mark all children expressions live.
264*67e74705SXin Li
265*67e74705SXin Li switch (S->getStmtClass()) {
266*67e74705SXin Li default:
267*67e74705SXin Li break;
268*67e74705SXin Li case Stmt::StmtExprClass: {
269*67e74705SXin Li // For statement expressions, look through the compound statement.
270*67e74705SXin Li S = cast<StmtExpr>(S)->getSubStmt();
271*67e74705SXin Li break;
272*67e74705SXin Li }
273*67e74705SXin Li case Stmt::CXXMemberCallExprClass: {
274*67e74705SXin Li // Include the implicit "this" pointer as being live.
275*67e74705SXin Li CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
276*67e74705SXin Li if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
277*67e74705SXin Li AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
278*67e74705SXin Li }
279*67e74705SXin Li break;
280*67e74705SXin Li }
281*67e74705SXin Li case Stmt::ObjCMessageExprClass: {
282*67e74705SXin Li // In calls to super, include the implicit "self" pointer as being live.
283*67e74705SXin Li ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
284*67e74705SXin Li if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
285*67e74705SXin Li val.liveDecls = LV.DSetFact.add(val.liveDecls,
286*67e74705SXin Li LV.analysisContext.getSelfDecl());
287*67e74705SXin Li break;
288*67e74705SXin Li }
289*67e74705SXin Li case Stmt::DeclStmtClass: {
290*67e74705SXin Li const DeclStmt *DS = cast<DeclStmt>(S);
291*67e74705SXin Li if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
292*67e74705SXin Li for (const VariableArrayType* VA = FindVA(VD->getType());
293*67e74705SXin Li VA != nullptr; VA = FindVA(VA->getElementType())) {
294*67e74705SXin Li AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
295*67e74705SXin Li }
296*67e74705SXin Li }
297*67e74705SXin Li break;
298*67e74705SXin Li }
299*67e74705SXin Li case Stmt::PseudoObjectExprClass: {
300*67e74705SXin Li // A pseudo-object operation only directly consumes its result
301*67e74705SXin Li // expression.
302*67e74705SXin Li Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
303*67e74705SXin Li if (!child) return;
304*67e74705SXin Li if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
305*67e74705SXin Li child = OV->getSourceExpr();
306*67e74705SXin Li child = child->IgnoreParens();
307*67e74705SXin Li val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
308*67e74705SXin Li return;
309*67e74705SXin Li }
310*67e74705SXin Li
311*67e74705SXin Li // FIXME: These cases eventually shouldn't be needed.
312*67e74705SXin Li case Stmt::ExprWithCleanupsClass: {
313*67e74705SXin Li S = cast<ExprWithCleanups>(S)->getSubExpr();
314*67e74705SXin Li break;
315*67e74705SXin Li }
316*67e74705SXin Li case Stmt::CXXBindTemporaryExprClass: {
317*67e74705SXin Li S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
318*67e74705SXin Li break;
319*67e74705SXin Li }
320*67e74705SXin Li case Stmt::UnaryExprOrTypeTraitExprClass: {
321*67e74705SXin Li // No need to unconditionally visit subexpressions.
322*67e74705SXin Li return;
323*67e74705SXin Li }
324*67e74705SXin Li }
325*67e74705SXin Li
326*67e74705SXin Li for (Stmt *Child : S->children()) {
327*67e74705SXin Li if (Child)
328*67e74705SXin Li AddLiveStmt(val.liveStmts, LV.SSetFact, Child);
329*67e74705SXin Li }
330*67e74705SXin Li }
331*67e74705SXin Li
VisitBinaryOperator(BinaryOperator * B)332*67e74705SXin Li void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
333*67e74705SXin Li if (B->isAssignmentOp()) {
334*67e74705SXin Li if (!LV.killAtAssign)
335*67e74705SXin Li return;
336*67e74705SXin Li
337*67e74705SXin Li // Assigning to a variable?
338*67e74705SXin Li Expr *LHS = B->getLHS()->IgnoreParens();
339*67e74705SXin Li
340*67e74705SXin Li if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS))
341*67e74705SXin Li if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
342*67e74705SXin Li // Assignments to references don't kill the ref's address
343*67e74705SXin Li if (VD->getType()->isReferenceType())
344*67e74705SXin Li return;
345*67e74705SXin Li
346*67e74705SXin Li if (!isAlwaysAlive(VD)) {
347*67e74705SXin Li // The variable is now dead.
348*67e74705SXin Li val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
349*67e74705SXin Li }
350*67e74705SXin Li
351*67e74705SXin Li if (observer)
352*67e74705SXin Li observer->observerKill(DR);
353*67e74705SXin Li }
354*67e74705SXin Li }
355*67e74705SXin Li }
356*67e74705SXin Li
VisitBlockExpr(BlockExpr * BE)357*67e74705SXin Li void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
358*67e74705SXin Li for (const VarDecl *VD :
359*67e74705SXin Li LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
360*67e74705SXin Li if (isAlwaysAlive(VD))
361*67e74705SXin Li continue;
362*67e74705SXin Li val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
363*67e74705SXin Li }
364*67e74705SXin Li }
365*67e74705SXin Li
VisitDeclRefExpr(DeclRefExpr * DR)366*67e74705SXin Li void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
367*67e74705SXin Li if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
368*67e74705SXin Li if (!isAlwaysAlive(D) && LV.inAssignment.find(DR) == LV.inAssignment.end())
369*67e74705SXin Li val.liveDecls = LV.DSetFact.add(val.liveDecls, D);
370*67e74705SXin Li }
371*67e74705SXin Li
VisitDeclStmt(DeclStmt * DS)372*67e74705SXin Li void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
373*67e74705SXin Li for (const auto *DI : DS->decls())
374*67e74705SXin Li if (const auto *VD = dyn_cast<VarDecl>(DI)) {
375*67e74705SXin Li if (!isAlwaysAlive(VD))
376*67e74705SXin Li val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
377*67e74705SXin Li }
378*67e74705SXin Li }
379*67e74705SXin Li
VisitObjCForCollectionStmt(ObjCForCollectionStmt * OS)380*67e74705SXin Li void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
381*67e74705SXin Li // Kill the iteration variable.
382*67e74705SXin Li DeclRefExpr *DR = nullptr;
383*67e74705SXin Li const VarDecl *VD = nullptr;
384*67e74705SXin Li
385*67e74705SXin Li Stmt *element = OS->getElement();
386*67e74705SXin Li if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
387*67e74705SXin Li VD = cast<VarDecl>(DS->getSingleDecl());
388*67e74705SXin Li }
389*67e74705SXin Li else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
390*67e74705SXin Li VD = cast<VarDecl>(DR->getDecl());
391*67e74705SXin Li }
392*67e74705SXin Li
393*67e74705SXin Li if (VD) {
394*67e74705SXin Li val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
395*67e74705SXin Li if (observer && DR)
396*67e74705SXin Li observer->observerKill(DR);
397*67e74705SXin Li }
398*67e74705SXin Li }
399*67e74705SXin Li
400*67e74705SXin Li void TransferFunctions::
VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr * UE)401*67e74705SXin Li VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
402*67e74705SXin Li {
403*67e74705SXin Li // While sizeof(var) doesn't technically extend the liveness of 'var', it
404*67e74705SXin Li // does extent the liveness of metadata if 'var' is a VariableArrayType.
405*67e74705SXin Li // We handle that special case here.
406*67e74705SXin Li if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
407*67e74705SXin Li return;
408*67e74705SXin Li
409*67e74705SXin Li const Expr *subEx = UE->getArgumentExpr();
410*67e74705SXin Li if (subEx->getType()->isVariableArrayType()) {
411*67e74705SXin Li assert(subEx->isLValue());
412*67e74705SXin Li val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
413*67e74705SXin Li }
414*67e74705SXin Li }
415*67e74705SXin Li
VisitUnaryOperator(UnaryOperator * UO)416*67e74705SXin Li void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
417*67e74705SXin Li // Treat ++/-- as a kill.
418*67e74705SXin Li // Note we don't actually have to do anything if we don't have an observer,
419*67e74705SXin Li // since a ++/-- acts as both a kill and a "use".
420*67e74705SXin Li if (!observer)
421*67e74705SXin Li return;
422*67e74705SXin Li
423*67e74705SXin Li switch (UO->getOpcode()) {
424*67e74705SXin Li default:
425*67e74705SXin Li return;
426*67e74705SXin Li case UO_PostInc:
427*67e74705SXin Li case UO_PostDec:
428*67e74705SXin Li case UO_PreInc:
429*67e74705SXin Li case UO_PreDec:
430*67e74705SXin Li break;
431*67e74705SXin Li }
432*67e74705SXin Li
433*67e74705SXin Li if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens()))
434*67e74705SXin Li if (isa<VarDecl>(DR->getDecl())) {
435*67e74705SXin Li // Treat ++/-- as a kill.
436*67e74705SXin Li observer->observerKill(DR);
437*67e74705SXin Li }
438*67e74705SXin Li }
439*67e74705SXin Li
440*67e74705SXin Li LiveVariables::LivenessValues
runOnBlock(const CFGBlock * block,LiveVariables::LivenessValues val,LiveVariables::Observer * obs)441*67e74705SXin Li LiveVariablesImpl::runOnBlock(const CFGBlock *block,
442*67e74705SXin Li LiveVariables::LivenessValues val,
443*67e74705SXin Li LiveVariables::Observer *obs) {
444*67e74705SXin Li
445*67e74705SXin Li TransferFunctions TF(*this, val, obs, block);
446*67e74705SXin Li
447*67e74705SXin Li // Visit the terminator (if any).
448*67e74705SXin Li if (const Stmt *term = block->getTerminator())
449*67e74705SXin Li TF.Visit(const_cast<Stmt*>(term));
450*67e74705SXin Li
451*67e74705SXin Li // Apply the transfer function for all Stmts in the block.
452*67e74705SXin Li for (CFGBlock::const_reverse_iterator it = block->rbegin(),
453*67e74705SXin Li ei = block->rend(); it != ei; ++it) {
454*67e74705SXin Li const CFGElement &elem = *it;
455*67e74705SXin Li
456*67e74705SXin Li if (Optional<CFGAutomaticObjDtor> Dtor =
457*67e74705SXin Li elem.getAs<CFGAutomaticObjDtor>()) {
458*67e74705SXin Li val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
459*67e74705SXin Li continue;
460*67e74705SXin Li }
461*67e74705SXin Li
462*67e74705SXin Li if (!elem.getAs<CFGStmt>())
463*67e74705SXin Li continue;
464*67e74705SXin Li
465*67e74705SXin Li const Stmt *S = elem.castAs<CFGStmt>().getStmt();
466*67e74705SXin Li TF.Visit(const_cast<Stmt*>(S));
467*67e74705SXin Li stmtsToLiveness[S] = val;
468*67e74705SXin Li }
469*67e74705SXin Li return val;
470*67e74705SXin Li }
471*67e74705SXin Li
runOnAllBlocks(LiveVariables::Observer & obs)472*67e74705SXin Li void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
473*67e74705SXin Li const CFG *cfg = getImpl(impl).analysisContext.getCFG();
474*67e74705SXin Li for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
475*67e74705SXin Li getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
476*67e74705SXin Li }
477*67e74705SXin Li
LiveVariables(void * im)478*67e74705SXin Li LiveVariables::LiveVariables(void *im) : impl(im) {}
479*67e74705SXin Li
~LiveVariables()480*67e74705SXin Li LiveVariables::~LiveVariables() {
481*67e74705SXin Li delete (LiveVariablesImpl*) impl;
482*67e74705SXin Li }
483*67e74705SXin Li
484*67e74705SXin Li LiveVariables *
computeLiveness(AnalysisDeclContext & AC,bool killAtAssign)485*67e74705SXin Li LiveVariables::computeLiveness(AnalysisDeclContext &AC,
486*67e74705SXin Li bool killAtAssign) {
487*67e74705SXin Li
488*67e74705SXin Li // No CFG? Bail out.
489*67e74705SXin Li CFG *cfg = AC.getCFG();
490*67e74705SXin Li if (!cfg)
491*67e74705SXin Li return nullptr;
492*67e74705SXin Li
493*67e74705SXin Li // The analysis currently has scalability issues for very large CFGs.
494*67e74705SXin Li // Bail out if it looks too large.
495*67e74705SXin Li if (cfg->getNumBlockIDs() > 300000)
496*67e74705SXin Li return nullptr;
497*67e74705SXin Li
498*67e74705SXin Li LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
499*67e74705SXin Li
500*67e74705SXin Li // Construct the dataflow worklist. Enqueue the exit block as the
501*67e74705SXin Li // start of the analysis.
502*67e74705SXin Li DataflowWorklist worklist(*cfg, AC);
503*67e74705SXin Li llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
504*67e74705SXin Li
505*67e74705SXin Li // FIXME: we should enqueue using post order.
506*67e74705SXin Li for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
507*67e74705SXin Li const CFGBlock *block = *it;
508*67e74705SXin Li worklist.enqueueBlock(block);
509*67e74705SXin Li
510*67e74705SXin Li // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
511*67e74705SXin Li // We need to do this because we lack context in the reverse analysis
512*67e74705SXin Li // to determine if a DeclRefExpr appears in such a context, and thus
513*67e74705SXin Li // doesn't constitute a "use".
514*67e74705SXin Li if (killAtAssign)
515*67e74705SXin Li for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
516*67e74705SXin Li bi != be; ++bi) {
517*67e74705SXin Li if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
518*67e74705SXin Li if (const BinaryOperator *BO =
519*67e74705SXin Li dyn_cast<BinaryOperator>(cs->getStmt())) {
520*67e74705SXin Li if (BO->getOpcode() == BO_Assign) {
521*67e74705SXin Li if (const DeclRefExpr *DR =
522*67e74705SXin Li dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
523*67e74705SXin Li LV->inAssignment[DR] = 1;
524*67e74705SXin Li }
525*67e74705SXin Li }
526*67e74705SXin Li }
527*67e74705SXin Li }
528*67e74705SXin Li }
529*67e74705SXin Li }
530*67e74705SXin Li
531*67e74705SXin Li worklist.sortWorklist();
532*67e74705SXin Li
533*67e74705SXin Li while (const CFGBlock *block = worklist.dequeue()) {
534*67e74705SXin Li // Determine if the block's end value has changed. If not, we
535*67e74705SXin Li // have nothing left to do for this block.
536*67e74705SXin Li LivenessValues &prevVal = LV->blocksEndToLiveness[block];
537*67e74705SXin Li
538*67e74705SXin Li // Merge the values of all successor blocks.
539*67e74705SXin Li LivenessValues val;
540*67e74705SXin Li for (CFGBlock::const_succ_iterator it = block->succ_begin(),
541*67e74705SXin Li ei = block->succ_end(); it != ei; ++it) {
542*67e74705SXin Li if (const CFGBlock *succ = *it) {
543*67e74705SXin Li val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
544*67e74705SXin Li }
545*67e74705SXin Li }
546*67e74705SXin Li
547*67e74705SXin Li if (!everAnalyzedBlock[block->getBlockID()])
548*67e74705SXin Li everAnalyzedBlock[block->getBlockID()] = true;
549*67e74705SXin Li else if (prevVal.equals(val))
550*67e74705SXin Li continue;
551*67e74705SXin Li
552*67e74705SXin Li prevVal = val;
553*67e74705SXin Li
554*67e74705SXin Li // Update the dataflow value for the start of this block.
555*67e74705SXin Li LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
556*67e74705SXin Li
557*67e74705SXin Li // Enqueue the value to the predecessors.
558*67e74705SXin Li worklist.enqueuePredecessors(block);
559*67e74705SXin Li }
560*67e74705SXin Li
561*67e74705SXin Li return new LiveVariables(LV);
562*67e74705SXin Li }
563*67e74705SXin Li
dumpBlockLiveness(const SourceManager & M)564*67e74705SXin Li void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
565*67e74705SXin Li getImpl(impl).dumpBlockLiveness(M);
566*67e74705SXin Li }
567*67e74705SXin Li
dumpBlockLiveness(const SourceManager & M)568*67e74705SXin Li void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
569*67e74705SXin Li std::vector<const CFGBlock *> vec;
570*67e74705SXin Li for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
571*67e74705SXin Li it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
572*67e74705SXin Li it != ei; ++it) {
573*67e74705SXin Li vec.push_back(it->first);
574*67e74705SXin Li }
575*67e74705SXin Li std::sort(vec.begin(), vec.end(), [](const CFGBlock *A, const CFGBlock *B) {
576*67e74705SXin Li return A->getBlockID() < B->getBlockID();
577*67e74705SXin Li });
578*67e74705SXin Li
579*67e74705SXin Li std::vector<const VarDecl*> declVec;
580*67e74705SXin Li
581*67e74705SXin Li for (std::vector<const CFGBlock *>::iterator
582*67e74705SXin Li it = vec.begin(), ei = vec.end(); it != ei; ++it) {
583*67e74705SXin Li llvm::errs() << "\n[ B" << (*it)->getBlockID()
584*67e74705SXin Li << " (live variables at block exit) ]\n";
585*67e74705SXin Li
586*67e74705SXin Li LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
587*67e74705SXin Li declVec.clear();
588*67e74705SXin Li
589*67e74705SXin Li for (llvm::ImmutableSet<const VarDecl *>::iterator si =
590*67e74705SXin Li vals.liveDecls.begin(),
591*67e74705SXin Li se = vals.liveDecls.end(); si != se; ++si) {
592*67e74705SXin Li declVec.push_back(*si);
593*67e74705SXin Li }
594*67e74705SXin Li
595*67e74705SXin Li std::sort(declVec.begin(), declVec.end(), [](const Decl *A, const Decl *B) {
596*67e74705SXin Li return A->getLocStart() < B->getLocStart();
597*67e74705SXin Li });
598*67e74705SXin Li
599*67e74705SXin Li for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
600*67e74705SXin Li de = declVec.end(); di != de; ++di) {
601*67e74705SXin Li llvm::errs() << " " << (*di)->getDeclName().getAsString()
602*67e74705SXin Li << " <";
603*67e74705SXin Li (*di)->getLocation().dump(M);
604*67e74705SXin Li llvm::errs() << ">\n";
605*67e74705SXin Li }
606*67e74705SXin Li }
607*67e74705SXin Li llvm::errs() << "\n";
608*67e74705SXin Li }
609*67e74705SXin Li
getTag()610*67e74705SXin Li const void *LiveVariables::getTag() { static int x; return &x; }
getTag()611*67e74705SXin Li const void *RelaxedLiveVariables::getTag() { static int x; return &x; }
612