Debian Codegraph @

src/com/google/javascript/jscomp/SpecializeModule.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.collect.Lists;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.Node;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30
31 /**
32 * Beginnings of an optimization to specialize the initial module at the cost of
33 * increasing code in later modules. This is still very experimental.
34 *
35 * High-level overview:
36 *
37 * This optimization replaces functions in the initial module with specialized
38 * versions that are only safe in the initial module. The original, general,
39 * versions of the functions are "fixed up" in later modules. This optimization
40 * can shrink the initial module significantly but the fixup code in later
41 * modules increases overall code size.
42 *
43 * Implementation approach:
44 *
45 * We take a ridiculously naive approach: remove the initial module
46 * from the rest of the AST, optimize it with existing optimization passes
47 * (recording which functions have been specialized), put it back in the AST,
48 * and add fixups restoring the general versions of the functions in each module
49 * that depends on the initial module.
50 *
51 * Since it is only safe to specialize functions that can be fixed up, we
52 * don't allow specialization of local functions and functions that
53 * are aliased.
54 *
55 * We currently run three optimizations on the isolated AST: InlineFunctions,
56 * DevirtualizePrototypeMethods, and RemoveUnusedPrototypeProperties.
57 *
58 * These optimizations rely on a coarse-grained name-based analysis to
59 * maintain safety properties and thus are likely to see some benefit when
60 * applied in isolation.
61 *
62 * InlineFunctions is truly specializing -- it replaces functions with
63 * versions that have calls to other functions inlined into them, while
64 * RemoveUnusedPrototypeProperties is really just removing properties that
65 * aren't used in the initial module and adding copies further down in the
66 * module graph. It would probably be more elegant to give
67 * CrossModuleMethodMotion permission to make copies of methods instead.
68 *
69 * There are additional passes that might benefit from being made
70 * specialization-aware:
71 *
72 * - OptimizeParameters
73 *
74 * - Any pass that is too slow to run over the entire AST but might
75 * be acceptable on only the initial module:
76 * - RemoveUnusedNames
77 *
78 * - Also, any pass that uses the results of PureFunctionIdentifier to
79 * determine when it is safe to remove code might benefit (e.g. the peephole
80 * passes), since PureFunctionIdentifier relies on SimpleDefinitionFinder,
81 * which would be more precise when running on only the initial module.
82 *
83 * @author [email protected] (Devin Coughlin)
84 */
85 class SpecializeModule implements CompilerPass {
86 private AbstractCompiler compiler;
87
88 private Map<Node, Node> specializedInputRootsByOriginal;
89
90 private Map<Node, OriginalFunctionInformation>
91 functionInfoBySpecializedFunctionNode;
92
93 private SpecializationState specializationState;
94
95 private final PassFactory[] specializationPassFactories;
96
97 public SpecializeModule(AbstractCompiler compiler,
98 PassFactory ...specializationPassFactories) {
99 this.compiler = compiler;
100 this.specializationPassFactories = specializationPassFactories;
101 }
102
103 /**
104 * Performs initial module specialization.
105 *
106 * The process is as follows:
107 *
108 * 1) Make a copy of each of the inputs in the initial root and put them
109 * in a fake AST that looks like it is the whole program.
110 *
111 * 2) Run the specializing compiler passes over the fake initial module AST
112 * until it reaches a fixed point, recording which functions are specialized
113 * or removed.
114 *
115 * 3) Replace the original input roots with the specialized input roots
116 *
117 * 4) For each module that directly depends on the initial module, add
118 * fixups for the specialized and removed functions. Right now we add
119 * fixups for for every function that was specialized or removed -- we could
120 * be smarter about this and for each dependent module only add the functions
121 * that it needs.
122 *
123 * 5) Add dummy variables declaring the removed function to the end of
124 * the now-specialized initial module. This is needed to keep
125 * {@link VarCheck} from complaining.
126 */
127 @Override
128 public void process(Node externs, Node root) {
129 JSModuleGraph moduleGraph = compiler.getModuleGraph();
130
131 // Can't perform optimization without a module graph!
132 if (moduleGraph == null) {
133 return;
134 }
135
136 JSModule module = moduleGraph.getRootModule();
137
138 Node fakeModuleRoot = copyModuleInputs(module);
139
140 SimpleDefinitionFinder defFinder = new SimpleDefinitionFinder(compiler);
141
142 defFinder.process(externs, fakeModuleRoot);
143
144 SimpleFunctionAliasAnalysis initialModuleFunctionAliasAnalysis =
145 new SimpleFunctionAliasAnalysis();
146
147 initialModuleFunctionAliasAnalysis.analyze(defFinder);
148
149 specializationState =
150 new SpecializationState(initialModuleFunctionAliasAnalysis);
151
152 do {
153 specializationState.resetHasChanged();
154
155 for (SpecializationAwareCompilerPass pass : createSpecializingPasses()) {
156 pass.enableSpecialization(specializationState);
157 pass.process(externs, fakeModuleRoot);
158 }
159 } while(specializationState.hasChanged());
160
161 // We must always add dummy variables before replacing the original module.
162 addDummyVarDeclarationsToInitialModule(module);
163 replaceOriginalModuleInputsWithSpecialized();
164 addOriginalFunctionVersionsToDependentModules(module);
165 }
166
167 /**
168 * Returns a collection of new instances of specializing passes.
169 */
170 private Collection<SpecializationAwareCompilerPass>
171 createSpecializingPasses() {
172
173 Collection<SpecializationAwareCompilerPass> passes = Lists.newLinkedList();
174
175 for (PassFactory passFactory : specializationPassFactories) {
176 CompilerPass pass = passFactory.create(compiler);
177
178 Preconditions.checkState(pass instanceof
179 SpecializationAwareCompilerPass);
180
181 passes.add((SpecializationAwareCompilerPass) pass);
182 }
183
184 return passes;
185 }
186
187 /**
188 * Creates an AST that consists solely of copies of the input roots for the
189 * passed in module.
190 *
191 * Also records a map in {@link #functionInfoBySpecializedFunctionNode}
192 * of information about the original function keyed on the copies of the
193 * functions to specialized.
194 */
195 private Node copyModuleInputs(JSModule module) {
196
197 specializedInputRootsByOriginal = Maps.newLinkedHashMap();
198
199 functionInfoBySpecializedFunctionNode = Maps.newLinkedHashMap();
200
201 Node syntheticModuleJsRoot = IR.block();
202 syntheticModuleJsRoot.setIsSyntheticBlock(true);
203
204 for (CompilerInput input : module.getInputs()) {
205 Node originalInputRoot = input.getAstRoot(compiler);
206
207 Node copiedInputRoot = originalInputRoot.cloneTree();
208 copiedInputRoot.copyInformationFromForTree(originalInputRoot);
209
210 specializedInputRootsByOriginal.put(originalInputRoot,
211 copiedInputRoot);
212
213 matchTopLevelFunctions(originalInputRoot, copiedInputRoot);
214
215 syntheticModuleJsRoot.addChildToBack(copiedInputRoot);
216 }
217
218 // The jsRoot needs a parent (in a normal compilation this would be the
219 // node that contains jsRoot and the externs).
220 Node syntheticExternsAndJsRoot = IR.block();
221 syntheticExternsAndJsRoot.addChildToBack(syntheticModuleJsRoot);
222
223 return syntheticModuleJsRoot;
224 }
225
226 /**
227 * Records information about original functions and creates a map from
228 * the specialized functions to this information.
229 *
230 * This information is only recorded for global functions since non-global
231 * functions cannot be inlined.
232 *
233 * @param original An original input root.
234 * @param toBeSpecialized A copy of the input root (the copy to be
235 * specialized)
236 */
237 private void matchTopLevelFunctions(Node original, Node toBeSpecialized) {
238 new NodeMatcher() {
239 @Override
240 public void reportMatch(Node original, Node specialized) {
241 if (original.isFunction()) {
242 OriginalFunctionInformation functionInfo =
243 new OriginalFunctionInformation(original);
244
245 functionInfoBySpecializedFunctionNode.put(specialized,
246 functionInfo);
247 }
248 }
249
250 @Override
251 public boolean shouldTraverse(Node n1, Node n2) {
252 return !n1.isFunction();
253 }
254 }.match(original, toBeSpecialized);
255 }
256
257 /**
258 * Replaces the original input roots of the initial module with
259 * their specialized versions.
260 *
261 * (Since {@link JsAst} holds a pointer to original inputs roots, we actually
262 * replace the all the children of the root rather than swapping the
263 * root pointers).
264 */
265 private void replaceOriginalModuleInputsWithSpecialized() {
266 for (Node original : specializedInputRootsByOriginal.keySet()) {
267 Node specialized = specializedInputRootsByOriginal.get(original);
268
269 original.removeChildren();
270
271 while (specialized.getFirstChild() != null) {
272 original.addChildToBack(specialized.removeFirstChild());
273 }
274 }
275 }
276
277 /**
278 * Adds dummy variable declarations for all the function declarations we've
279 * removed to the end of the initial module.
280 *
281 * We do this to make {@link VarCheck} happy, since it requires variables to
282 * be declared before they are used in the whole program AST and doesn't
283 * like it when they are declared multiple times.
284 *
285 * TODO(dcc): Be smarter about whether we need a VAR here or not.
286 */
287 private void addDummyVarDeclarationsToInitialModule(JSModule module) {
288 for (Node modifiedFunction :
289 functionInfoBySpecializedFunctionNode.keySet()) {
290 if (specializationState.getRemovedFunctions().contains(modifiedFunction)) {
291 OriginalFunctionInformation originalInfo =
292 functionInfoBySpecializedFunctionNode.get(modifiedFunction);
293
294 if (originalInfo.name != null && originalInfo.originalWasDeclaration()) {
295 Node block = specializationState.removedFunctionToBlock.get(
296 modifiedFunction);
297
298 // Declaring block might be null if no fix-up declarations is needed.
299 // For example, InlineFunction can inline an anonymous function call or
300 // anything with prototype property requires no dummy declaration
301 // fix-ups afterward.
302 if (block != null) {
303 block.addChildrenToBack(originalInfo.generateDummyDeclaration());
304 }
305 }
306 }
307 }
308 }
309
310 /**
311 * Adds a copy of the original versions of specialized/removed functions
312 * to each of the dependents of module.
313 *
314 * Currently we add all of these functions to all dependents; it
315 * would be more efficient to only add the functions that could be used.
316 *
317 * TODO(dcc): Only add fixup functions where needed.
318 */
319 private void addOriginalFunctionVersionsToDependentModules(JSModule module) {
320 for (JSModule directDependent : getDirectDependents(module)) {
321 CompilerInput firstInput = directDependent.getInputs().get(0);
322 Node firstInputRootNode = firstInput.getAstRoot(compiler);
323
324 // We don't iterate specializedFunctions directly because want to maintain
325 // and specializedFunctions in source order, rather than
326 // in the order that some optimization specialized the function.
327
328 // So since we're adding to the front of the module each time, we
329 // have to iterate in reverse source order.
330
331 List<Node> possiblyModifiedFunctions =
332 Lists.newArrayList(functionInfoBySpecializedFunctionNode.keySet());
333
334 Collections.reverse(possiblyModifiedFunctions);
335
336 for (Node modifiedFunction : possiblyModifiedFunctions) {
337 boolean declarationWasSpecialized =
338 specializationState.getSpecializedFunctions()
339 .contains(modifiedFunction);
340
341 boolean declarationWasRemoved =
342 specializationState.getRemovedFunctions()
343 .contains(modifiedFunction);
344
345 if (declarationWasSpecialized || declarationWasRemoved) {
346 OriginalFunctionInformation originalInfo =
347 functionInfoBySpecializedFunctionNode.get(modifiedFunction);
348
349 // Don't add unspecialized versions of anonymous functions
350 if (originalInfo.name != null) {
351 Node newDefinition =
352 originalInfo.generateFixupDefinition();
353
354 firstInputRootNode.addChildrenToFront(newDefinition);
355 }
356 }
357 }
358 }
359 }
360
361 /**
362 * Returns a list of modules that directly depend on the given module.
363 *
364 * This probably deserves to be in JSModuleGraph.
365 */
366 public Collection<JSModule> getDirectDependents(JSModule module) {
367 Set<JSModule> directDependents = Sets.newHashSet();
368
369 for (JSModule possibleDependent :
370 compiler.getModuleGraph().getAllModules()) {
371 if (possibleDependent.getDependencies().contains(module)) {
372 directDependents.add(possibleDependent);
373 }
374 }
375
376 return directDependents;
377 }
378
379 /**
380 * A simple abstract classes that takes two isomorphic ASTs and walks
381 * each of them together, reporting matches to subclasses.
382 *
383 * This could probably be hardened and moved to NodeUtil
384 */
385 private abstract static class NodeMatcher {
386
387 /**
388 * Calls {@link #reportMatch(Node, Node)} for each pair of matching nodes
389 * from the two ASTs.
390 *
391 * The two ASTs must be isomorphic. Currently no error checking is
392 * performed to ensure that this is the case.
393 */
394 public void match(Node ast1, Node ast2) {
395 // Just blunder ahead and assume that the two nodes actually match
396
397 reportMatch(ast1, ast2);
398
399 if (shouldTraverse(ast1, ast2)) {
400 Node childOf1 = ast1.getFirstChild();
401 Node childOf2 = ast2.getFirstChild();
402
403 while (childOf1 != null) {
404 match(childOf1, childOf2);
405 childOf1 = childOf1.getNext();
406 childOf2 = childOf2.getNext();
407 }
408 }
409
410 }
411
412 /**
413 * Subclasses should override to add their own behavior when two nodes
414 * are matched.
415 * @param n1 A node from the AST passed as ast1 in
416 * {@link #match(Node, Node)}.
417 * @param n2 A node from the AST passed as ast1 in
418 * {@link #match(Node, Node)}.
419 */
420 public abstract void reportMatch(Node n1, Node n2);
421
422 /**
423 * Subclasses should override to determine whether matching should proceed
424 * under a subtree.
425 */
426 public boolean shouldTraverse(Node node1, Node n2) {
427 return true;
428 }
429 }
430
431 /**
432 * A class that stores information about the original version of a
433 * function that will be/was specialized or removed.
434 *
435 * This class stores:
436 * - how the function was defined
437 * - a copy of the original function
438 */
439 private class OriginalFunctionInformation {
440 private String name;
441
442 /**
443 * a = function() {} if true;
444 * function a() {} otherwise
445 */
446 private boolean isAssignFunction;
447
448 private boolean assignHasVar;
449
450 private Node originalFunctionCopy;
451
452 public OriginalFunctionInformation(Node originalFunction) {
453 name = NodeUtil.getFunctionName(originalFunction);
454
455 originalFunctionCopy = originalFunction.cloneTree();
456 originalFunctionCopy.copyInformationFromForTree(originalFunction);
457
458 Node originalParent = originalFunction.getParent();
459
460 isAssignFunction = originalParent.isAssign() ||
461 originalParent.isName();
462
463 assignHasVar =
464 isAssignFunction && originalParent.getParent().isVar();
465 }
466
467 private Node copiedOriginalFunction() {
468 // Copy of a copy
469 Node copy = originalFunctionCopy.cloneTree();
470 copy.copyInformationFromForTree(originalFunctionCopy);
471
472 return copy;
473 }
474
475 /**
476 * Did the original function add its name to scope?
477 * (If so, and specialization removes it, then we'll have to
478 * add a VAR for it so VarCheck doesn't complain).
479 */
480 private boolean originalWasDeclaration() {
481 return (!isAssignFunction) || (assignHasVar);
482 }
483
484 /**
485 * Generates a definition of the original function that can be added as
486 * a fixup in the modules that directly depend on the specialized module.
487 *
488 * <PRE>
489 * The trick here is that even if the original function is declared as:
490 *
491 * function foo() {
492 * // stuff
493 * }
494 *
495 * the fixup will have to be of the form
496 *
497 * foo = function() {
498 * // stuff
499 * }
500 * </PRE>
501 *
502 */
503 private Node generateFixupDefinition() {
504 Node functionCopy = copiedOriginalFunction();
505
506 Node nameNode;
507
508 if (isAssignFunction) {
509 nameNode =
510 NodeUtil.newQualifiedNameNode(
511 compiler.getCodingConvention(), name, functionCopy, name);
512 } else {
513 // Grab the name node from the original function and make that
514 // function anonymous.
515 nameNode = functionCopy.getFirstChild();
516 functionCopy.replaceChild(nameNode,
517 NodeUtil.newName(compiler.getCodingConvention(), "", nameNode));
518 }
519
520 Node assignment = IR.assign(nameNode, functionCopy);
521 assignment.copyInformationFrom(functionCopy);
522
523 return NodeUtil.newExpr(assignment);
524 }
525
526 /**
527 * Returns a new dummy var declaration for the function with no initial
528 * value:
529 *
530 * var name;
531 */
532 private Node generateDummyDeclaration() {
533 Node declaration = NodeUtil.newVarNode(name, null);
534 declaration.copyInformationFromForTree(originalFunctionCopy);
535
536 return declaration;
537 }
538 }
539
540 /**
541 * A class to hold state during SpecializeModule. An instance of this class
542 * is passed to specialization-aware compiler passes -- they use it to
543 * communicate with SpecializeModule.
544 *
545 * SpecializationAware optimizations are required to keep track of the
546 * functions they remove and the functions that they modify so that the fixups
547 * can be added. However, not all functions can be fixed up.
548 *
549 * Specialization-aware classes *must* call
550 * {@link #reportSpecializedFunction} when a function is modified during
551 * specialization and {@link #reportRemovedFunction} when one is removed.
552 *
553 * Also, when specializing, they must query {@link #canFixupFunction}
554 * before modifying a function.
555 *
556 * This two-way communication, is the reason we don't use
557 * {@link AstChangeProxy} to report code changes.
558 */
559 public static class SpecializationState {
560
561 /**
562 * The functions that the pass has specialized. These functions will
563 * be fixed up in non-specialized modules to their more general versions.
564 *
565 * This field is also used to determine whether specialization is enabled.
566 * If not null, specialization is enabled, otherwise it is disabled.
567 */
568 private Set<Node> specializedFunctions;
569
570 /**
571 * The functions that the pass has removed. These functions will be
572 * redefined in non-specialized modules.
573 */
574 private Set<Node> removedFunctions;
575
576 private Map<Node, Node> removedFunctionToBlock;
577
578 private SimpleFunctionAliasAnalysis initialModuleAliasAnalysis;
579
580 /** Will be true if any new functions have been removed or specialized since
581 * {@link #resetHasChanged}.
582 */
583 private boolean hasChanged = false;
584
585 public SpecializationState(SimpleFunctionAliasAnalysis
586 initialModuleAliasAnalysis) {
587
588 this.initialModuleAliasAnalysis = initialModuleAliasAnalysis;
589
590 specializedFunctions = Sets.newLinkedHashSet();
591 removedFunctions = Sets.newLinkedHashSet();
592 removedFunctionToBlock = Maps.newLinkedHashMap();
593 }
594
595 /**
596 * Returns true if any new functions have been reported as removed or
597 * specialized since {@link #resetHasChanged()} was last called.
598 */
599 private boolean hasChanged() {
600 return hasChanged;
601 }
602
603 private void resetHasChanged() {
604 hasChanged = false;
605 }
606
607 /**
608 * Returns the functions specialized by this compiler pass.
609 */
610 public Set<Node> getSpecializedFunctions() {
611 return specializedFunctions;
612 }
613
614 /**
615 * Reports that a function has been specialized.
616 *
617 * @param functionNode A specialized AST node with type Token.FUNCTION
618 */
619 public void reportSpecializedFunction(Node functionNode) {
620 if (specializedFunctions.add(functionNode)) {
621 hasChanged = true;
622 }
623 }
624
625 /**
626 * Reports that the function containing the node has been specialized.
627 */
628 public void reportSpecializedFunctionContainingNode(Node node) {
629 Node containingFunction = containingFunction(node);
630
631 if (containingFunction != null) {
632 reportSpecializedFunction(containingFunction);
633 }
634 }
635
636 /**
637 * The functions removed by this compiler pass.
638 */
639 public Set<Node> getRemovedFunctions() {
640 return removedFunctions;
641 }
642
643 /**
644 * Reports that a function has been removed.
645 *
646 * @param functionNode A removed AST node with type Token.FUNCTION
647 * @param declaringBlock If the function declaration puts a variable in the
648 * scope, we need to have a VAR statement in the scope where the
649 * function is declared. Null if the function does not put a name
650 * in the scope.
651 */
652 public void reportRemovedFunction(Node functionNode, Node declaringBlock) {
653 // Depends when we were notified, functionNode.getParent might or might
654 // not be null. We are going to force the user to tell us the parent
655 // instead.
656 if (removedFunctions.add(functionNode)) {
657 hasChanged = true;
658 removedFunctionToBlock.put(functionNode, declaringBlock);
659 }
660 }
661
662 /**
663 * Returns true if the function can be fixed up (that is, if it can be
664 * safely removed or specialized).
665 *
666 * <p>In order to be safely fixed up, a function must be:
667 * <PRE>
668 * - in the global scope
669 * - not aliased in the initial module
670 * - of one of the following forms:
671 * function f() {}
672 * var f = function() {}
673 * f = function(){}
674 * var ns = {}; ns.f = function() {}
675 * SomeClass.prototype.foo = function() {};
676 * </PRE>
677 *
678 * <p>Anonymous functions cannot be safely fixed up, nor can functions
679 * that have been aliased.
680 *
681 * <p>Some functions declared as object literals could be safely fixed up,
682 * however we do not currently support this.
683 */
684 public boolean canFixupFunction(Node functionNode) {
685 Preconditions.checkArgument(functionNode.isFunction());
686
687 if (!nodeIsInGlobalScope(functionNode) ||
688 initialModuleAliasAnalysis.isAliased(functionNode)) {
689 return false;
690 }
691
692 if (NodeUtil.isStatement(functionNode)) {
693 // function F() {}
694 return true;
695 }
696
697 Node parent = functionNode.getParent();
698 Node gramps = parent.getParent();
699
700 if (parent.isName() && gramps.isVar()) {
701 // var f = function() {}
702 return true;
703 }
704
705 if (NodeUtil.isExprAssign(gramps)
706 && parent.getChildAtIndex(1) == functionNode) {
707 // f = function() {}
708 // ns.f = function() {}
709 return true;
710 }
711
712 return false;
713 }
714
715 /**
716 * Returns true if the function containing n can be fixed up.
717 * Also returns true if n is in the global scope -- since it is always safe
718 * to specialize the global scope.
719 */
720 public boolean canFixupSpecializedFunctionContainingNode(Node n) {
721 Node containingFunction = containingFunction(n);
722 if (containingFunction != null) {
723 return canFixupFunction(containingFunction);
724 } else {
725 // Always safe to specialize the global scope
726 return true;
727 }
728 }
729
730 /**
731 * Returns true if a node is in the global scope; false otherwise.
732 */
733 private boolean nodeIsInGlobalScope(Node node) {
734 return containingFunction(node) == null;
735 }
736
737 /**
738 * Returns the function containing the node, or null if none exists.
739 */
740 private Node containingFunction(Node node) {
741 for (Node ancestor : node.getAncestors()) {
742 if (ancestor.isFunction()) {
743 return ancestor;
744 }
745 }
746
747 return null;
748 }
749 }
750 }