Debian Codegraph @

src/com/google/javascript/jscomp/LiveVariablesAnalysis.java

raw symbols SCIP
1 /*
2 * Copyright 2008 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.Sets;
21 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
22 import com.google.javascript.jscomp.Scope.Var;
23 import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge;
24 import com.google.javascript.jscomp.graph.LatticeElement;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.Token;
27
28 import java.util.BitSet;
29 import java.util.List;
30 import java.util.Set;
31
32 /**
33 * Compute the "liveness" of all local variables. A variable is "live" at a
34 * point of a program if the value it is currently holding might be read later.
35 * Otherwise, the variable is considered "dead" if we know for sure that it will
36 * no longer be read. Dead variables are candidates for dead assignment
37 * elimination and variable name sharing. The worst case safe assumption is to
38 * assume that all variables are live. In that case, we will have no opportunity
39 * for optimizations. This is especially the case within a TRY block when an
40 * assignment is not guaranteed to take place. We bail out by assuming that
41 * all variables are live.
42 * <p>
43 * Due to the possibility of inner functions and closures, certain "local"
44 * variables can escape the function. These variables will be considered as
45 * global and they can be retrieved with {@link #getEscapedLocals()}.
46 *
47 */
48 class LiveVariablesAnalysis extends
49 DataFlowAnalysis<Node, LiveVariablesAnalysis.LiveVariableLattice> {
50
51 // 100 = ((# of original Power Rangers) ^
52 // (# years of Warren Harding in office)) *
53 // (# of Ninja Turtles)
54 static final int MAX_VARIABLES_TO_ANALYZE = 100;
55
56 public static final String ARGUMENT_ARRAY_ALIAS = "arguments";
57
58 private static class LiveVariableJoinOp
59 implements JoinOp<LiveVariableLattice> {
60 @Override
61 public LiveVariableLattice apply(List<LiveVariableLattice> in) {
62 LiveVariableLattice result = new LiveVariableLattice(in.get(0));
63 for (int i = 1; i < in.size(); i++) {
64 result.liveSet.or(in.get(i).liveSet);
65 }
66 return result;
67 }
68 }
69
70 /**
71 * The lattice that stores the liveness of all local variables at a given
72 * point in the program. The whole lattice is the power set of all local
73 * variables and a variable is live if it is in the set.
74 */
75 static class LiveVariableLattice implements LatticeElement {
76 private final BitSet liveSet;
77
78 /**
79 * @param numVars Number of all local variables.
80 */
81 private LiveVariableLattice(int numVars) {
82 this.liveSet = new BitSet(numVars);
83 }
84
85 private LiveVariableLattice(LiveVariableLattice other) {
86 Preconditions.checkNotNull(other);
87 this.liveSet = (BitSet) other.liveSet.clone();
88 }
89
90 @Override
91 public boolean equals(Object other) {
92 Preconditions.checkNotNull(other);
93 return (other instanceof LiveVariableLattice) &&
94 this.liveSet.equals(((LiveVariableLattice) other).liveSet);
95 }
96
97 public boolean isLive(Var v) {
98 Preconditions.checkNotNull(v);
99 return liveSet.get(v.index);
100 }
101
102 public boolean isLive(int index) {
103 return liveSet.get(index);
104 }
105
106 @Override
107 public String toString() {
108 return liveSet.toString();
109 }
110
111 @Override
112 public int hashCode() {
113 return liveSet.hashCode();
114 }
115 }
116
117 // The scope of the function that we are analyzing.
118 private final Scope jsScope;
119 private final Set<Var> escaped;
120
121 LiveVariablesAnalysis(ControlFlowGraph<Node> cfg, Scope jsScope,
122 AbstractCompiler compiler) {
123 super(cfg, new LiveVariableJoinOp());
124 this.jsScope = jsScope;
125 this.escaped = Sets.newHashSet();
126 computeEscaped(jsScope, escaped, compiler);
127 }
128
129 public Set<Var> getEscapedLocals() {
130 return escaped;
131 }
132
133 public int getVarIndex(String var) {
134 return jsScope.getVar(var).index;
135 }
136
137 @Override
138 boolean isForward() {
139 return false;
140 }
141
142 @Override
143 LiveVariableLattice createEntryLattice() {
144 return new LiveVariableLattice(jsScope.getVarCount());
145 }
146
147 @Override
148 LiveVariableLattice createInitialEstimateLattice() {
149 return new LiveVariableLattice(jsScope.getVarCount());
150 }
151
152 @Override
153 LiveVariableLattice flowThrough(Node node, LiveVariableLattice input) {
154 final BitSet gen = new BitSet(input.liveSet.size());
155 final BitSet kill = new BitSet(input.liveSet.size());
156
157 // Make kills conditional if the node can end abruptly by an exception.
158 boolean conditional = false;
159 List<DiGraphEdge<Node, Branch>> edgeList = getCfg().getOutEdges(node);
160 for (DiGraphEdge<Node, Branch> edge : edgeList) {
161 if (Branch.ON_EX.equals(edge.getValue())) {
162 conditional = true;
163 }
164 }
165 computeGenKill(node, gen, kill, conditional);
166 LiveVariableLattice result = new LiveVariableLattice(input);
167 // L_in = L_out - Kill + Gen
168 result.liveSet.andNot(kill);
169 result.liveSet.or(gen);
170 return result;
171 }
172
173 /**
174 * Computes the GEN and KILL set.
175 *
176 * @param n Root node.
177 * @param gen Local variables that are live because of the instruction at
178 * {@code n} will be added to this set.
179 * @param kill Local variables that are killed because of the instruction at
180 * {@code n} will be added to this set.
181 * @param conditional {@code true} if any assignments encountered are
182 * conditionally executed. These assignments might not kill a variable.
183 */
184 private void computeGenKill(Node n, BitSet gen, BitSet kill,
185 boolean conditional) {
186
187 switch (n.getType()) {
188 case Token.SCRIPT:
189 case Token.BLOCK:
190 case Token.FUNCTION:
191 return;
192
193 case Token.WHILE:
194 case Token.DO:
195 case Token.IF:
196 computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,
197 conditional);
198 return;
199
200 case Token.FOR:
201 if (!NodeUtil.isForIn(n)) {
202 computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,
203 conditional);
204 } else {
205 // for(x in y) {...}
206 Node lhs = n.getFirstChild();
207 if (lhs.isVar()) {
208 // for(var x in y) {...}
209 lhs = lhs.getLastChild();
210 }
211
212 if (lhs.isName()) {
213 addToSetIfLocal(lhs, kill);
214 addToSetIfLocal(lhs, gen);
215 } else {
216 computeGenKill(lhs, gen, kill, conditional);
217 }
218
219 // rhs is executed only once so we don't go into it every loop.
220 }
221 return;
222
223 case Token.VAR:
224 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
225 if (c.hasChildren()) {
226 computeGenKill(c.getFirstChild(), gen, kill, conditional);
227 if (!conditional) {
228 addToSetIfLocal(c, kill);
229 }
230 }
231 }
232 return;
233
234 case Token.AND:
235 case Token.OR:
236 computeGenKill(n.getFirstChild(), gen, kill, conditional);
237 // May short circuit.
238 computeGenKill(n.getLastChild(), gen, kill, true);
239 return;
240
241 case Token.HOOK:
242 computeGenKill(n.getFirstChild(), gen, kill, conditional);
243 // Assume both sides are conditional.
244 computeGenKill(n.getFirstChild().getNext(), gen, kill, true);
245 computeGenKill(n.getLastChild(), gen, kill, true);
246 return;
247
248 case Token.NAME:
249 if (isArgumentsName(n)) {
250 markAllParametersEscaped();
251 } else {
252 addToSetIfLocal(n, gen);
253 }
254 return;
255
256 default:
257 if (NodeUtil.isAssignmentOp(n) && n.getFirstChild().isName()) {
258 Node lhs = n.getFirstChild();
259 if (!conditional) {
260 addToSetIfLocal(lhs, kill);
261 }
262 if (!n.isAssign()) {
263 // assignments such as a += 1 reads a.
264 addToSetIfLocal(lhs, gen);
265 }
266 computeGenKill(lhs.getNext(), gen, kill, conditional);
267 } else {
268 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
269 computeGenKill(c, gen, kill, conditional);
270 }
271 }
272 return;
273 }
274 }
275
276 private void addToSetIfLocal(Node node, BitSet set) {
277 Preconditions.checkState(node.isName());
278 String name = node.getString();
279 if (!jsScope.isDeclared(name, false)) {
280 return;
281 }
282 Var var = jsScope.getVar(name);
283 if (!escaped.contains(var)) {
284 set.set(var.index);
285 }
286 }
287
288 /**
289 * Give up computing liveness of formal parameter by putting all the parameter
290 * names in the escaped set.
291 */
292 void markAllParametersEscaped() {
293 Node lp = jsScope.getRootNode().getFirstChild().getNext();
294 for(Node arg = lp.getFirstChild(); arg != null; arg = arg.getNext()) {
295 escaped.add(jsScope.getVar(arg.getString()));
296 }
297 }
298
299 private boolean isArgumentsName(Node n) {
300 if (!n.isName()||
301 !n.getString().equals(ARGUMENT_ARRAY_ALIAS) ||
302 jsScope.isDeclared(ARGUMENT_ARRAY_ALIAS, false)) {
303 return false;
304 } else {
305 return true;
306 }
307 }
308 }