Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2010 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.base.Predicate;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.NodeTraversal.AbstractShallowCallback;
25 import com.google.javascript.jscomp.ReferenceCollectingCallback.Reference;
26 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection;
27 import com.google.javascript.jscomp.Scope.Var;
28 import com.google.javascript.jscomp.VariableVisibilityAnalysis.VariableVisibility;
29 import com.google.javascript.rhino.Node;
30 import com.google.javascript.rhino.Token;
31
32 import java.util.ArrayList;
33 import java.util.Map;
34 import java.util.Set;
35
36 /**
37 * A pass that analyzes side effects to determine when it is safe to move
38 * code from one program point to another.
39 *
40 * In its current form, SideEffectsAnalysis is very incomplete; this is
41 * mostly a sketch to prototype the interface and the broad strokes of
42 * a possible implementation based on flow-insensitive MOD and REF sets.
43 *
44 * See:
45 *
46 * Banning, John. "An efficient way to find the side effects of procedure
47 * calls and the aliases of variables." POPL '79.
48 *
49 * For an introduction to MOD and REF sets.
50 *
51 * @author [email protected] (Devin Coughlin)
52 */
53 class SideEffectsAnalysis implements CompilerPass {
54
55 /**
56 * The type of location abstraction to use for this analysis.
57 */
58 enum LocationAbstractionMode {
59 /** See {@link DegenerateLocationAbstraction} for details. */
60 DEGENERATE,
61 /** See {@link VisibilityLocationAbstraction} for details. */
62 VISIBILITY_BASED
63 }
64
65 private static final Predicate<Node> NOT_FUNCTION_PREDICATE =
66 new Predicate<Node>() {
67 @Override
68 public boolean apply(Node input) {
69 return !input.isFunction();
70 }
71 };
72
73 private AbstractCompiler compiler;
74
75 /** The location abstraction used to calculate the effects of code */
76 private LocationAbstraction locationAbstraction;
77
78 /** The kind of location abstraction to use */
79 private final LocationAbstractionMode locationAbstractionIdentifier;
80
81 /**
82 * Constructs a new SideEffectsAnalysis with the given location abstraction.
83 *
84 * @param compiler A compiler instance
85 * @param locationAbstractionMode The location abstraction to use. {@code
86 * DEGENERATE} will use {@link DegenerateLocationAbstraction} while
87 * {@code VISIBILITY_BASED} will use {@link VisibilityLocationAbstraction}
88 *
89 */
90 public SideEffectsAnalysis(AbstractCompiler compiler,
91 LocationAbstractionMode locationAbstractionMode) {
92 this.compiler = compiler;
93
94 this.locationAbstractionIdentifier = locationAbstractionMode;
95 }
96
97 public SideEffectsAnalysis(AbstractCompiler compiler) {
98 this(compiler, LocationAbstractionMode.DEGENERATE);
99 }
100
101 @Override
102 public void process(Node externs, Node root) {
103 switch(locationAbstractionIdentifier) {
104 case DEGENERATE:
105 locationAbstraction = new DegenerateLocationAbstraction();
106 break;
107 case VISIBILITY_BASED:
108 locationAbstraction = createVisibilityAbstraction(externs, root);
109 break;
110 default:
111 throw new IllegalStateException("Unrecognized location abstraction " +
112 "identifier: " + locationAbstractionIdentifier);
113 }
114
115 // In the future, this method
116 // will construct a callgraph and calculate side effects summaries
117 // for all functions.
118 // TODO(dcc): Add per-function side effects summaries.
119 }
120
121 private LocationAbstraction createVisibilityAbstraction(Node externs,
122 Node root) {
123 VariableVisibilityAnalysis variableVisibility =
124 new VariableVisibilityAnalysis(compiler);
125
126 variableVisibility.process(externs, root);
127
128 VariableUseDeclarationMap variableMap =
129 new VariableUseDeclarationMap(compiler);
130
131 variableMap.mapUses(root);
132
133 return new VisibilityLocationAbstraction(compiler,
134 variableVisibility, variableMap);
135 }
136
137 /**
138 * Determines whether it is safe to move code ({@code source}) across
139 * an environment to another program point (immediately preceding
140 * {@code destination}).
141 *
142 * <p>The notion of "environment" is optimization-specific, but it should
143 * include any code that could be executed between the source program point
144 * and the destination program point.
145 *
146 * {@code destination} must not be a descendant of {@code source}.
147 *
148 * @param source The node that would be moved
149 * @param environment An environment representing the code across which
150 * the source will be moved.
151 * @param destination The node before which the source would be moved
152 * @return Whether it is safe to move the source to the destination
153 */
154 public boolean safeToMoveBefore(Node source,
155 AbstractMotionEnvironment environment,
156 Node destination) {
157 Preconditions.checkNotNull(locationAbstraction);
158 Preconditions.checkArgument(!nodeHasAncestor(destination, source));
159
160 // It is always safe to move pure code.
161 if (isPure(source)) {
162 return true;
163 }
164
165 // Don't currently support interprocedural analysis
166 if (nodeHasCall(source)) {
167 return false;
168 }
169
170 LocationSummary sourceLocationSummary =
171 locationAbstraction.calculateLocationSummary(source);
172
173 EffectLocation sourceModSet = sourceLocationSummary.getModSet();
174
175 // If the source has side effects, then we require that the source
176 // is executed exactly as many times as the destination.
177 if (!sourceModSet.isEmpty() &&
178 !nodesHaveSameControlFlow(source, destination)) {
179 return false;
180 }
181
182 EffectLocation sourceRefSet = sourceLocationSummary.getRefSet();
183
184 Set<Node> environmentNodes = environment.calculateEnvironment();
185
186 for (Node environmentNode : environmentNodes) {
187 if (nodeHasCall(environmentNode)) {
188 return false;
189 }
190 }
191
192 LocationSummary environmentLocationSummary =
193 locationAbstraction.calculateLocationSummary(environmentNodes);
194
195 EffectLocation environmentModSet = environmentLocationSummary.getModSet();
196
197 EffectLocation environmentRefSet = environmentLocationSummary.getRefSet();
198
199 // If MOD(environment) intersects REF(source) then moving the
200 // source across the environment could cause the source
201 // to read an incorrect value.
202 // If REF(environment) intersects MOD(source) then moving the
203 // source across the environment could cause the environment
204 // to read an incorrect value.
205 // If MOD(environment) intersects MOD(source) then moving the
206 // source across the environment could cause some later code that reads
207 // a modified location to get an incorrect value.
208
209 if (!environmentModSet.intersectsLocation(sourceRefSet)
210 && !environmentRefSet.intersectsLocation(sourceModSet)
211 && !environmentModSet.intersectsLocation(sourceModSet)) {
212 return true;
213 }
214
215 return false;
216 }
217
218 /**
219 * Returns true if the node is pure, that is it side effect free and does it
220 * not depend on its environment?
221 * @param node node to check.
222 */
223 private boolean isPure(Node node) {
224 // For now, we conservatively assume all code is not pure.
225 // TODO(dcc): Implement isPure().
226 return false;
227 }
228
229 /**
230 * Returns true if the two nodes have the same control flow properties,
231 * that is, is node1 be executed every time node2 is executed and vice versa?
232 */
233 private static boolean nodesHaveSameControlFlow(Node node1, Node node2) {
234 /*
235 * We conservatively approximate this with the following criteria:
236 *
237 * Define the "deepest control dependent block" for a node to be the
238 * closest ancestor whose *parent* is a control structure and where that
239 * ancestor may or may be executed depending on the parent.
240 *
241 * So, for example, in:
242 * if (a) {
243 * b;
244 * } else {
245 * c;
246 * }
247 *
248 * a has not deepest control dependent block.
249 * b's deepest control dependent block is the "then" block of the IF.
250 * c's deepest control dependent block is the "else" block of the IF.
251 *
252 * We'll say two nodes have the same control flow if
253 *
254 * 1) they have the same deepest control dependent block
255 * 2) that block is either a CASE (which can't have early exits) or it
256 * doesn't have any early exits (e.g. breaks, continues, returns.)
257 *
258 */
259
260 Node node1DeepestControlDependentBlock =
261 closestControlDependentAncestor(node1);
262
263 Node node2DeepestControlDependentBlock =
264 closestControlDependentAncestor(node2);
265
266 if (node1DeepestControlDependentBlock ==
267 node2DeepestControlDependentBlock) {
268
269 if (node2DeepestControlDependentBlock != null) {
270 // CASE is complicated because we have to deal with fall through and
271 // because some BREAKs are early exits and some are not.
272 // For now, we don't allow movement within a CASE.
273 //
274 // TODO(dcc): be less conservative about movement within CASE
275 if (node2DeepestControlDependentBlock.isCase()) {
276 return false;
277 }
278
279 // Don't allow breaks, continues, returns in control dependent
280 // block because we don't actually create a control-flow graph
281 // and so don't know if early exits site between the source
282 // and the destination.
283 //
284 // This is overly conservative as it doesn't allow, for example,
285 // moving in the following case:
286 // while (a) {
287 // source();
288 //
289 // while(b) {
290 // break;
291 // }
292 //
293 // destination();
294 // }
295 //
296 // To fully support this kind of movement, we'll probably have to use
297 // a CFG-based analysis rather than just looking at the AST.
298 //
299 // TODO(dcc): have nodesHaveSameControlFlow() use a CFG
300 Predicate<Node> isEarlyExitPredicate = new Predicate<Node>() {
301 @Override
302 public boolean apply(Node input) {
303 int nodeType = input.getType();
304
305 return nodeType == Token.RETURN
306 || nodeType == Token.BREAK
307 || nodeType == Token.CONTINUE;
308 }
309 };
310
311 return !NodeUtil.has(node2DeepestControlDependentBlock,
312 isEarlyExitPredicate, NOT_FUNCTION_PREDICATE);
313 } else {
314 return true;
315 }
316 } else {
317 return false;
318 }
319 }
320
321 /**
322 * Returns true if the number of times the child executes depends on the
323 * parent.
324 *
325 * For example, the guard of an IF is not control dependent on the
326 * IF, but its two THEN/ELSE blocks are.
327 *
328 * Also, the guard of WHILE and DO are control dependent on the parent
329 * since the number of times it executes depends on the parent.
330 */
331 private static boolean isControlDependentChild(Node child) {
332 Node parent = child.getParent();
333
334 if (parent == null) {
335 return false;
336 }
337
338 ArrayList<Node> siblings = Lists.newArrayList(parent.children());
339
340 int indexOfChildInParent = siblings.indexOf(child);
341
342 switch(parent.getType()) {
343 case Token.IF:
344 case Token.HOOK:
345 return (indexOfChildInParent == 1 || indexOfChildInParent == 2);
346 case Token.WHILE:
347 case Token.DO:
348 return true;
349 case Token.FOR:
350 // Only initializer is not control dependent
351 return indexOfChildInParent != 0;
352 case Token.SWITCH:
353 return indexOfChildInParent > 0;
354 case Token.AND:
355 return true;
356 case Token.OR:
357 return true;
358 case Token.FUNCTION:
359 return true;
360
361 default:
362 return false;
363 }
364 }
365
366 private static Node closestControlDependentAncestor(Node node) {
367 if (isControlDependentChild(node)) {
368 return node;
369 }
370
371 // Note: node is not considered one of its ancestors
372 for (Node ancestor : node.getAncestors()) {
373 if (isControlDependentChild(ancestor)) {
374 return ancestor;
375 }
376 }
377
378 return null;
379 }
380
381 /**
382 * Returns true if {@code possibleAncestor} is an ancestor of{@code node}.
383 * A node is not considered to be an ancestor of itself.
384 */
385 private static boolean nodeHasAncestor(Node node, Node possibleAncestor) {
386 // Note node is not in node.getAncestors()
387
388 for (Node ancestor : node.getAncestors()) {
389 if (ancestor == possibleAncestor) {
390 return true;
391 }
392 }
393
394 return false;
395 }
396
397 /**
398 * Returns true if a node has a CALL or a NEW descendant.
399 */
400 private boolean nodeHasCall(Node node) {
401 return NodeUtil.has(node, new Predicate<Node>() {
402 @Override
403 public boolean apply(Node input) {
404 return input.isCall() || input.isNew();
405 }},
406 NOT_FUNCTION_PREDICATE);
407 }
408
409 /**
410 * Represents an environment across which code might be moved, i.e. the set
411 * of code that could be run in between the source and the destination.
412 *
413 * SideEffectAnalysis characterizes the code to be moved and the environment
414 * in order to determine if they interact in such a way as to make the move
415 * unsafe.
416 *
417 * Since determining the environment for an optimization can be tricky,
418 * we provide several concrete subclasses that common classes of optimizations
419 * may be able to reuse.
420 */
421 public abstract static class AbstractMotionEnvironment {
422
423 /**
424 * Calculates the set of nodes that this environment represents.
425 */
426 public abstract Set<Node> calculateEnvironment();
427 }
428
429 /**
430 * An environment for motion within a function. Given a
431 * control flow graph and a source and destination node in the control
432 * flow graph, instances of this object will calculate the environment between
433 * the source and destination.
434 */
435 public static class IntraproceduralMotionEnvironment
436 extends AbstractMotionEnvironment {
437
438 /**
439 * Creates an intraprocedural motion environment.
440 *
441 * @param controlFlowGraph A control flow graph for function in which
442 * code will be moved
443 * @param cfgSource The code to be moved
444 * @param cfgDestination The node immediately before which cfgSource
445 * will be moved
446 */
447 public IntraproceduralMotionEnvironment(
448 ControlFlowGraph<Node> controlFlowGraph,
449 Node cfgSource,
450 Node cfgDestination) {
451
452 }
453
454 @Override
455 public Set<Node> calculateEnvironment() {
456 // TODO(dcc): Implement IntraproceduralMotionEnvironment
457 return null;
458 }
459 }
460
461 /**
462 * An environment for motion between modules. Given a
463 * module graph and as well as source and destination nodes and modules,
464 * instances of this object will calculate the environment between the source
465 * and destination.
466 */
467 public static class CrossModuleMotionEnvironment
468 extends AbstractMotionEnvironment {
469
470 /**
471 * Creates a cross module code motion environment.
472 *
473 * @param sourceNode The code to be moved
474 * @param sourceModule The module for the code to be moved
475 * @param destinationNode The node before which sourceNode will be inserted
476 * @param destinationModule The module that destination is in
477 * @param moduleGraph The module graph of the entire program
478 */
479 public CrossModuleMotionEnvironment(Node sourceNode,
480 JSModule sourceModule,
481 Node destinationNode,
482 JSModule destinationModule,
483 JSModuleGraph moduleGraph) {
484
485 }
486
487 @Override
488 public Set<Node> calculateEnvironment() {
489 // TODO(dcc): Implement CrossModuleMotionEnvironment
490 return null;
491 }
492 }
493 /**
494 * A low-level concrete environment that allows the client to specify
495 * the environment nodes directly. Clients may wish to use this environment
496 * if none of the higher-level environments fit their needs.
497 */
498 public static class RawMotionEnvironment
499 extends AbstractMotionEnvironment {
500 Set<Node> environment;
501
502 public RawMotionEnvironment(Set<Node> environment) {
503 this.environment = environment;
504 }
505
506 @Override
507 public Set<Node> calculateEnvironment() {
508 return environment;
509 }
510 }
511
512 /*
513 * A combined representation for location set summaries.
514 *
515 * Basically, it is often easier to shuffle MOD/REF around together; this is
516 * a value class for that purpose.
517 */
518 private static class LocationSummary {
519
520 private EffectLocation modSet;
521 private EffectLocation refSet;
522
523 public LocationSummary(EffectLocation modSet, EffectLocation refSet) {
524 this.modSet = modSet;
525 this.refSet = refSet;
526 }
527
528 public EffectLocation getModSet() {
529 return modSet;
530 }
531
532 public EffectLocation getRefSet() {
533 return refSet;
534 }
535 }
536
537 /**
538 * Interface representing the notion of an effect location -- an abstract
539 * location that can be modified or referenced.
540 *
541 * <p>Since there are an infinite number of possible concrete locations
542 * in a running program, this abstraction must be imprecise (i.e. there
543 * will be some distinct concrete locations that are indistinguishable
544 * under the abstraction).
545 *
546 * <p>Different location abstractions will provide their
547 * own implementations of this interface, based on the level and kind
548 * of precision they provide.
549 */
550 private static interface EffectLocation {
551
552 /**
553 * Does the receiver's effect location intersect a given effect location?
554 * That is, could any of the concrete storage locations (fields, variables,
555 * etc.) represented by the receiver be contained in the set of concrete
556 * storage locations represented by the given abstract effect location.
557 */
558 public boolean intersectsLocation(EffectLocation otherLocation);
559
560 /**
561 * Returns the result of merging the given effect location with
562 * the receiver. The concrete locations represented by the result must
563 * include all the concrete locations represented by each of the merged
564 * locations and may also possibly include more (i.e., a join may
565 * introduce a loss of precision).
566 */
567 public EffectLocation join(EffectLocation otherLocation);
568
569 /**
570 * Does the effect location represent any possible concrete locations?
571 */
572 public boolean isEmpty();
573 }
574
575 /**
576 * An abstract class representing a location abstraction. (Here "abstraction"
577 * means an imprecise representation of concrete side effects.)
578 *
579 * <p>Implementations of this class will each provide own their
580 * implementation(s) of SideEffectLocation and methods to determine the side
581 * effect locations of a given piece of code.
582 */
583 private abstract static class LocationAbstraction {
584
585 /** Calculates the abstraction-specific side effects
586 * for the node.
587 */
588 abstract LocationSummary calculateLocationSummary(Node node);
589
590 /**
591 * Returns an abstraction-specific EffectLocation representing
592 * no location.
593 *
594 * <p>The bottom location joined with any location should return
595 * that location.
596 */
597 abstract EffectLocation getBottomLocation();
598
599 /**
600 * Calculates the abstraction-specific side effects
601 * for the node.
602 */
603 public LocationSummary calculateLocationSummary(Set<Node> nodes) {
604 EffectLocation modAccumulator = getBottomLocation();
605 EffectLocation refAccumulator = getBottomLocation();
606
607 for (Node node : nodes) {
608 LocationSummary nodeLocationSummary = calculateLocationSummary(node);
609
610 modAccumulator = modAccumulator.join(nodeLocationSummary.getModSet());
611 refAccumulator = refAccumulator.join(nodeLocationSummary.getRefSet());
612 }
613
614 return new LocationSummary(modAccumulator, refAccumulator);
615 }
616 }
617 /**
618 * A very imprecise location abstraction in which there are only two abstract
619 * locations: one representing all concrete locations and one for bottom
620 * (no concrete locations).
621 *
622 * This implementation is a thin wrapper on NodeUtil.mayHaveSideEffects()
623 * and NodeUtil.canBeSideEffected() -- it doesn't add any real value other
624 * than to prototype the LocationAbstraction interface.
625 */
626 private static class DegenerateLocationAbstraction
627 extends LocationAbstraction {
628
629 private static final EffectLocation EVERY_LOCATION =
630 new DegenerateEffectLocation();
631
632 private static final EffectLocation NO_LOCATION =
633 new DegenerateEffectLocation();
634
635 @Override
636 EffectLocation getBottomLocation() {
637 return NO_LOCATION;
638 }
639
640 @Override
641 public LocationSummary calculateLocationSummary(Node node) {
642 return new LocationSummary(calculateModSet(node), calculateRefSet(node));
643 }
644
645 EffectLocation calculateRefSet(Node node) {
646 if (NodeUtil.canBeSideEffected(node)) {
647 return EVERY_LOCATION;
648 } else {
649 return NO_LOCATION;
650 }
651 }
652
653 EffectLocation calculateModSet(Node node) {
654 if (NodeUtil.mayHaveSideEffects(node)) {
655 return EVERY_LOCATION;
656 } else {
657 return NO_LOCATION;
658 }
659 }
660
661 private static class DegenerateEffectLocation implements EffectLocation {
662 @Override
663 public EffectLocation join(EffectLocation otherLocation) {
664 if (otherLocation == EVERY_LOCATION) {
665 return otherLocation;
666 } else {
667 return this;
668 }
669 }
670
671 @Override
672 public boolean intersectsLocation(EffectLocation otherLocation) {
673 return this == EVERY_LOCATION && otherLocation == EVERY_LOCATION;
674 }
675
676 @Override
677 public boolean isEmpty() {
678 return this == NO_LOCATION;
679 }
680 }
681 }
682
683 /**
684 * A location abstraction based on the visibility of concrete locations.
685 *
686 * A global variables are treated as one common location, as are all heap
687 * storage locations.
688 *
689 * Local variables are broken up into two classes, one for truly local
690 * variables and one for local variables captured by an inner scope. Each
691 * of these classes has their own separate location representing the
692 * variables in the class.
693 *
694 * Parameter variables are considered to be heap locations since they
695 * can be accessed via the arguments object which itself can be aliased.
696 *
697 * A more precise analysis could:
698 * 1) put parameters on the heap only when "arguments" is actually used
699 * in a method
700 * 2) recognize that GETPROPs cannot access or modify parameters, only
701 * GETELEMs
702 *
703 * TODO(dcc): Don't merge parameters with the heap unless necessary.
704 *
705 * Internally, abstract locations are represented as integers
706 * with bits set (masks) representing the storage classes in the location, so
707 * that joining is bit-wise ORing and intersection is bitwise AND.
708 */
709 private static class VisibilityLocationAbstraction
710 extends LocationAbstraction {
711
712 /** The "bottom" location. Used to signify an empty location set */
713 private static final int VISIBILITY_LOCATION_NONE = 0;
714
715 /** The "top" location. Used to signify the set containing all locations */
716 private static final int UNKNOWN_LOCATION_MASK = 0xFFFFFFFF;
717
718 private static final int LOCAL_VARIABLE_LOCATION_MASK = 1 << 1;
719
720 private static final int CAPTURED_LOCAL_VARIABLE_LOCATION_MASK = 1 << 2;
721
722 private static final int GLOBAL_VARIABLE_LOCATION_MASK = 1 << 3;
723
724 private static final int HEAP_LOCATION_MASK = 1 << 4;
725
726 AbstractCompiler compiler;
727
728 VariableVisibilityAnalysis variableVisibilityAnalysis;
729 VariableUseDeclarationMap variableUseMap;
730
731 private VisibilityLocationAbstraction(AbstractCompiler compiler,
732 VariableVisibilityAnalysis variableVisibilityAnalysis,
733 VariableUseDeclarationMap variableUseMap) {
734 this.compiler = compiler;
735 this.variableVisibilityAnalysis = variableVisibilityAnalysis;
736 this.variableUseMap = variableUseMap;
737 }
738
739 /**
740 * Calculates the MOD/REF summary for the given node.
741 */
742 @Override
743 LocationSummary calculateLocationSummary(Node node) {
744 int visibilityRefLocations = VISIBILITY_LOCATION_NONE;
745 int visibilityModLocations = VISIBILITY_LOCATION_NONE;
746
747 for (Node reference : findStorageLocationReferences(node)) {
748 int effectMask;
749
750 if (reference.isName()) {
751 // Variable access
752 effectMask = effectMaskForVariableReference(reference);
753 } else {
754 // Heap access
755 effectMask = HEAP_LOCATION_MASK;
756 }
757
758 if (storageNodeIsLValue(reference)) {
759 visibilityModLocations |= effectMask;
760 }
761
762 if (storageNodeIsRValue(reference)) {
763 visibilityRefLocations |= effectMask;
764 }
765 }
766
767 VisibilityBasedEffectLocation modSet =
768 new VisibilityBasedEffectLocation(visibilityModLocations);
769
770 VisibilityBasedEffectLocation refSet =
771 new VisibilityBasedEffectLocation(visibilityRefLocations);
772
773 return new LocationSummary(modSet, refSet);
774 }
775
776 /**
777 * Returns the set of references to storage locations (both variables
778 * and the heap) under {@code root}.
779 */
780 private Set<Node> findStorageLocationReferences(Node root) {
781 final Set<Node> references = Sets.newHashSet();
782
783 NodeTraversal.traverse(compiler, root, new AbstractShallowCallback() {
784 @Override
785 public void visit(NodeTraversal t, Node n, Node parent) {
786 if (NodeUtil.isGet(n)
787 || (n.isName() && !parent.isFunction())) {
788 references.add(n);
789 }
790 }
791 });
792
793 return references;
794 }
795
796 /**
797 * Calculates the effect mask for a variable reference.
798 */
799 private int effectMaskForVariableReference(Node variableReference) {
800 Preconditions.checkArgument(variableReference.isName());
801
802 int effectMask = VISIBILITY_LOCATION_NONE;
803
804 Node declaringNameNode =
805 variableUseMap.findDeclaringNameNodeForUse(variableReference);
806
807 if (declaringNameNode != null) {
808 VariableVisibility visibility =
809 variableVisibilityAnalysis.getVariableVisibility(declaringNameNode);
810
811 switch (visibility) {
812 case LOCAL:
813 effectMask = LOCAL_VARIABLE_LOCATION_MASK;
814 break;
815 case CAPTURED_LOCAL:
816 effectMask = CAPTURED_LOCAL_VARIABLE_LOCATION_MASK;
817 break;
818 case PARAMETER:
819 // Parameters are considered to be on the heap since they
820 // can be accessed via the arguments object.
821 effectMask = HEAP_LOCATION_MASK;
822 break;
823 case GLOBAL:
824 effectMask = GLOBAL_VARIABLE_LOCATION_MASK;
825 break;
826 default:
827 throw new IllegalStateException("Unrecognized variable" +
828 " visibility: " + visibility);
829 }
830 } else {
831 // Couldn't find a variable for the reference
832 effectMask = UNKNOWN_LOCATION_MASK;
833 }
834
835 return effectMask;
836 }
837
838 @Override
839 EffectLocation getBottomLocation() {
840 return new VisibilityBasedEffectLocation(VISIBILITY_LOCATION_NONE);
841 }
842
843 /**
844 * Returns true if the node is a storage node.
845 *
846 * Only NAMEs, GETPROPs, and GETELEMs are storage nodes.
847 */
848 private static boolean isStorageNode(Node node) {
849 return node.isName() || NodeUtil.isGet(node);
850 }
851
852 /**
853 * Return true if the storage node is an r-value.
854 */
855 private static boolean storageNodeIsRValue(Node node) {
856 Preconditions.checkArgument(isStorageNode(node));
857
858 // We consider all names to be r-values unless
859 // LHS of Token.ASSIGN
860 // LHS of of for in expression
861 // Child of VAR
862
863 Node parent = node.getParent();
864
865 if (storageNodeIsLValue(node)) {
866 // Assume l-value is NOT an r-value
867 // unless it is a non-simple assign
868 // or an increment/decrement
869
870 boolean nonSimpleAssign =
871 NodeUtil.isAssignmentOp(parent) && !parent.isAssign();
872
873 return (nonSimpleAssign
874 || parent.isDec()
875 || parent.isInc());
876 }
877
878 return true;
879 }
880
881 /**
882 * Return true if the storage node is an l-value.
883 */
884 private static boolean storageNodeIsLValue(Node node) {
885 Preconditions.checkArgument(isStorageNode(node));
886 return NodeUtil.isLValue(node);
887 }
888
889 /**
890 * An abstract effect location based the visibility of the
891 * concrete storage location.
892 *
893 * See {@link VisibilityLocationAbstraction} for deeper description
894 * of this abstraction.
895 *
896 * The effect locations are stored as bits set on an integer, so
897 * intersect, join, etc. are the standard bitwise operations.
898 */
899 private static class VisibilityBasedEffectLocation
900 implements EffectLocation {
901 int visibilityMask = VISIBILITY_LOCATION_NONE;
902
903 public VisibilityBasedEffectLocation(int visibilityMask) {
904 this.visibilityMask = visibilityMask;
905 }
906
907 @Override
908 public boolean intersectsLocation(EffectLocation otherLocation) {
909 Preconditions.checkArgument(otherLocation instanceof
910 VisibilityBasedEffectLocation);
911
912 int otherMask =
913 ((VisibilityBasedEffectLocation) otherLocation).visibilityMask;
914
915 return (visibilityMask & otherMask) > 0;
916 }
917
918 @Override
919 public boolean isEmpty() {
920 return visibilityMask == VISIBILITY_LOCATION_NONE;
921 }
922
923 @Override
924 public EffectLocation join(EffectLocation otherLocation) {
925 Preconditions.checkArgument(otherLocation instanceof
926 VisibilityBasedEffectLocation);
927
928 int otherMask =
929 ((VisibilityBasedEffectLocation) otherLocation).visibilityMask;
930
931 int joinedMask = visibilityMask | otherMask;
932
933 return new VisibilityBasedEffectLocation(joinedMask);
934 }
935 }
936 }
937
938 /**
939 * Maps NAME nodes that refer to variables to the NAME
940 * nodes that declared them.
941 */
942 private static class VariableUseDeclarationMap {
943
944 private AbstractCompiler compiler;
945
946 // Maps a using name to its declaring name
947 private Map<Node, Node> referencesByNameNode;
948
949 public VariableUseDeclarationMap(AbstractCompiler compiler) {
950 this.compiler = compiler;
951 }
952
953 /**
954 * Adds a map from each use NAME in {@code root} to its corresponding
955 * declaring name, *provided the declaration is also under root*.
956 *
957 * If the declaration is not under root, then the reference will
958 * not be added to the map.
959 */
960 public void mapUses(Node root) {
961 referencesByNameNode = Maps.newHashMap();
962
963 ReferenceCollectingCallback callback =
964 new ReferenceCollectingCallback(compiler,
965 ReferenceCollectingCallback.DO_NOTHING_BEHAVIOR);
966
967 NodeTraversal.traverse(compiler, root, callback);
968
969 for (Var variable : callback.getAllSymbols()) {
970 ReferenceCollection referenceCollection =
971 callback.getReferences(variable);
972
973 for (Reference reference : referenceCollection.references) {
974 Node referenceNameNode = reference.getNode();
975
976 // Note that this counts a declaration as a reference to itself
977 referencesByNameNode.put(referenceNameNode, variable.getNameNode());
978 }
979 }
980 }
981
982 /**
983 * Returns the NAME node for the declaration of the variable
984 * that {@code usingNameNode} refers to, if it is in the map,
985 * or {@code null} otherwise.
986 */
987 public Node findDeclaringNameNodeForUse(Node usingNameNode) {
988 Preconditions.checkArgument(usingNameNode.isName());
989
990 return referencesByNameNode.get(usingNameNode);
991 }
992 }
993 }