Debian Codegraph @

src/com/google/javascript/jscomp/MustBeReachingVariableDef.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.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.ControlFlowGraph.AbstractCfgNodeTraversalCallback;
23 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
24 import com.google.javascript.jscomp.Scope.Var;
25 import com.google.javascript.jscomp.graph.GraphNode;
26 import com.google.javascript.jscomp.graph.LatticeElement;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.Token;
29
30 import java.util.Iterator;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Set;
34
35 import javax.annotation.Nullable;
36
37 /**
38 * Computes reaching definition for all use of each variables.
39 *
40 * A definition of {@code A} in {@code A = foo()} is a reaching definition of
41 * the use of {@code A} in {@code alert(A)} if all paths from entry node must
42 * reaches that definition and it is the last definition before the use.
43 *
44 */
45 final class MustBeReachingVariableDef extends
46 DataFlowAnalysis<Node, MustBeReachingVariableDef.MustDef> {
47
48 // The scope of the function that we are analyzing.
49 private final Scope jsScope;
50 private final AbstractCompiler compiler;
51 private final Set<Var> escaped;
52
53 MustBeReachingVariableDef(
54 ControlFlowGraph<Node> cfg, Scope jsScope, AbstractCompiler compiler) {
55 super(cfg, new MustDefJoin());
56 this.jsScope = jsScope;
57 this.compiler = compiler;
58 this.escaped = Sets.newHashSet();
59 computeEscaped(jsScope, escaped, compiler);
60 }
61
62 /**
63 * Abstraction of a local variable definition. It represents the node which
64 * a local variable is defined as well as a set of other local variables that
65 * this definition reads from. For example N: a = b + foo.bar(c). The
66 * definition node will be N, the depending set would be {b,c}.
67 */
68 static class Definition {
69 final Node node;
70 final Set<Var> depends = Sets.newHashSet();
71 private boolean unknownDependencies = false;
72
73 Definition(Node node) {
74 this.node = node;
75 }
76
77 @Override
78 public boolean equals(Object other) {
79 if (!(other instanceof Definition)) {
80 return false;
81 }
82 Definition otherDef = (Definition) other;
83 // If the var has the same definition node we can assume they have the
84 // same depends set.
85 return otherDef.node == node;
86 }
87 }
88
89 /**
90 * Must reaching definition lattice representation. It captures a product
91 * lattice for each local (non-escaped) variable. The sub-lattice is
92 * a n + 2 element lattice with all the {@link Definition} in the program,
93 * TOP and BOTTOM.
94 *
95 * <p>Since this is a Must-Define analysis, BOTTOM represents the case where
96 * there might be more than one reaching definition for the variable.
97 *
98 *
99 * (TOP)
100 * / | | \
101 * N1 N2 N3 ....Nn
102 * \ | | /
103 * (BOTTOM)
104 *
105 */
106 static final class MustDef implements LatticeElement {
107
108 // TODO(user): Use bit vector instead of maps might get better
109 // performance. Change it after this is tested to be fully functional.
110
111 // When a Var "A" = "TOP", "A" does not exist in reachingDef's keySet.
112 // When a Var "A" = Node N, "A" maps to that node.
113 // When a Var "A" = "BOTTOM", "A" maps to null.
114 final Map<Var, Definition> reachingDef;
115
116 public MustDef() {
117 reachingDef = Maps.newHashMap();
118 }
119
120 public MustDef(Iterator<Var> vars) {
121 this();
122 while(vars.hasNext()) {
123 Var var = vars.next();
124 // Every variable in the scope is defined once in the beginning of the
125 // function: all the declared variables are undefined, all functions
126 // have been assigned and all arguments has its value from the caller.
127 reachingDef.put(var, new Definition(var.scope.getRootNode()));
128 }
129 }
130
131 /**
132 * Copy constructor.
133 *
134 * @param other The constructed object is a replicated copy of this element.
135 */
136 public MustDef(MustDef other) {
137 reachingDef = Maps.newHashMap(other.reachingDef);
138 }
139
140 @Override
141 public boolean equals(Object other) {
142 return (other instanceof MustDef) &&
143 ((MustDef) other).reachingDef.equals(this.reachingDef);
144 }
145 }
146
147 private static class MustDefJoin extends JoinOp.BinaryJoinOp<MustDef> {
148 @Override
149 public MustDef apply(MustDef a, MustDef b) {
150 MustDef result = new MustDef();
151 Map<Var, Definition> resultMap = result.reachingDef;
152
153 // Take the join of all variables that are not TOP in this.
154 for (Map.Entry<Var, Definition> varEntry : a.reachingDef.entrySet()) {
155 Var var = varEntry.getKey();
156 Definition aDef = varEntry.getValue();
157
158 if (aDef == null) {
159 // "a" is BOTTOM implies that the variable has more than one possible
160 // definition. We set the join of this to be BOTTOM regardless of what
161 // "b" might be.
162 resultMap.put(var, null);
163 continue;
164 }
165
166 if (b.reachingDef.containsKey(var)) {
167 Definition bDef = b.reachingDef.get(var);
168
169 if (aDef.equals(bDef)) {
170 resultMap.put(var, aDef);
171 } else {
172 resultMap.put(var, null);
173 }
174 } else {
175 resultMap.put(var, aDef);
176 }
177 }
178
179 // Take the join of all variables that are not TOP in other but it is TOP
180 // in this.
181 for (Map.Entry<Var, Definition> entry : b.reachingDef.entrySet()) {
182 Var var = entry.getKey();
183 if (!a.reachingDef.containsKey(var)) {
184 resultMap.put(var, entry.getValue());
185 }
186 }
187 return result;
188 }
189 }
190
191 @Override
192 boolean isForward() {
193 return true;
194 }
195
196 @Override
197 MustDef createEntryLattice() {
198 return new MustDef(jsScope.getVars());
199 }
200
201 @Override
202 MustDef createInitialEstimateLattice() {
203 return new MustDef();
204 }
205
206 @Override
207 MustDef flowThrough(Node n, MustDef input) {
208 // TODO(user): We are doing a straight copy from input to output. There
209 // might be some opportunities to cut down overhead.
210 MustDef output = new MustDef(input);
211 // TODO(user): This must know about ON_EX edges but it should handle
212 // it better than what we did in liveness. Because we are in a forward mode,
213 // we can used the branched forward analysis.
214 computeMustDef(n, n, output, false);
215 return output;
216 }
217
218 /**
219 * @param n The node in question.
220 * @param cfgNode The node to add
221 * @param conditional true if the definition is not always executed.
222 */
223 private void computeMustDef(
224 Node n, Node cfgNode, MustDef output, boolean conditional) {
225 switch (n.getType()) {
226
227 case Token.BLOCK:
228 case Token.FUNCTION:
229 return;
230
231 case Token.WHILE:
232 case Token.DO:
233 case Token.IF:
234 computeMustDef(
235 NodeUtil.getConditionExpression(n), cfgNode, output, conditional);
236 return;
237
238 case Token.FOR:
239 if (!NodeUtil.isForIn(n)) {
240 computeMustDef(
241 NodeUtil.getConditionExpression(n), cfgNode, output, conditional);
242 } else {
243 // for(x in y) {...}
244 Node lhs = n.getFirstChild();
245 Node rhs = lhs.getNext();
246 if (lhs.isVar()) {
247 lhs = lhs.getLastChild(); // for(var x in y) {...}
248 }
249 if (lhs.isName()) {
250 addToDefIfLocal(lhs.getString(), cfgNode, rhs, output);
251 }
252 }
253 return;
254
255 case Token.AND:
256 case Token.OR:
257 computeMustDef(n.getFirstChild(), cfgNode, output, conditional);
258 computeMustDef(n.getLastChild(), cfgNode, output, true);
259 return;
260
261 case Token.HOOK:
262 computeMustDef(n.getFirstChild(), cfgNode, output, conditional);
263 computeMustDef(n.getFirstChild().getNext(), cfgNode, output, true);
264 computeMustDef(n.getLastChild(), cfgNode, output, true);
265 return;
266
267 case Token.VAR:
268 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
269 if (c.hasChildren()) {
270 computeMustDef(c.getFirstChild(), cfgNode, output, conditional);
271 addToDefIfLocal(c.getString(), conditional ? null : cfgNode,
272 c.getFirstChild(), output);
273 }
274 }
275 return;
276
277 default:
278 if (NodeUtil.isAssignmentOp(n)) {
279 if (n.getFirstChild().isName()) {
280 Node name = n.getFirstChild();
281 computeMustDef(name.getNext(), cfgNode, output, conditional);
282 addToDefIfLocal(name.getString(), conditional ? null : cfgNode,
283 n.getLastChild(), output);
284 return;
285 } else if (NodeUtil.isGet(n.getFirstChild())) {
286 // Treat all assignments to arguments as redefining the
287 // parameters itself.
288 Node obj = n.getFirstChild().getFirstChild();
289 if (obj.isName() && "arguments".equals(obj.getString())) {
290 // TODO(user): More accuracy can be introduced
291 // i.e. We know exactly what arguments[x] is if x is a constant
292 // number.
293 escapeParameters(output);
294 }
295 }
296 }
297
298 if (n.isName() && "arguments".equals(n.getString())) {
299 escapeParameters(output);
300 }
301
302 // DEC and INC actually defines the variable.
303 if (n.isDec() || n.isInc()) {
304 Node target = n.getFirstChild();
305 if (target.isName()) {
306 addToDefIfLocal(target.getString(),
307 conditional ? null : cfgNode, null, output);
308 return;
309 }
310 }
311
312 for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {
313 computeMustDef(c, cfgNode, output, conditional);
314 }
315 }
316 }
317
318 /**
319 * Set the variable lattice for the given name to the node value in the def
320 * lattice. Do nothing if the variable name is one of the escaped variable.
321 *
322 * @param node The CFG node where the definition should be record to.
323 * {@code null} if this is a conditional define.
324 */
325 private void addToDefIfLocal( String name, @Nullable Node node,
326 @Nullable Node rValue, MustDef def) {
327 Var var = jsScope.getVar(name);
328
329 // var might be null because the variable might be defined in the extern
330 // that we might not traverse.
331 if (var == null || var.scope != jsScope) {
332 return;
333 }
334
335 for (Var other : def.reachingDef.keySet()) {
336 Definition otherDef = def.reachingDef.get(other);
337 if (otherDef == null) {
338 continue;
339 }
340 if (otherDef.depends.contains(var)) {
341 def.reachingDef.put(other, null);
342 }
343 }
344
345 if (!escaped.contains(var)) {
346 if (node == null) {
347 def.reachingDef.put(var, null);
348 } else {
349 Definition definition = new Definition(node);
350 if (rValue != null) {
351 computeDependence(definition, rValue);
352 }
353 def.reachingDef.put(var, definition);
354 }
355 }
356 }
357
358 private void escapeParameters(MustDef output) {
359 for (Iterator<Var> i = jsScope.getVars(); i.hasNext();) {
360 Var v = i.next();
361 if (isParameter(v)) {
362 // Assume we no longer know where the parameter comes from
363 // anymore.
364 output.reachingDef.put(v, null);
365 }
366 }
367
368 // Also, assume we no longer know anything that depends on a parameter.
369 for (Entry<Var, Definition> pair: output.reachingDef.entrySet()) {
370 Definition value = pair.getValue();
371 if (value == null) {
372 continue;
373 }
374 for (Var dep : value.depends) {
375 if (isParameter(dep)) {
376 output.reachingDef.put(pair.getKey(), null);
377 }
378 }
379 }
380 }
381
382 private boolean isParameter(Var v) {
383 return v.getParentNode().isParamList();
384 }
385
386 /**
387 * Computes all the local variables that rValue reads from and store that
388 * in the def's depends set.
389 */
390 private void computeDependence(final Definition def, Node rValue) {
391 NodeTraversal.traverse(compiler, rValue,
392 new AbstractCfgNodeTraversalCallback() {
393 @Override
394 public void visit(NodeTraversal t, Node n, Node parent) {
395 if (n.isName()) {
396 Var dep = jsScope.getVar(n.getString());
397 if (dep == null) {
398 def.unknownDependencies = true;
399 } else {
400 def.depends.add(dep);
401 }
402 }
403 }
404 });
405 }
406
407 /**
408 * Gets the must reaching definition of a given node.
409 *
410 * @param name name of the variable. It can only be names of local variable
411 * that are not function parameters, escaped variables or variables
412 * declared in catch.
413 * @param useNode the location of the use where the definition reaches.
414 */
415 Definition getDef(String name, Node useNode) {
416 Preconditions.checkArgument(getCfg().hasNode(useNode));
417 GraphNode<Node, Branch> n = getCfg().getNode(useNode);
418 FlowState<MustDef> state = n.getAnnotation();
419 return state.getIn().reachingDef.get(jsScope.getVar(name));
420 }
421
422 Node getDefNode(String name, Node useNode) {
423 Definition def = getDef(name, useNode);
424 return def == null ? null : def.node;
425 }
426
427 boolean dependsOnOuterScopeVars(Definition def) {
428 if (def.unknownDependencies) {
429 return true;
430 }
431
432 for (Var s : def.depends) {
433 if (s.scope != jsScope) {
434 return true;
435 }
436 }
437 return false;
438 }
439 }