Debian Codegraph @

src/com/google/javascript/jscomp/InlineVariables.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.base.Predicate;
21 import com.google.common.base.Predicates;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.CodingConvention.SubclassRelationship;
25 import com.google.javascript.jscomp.ReferenceCollectingCallback.Behavior;
26 import com.google.javascript.jscomp.ReferenceCollectingCallback.Reference;
27 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceCollection;
28 import com.google.javascript.jscomp.ReferenceCollectingCallback.ReferenceMap;
29 import com.google.javascript.jscomp.Scope.Var;
30 import com.google.javascript.rhino.Node;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Set;
35
36
37 /**
38 * Using the infrastructure provided by VariableReferencePass, identify
39 * variables that are used only once and in a way that is safe to move, and then
40 * inline them.
41 *
42 * This pass has two "modes." One mode only inlines variables declared as
43 * constants, for legacy compiler clients. The second mode inlines any
44 * variable that we can provably inline. Note that the second mode is a
45 * superset of the first mode. We only support the first mode for
46 * backwards-compatibility with compiler clients that don't want
47 * --inline_variables.
48 *
49 * The approach of this pass is similar to {@link CrossModuleCodeMotion}
50 *
51 * @author [email protected] (Kushal Dave)
52 * @author [email protected] (Nick Santos)
53 */
54 class InlineVariables implements CompilerPass {
55
56 private final AbstractCompiler compiler;
57
58 enum Mode {
59 // Only inline things explicitly marked as constant.
60 CONSTANTS_ONLY,
61 // Locals only
62 LOCALS_ONLY,
63 ALL
64 }
65
66 private final Mode mode;
67
68 // Inlines all strings, even if they increase the size of the gzipped binary.
69 private final boolean inlineAllStrings;
70
71 private final IdentifyConstants identifyConstants = new IdentifyConstants();
72
73 InlineVariables(
74 AbstractCompiler compiler,
75 Mode mode,
76 boolean inlineAllStrings) {
77 this.compiler = compiler;
78 this.mode = mode;
79 this.inlineAllStrings = inlineAllStrings;
80 }
81
82 @Override
83 public void process(Node externs, Node root) {
84 ReferenceCollectingCallback callback = new ReferenceCollectingCallback(
85 compiler, new InliningBehavior(), getFilterForMode());
86 callback.process(externs, root);
87 }
88
89 private Predicate<Var> getFilterForMode() {
90 switch (mode) {
91 case ALL:
92 return Predicates.<Var>alwaysTrue();
93 case LOCALS_ONLY:
94 return new IdentifyLocals();
95 case CONSTANTS_ONLY:
96 return new IdentifyConstants();
97 default:
98 throw new IllegalStateException();
99 }
100 }
101
102 /**
103 * Filters variables declared as "constant", and declares them in the outer
104 * declaredConstants map.
105 *
106 * In Google coding conventions, this means anything declared with @const
107 * or named in all caps, and initialized to an immutable value.
108 * CheckConsts has already verified that these are truly constants.
109 */
110 private class IdentifyConstants implements Predicate<Var> {
111 @Override
112 public boolean apply(Var var) {
113 return var.isConst();
114 }
115 }
116
117 /**
118 * Filters non-global variables.
119 */
120 private class IdentifyLocals implements Predicate<Var> {
121 @Override
122 public boolean apply(Var var) {
123 return var.scope.isLocal();
124 }
125 }
126
127 private static class AliasCandidate {
128 private final Var alias;
129 private final ReferenceCollection refInfo;
130
131 AliasCandidate(Var alias, ReferenceCollection refInfo) {
132 this.alias = alias;
133 this.refInfo = refInfo;
134 }
135 }
136
137 /**
138 * Builds up information about nodes in each scope. When exiting the
139 * scope, inspects all variables in that scope, and inlines any
140 * that we can.
141 */
142 private class InliningBehavior implements Behavior {
143
144 /**
145 * A list of variables that should not be inlined, because their
146 * reference information is out of sync with the state of the AST.
147 */
148 private final Set<Var> staleVars = Sets.newHashSet();
149
150 /**
151 * Stored possible aliases of variables that never change, with
152 * all the reference info about those variables. Hashed by the NAME
153 * node of the variable being aliased.
154 */
155 final Map<Node, AliasCandidate> aliasCandidates = Maps.newHashMap();
156
157 @Override
158 public void afterExitScope(NodeTraversal t, ReferenceMap referenceMap) {
159 collectAliasCandidates(t, referenceMap);
160 doInlinesForScope(t, referenceMap);
161 }
162
163 /**
164 * If any of the variables are well-defined and alias other variables,
165 * mark them as aliasing candidates.
166 */
167 private void collectAliasCandidates(NodeTraversal t,
168 ReferenceMap referenceMap) {
169 if (mode != Mode.CONSTANTS_ONLY) {
170 for (Iterator<Var> it = t.getScope().getVars(); it.hasNext();) {
171 Var v = it.next();
172 ReferenceCollection referenceInfo = referenceMap.getReferences(v);
173
174 // NOTE(nicksantos): Don't handle variables that are never used.
175 // The tests are much easier to write if you don't, and there's
176 // another pass that handles unused variables much more elegantly.
177 if (referenceInfo != null && referenceInfo.references.size() >= 2 &&
178 referenceInfo.isWellDefined() &&
179 referenceInfo.isAssignedOnceInLifetime()) {
180 Reference init = referenceInfo.getInitializingReference();
181 Node value = init.getAssignedValue();
182 if (value != null && value.isName()) {
183 aliasCandidates.put(value, new AliasCandidate(v, referenceInfo));
184 }
185 }
186 }
187 }
188 }
189
190 /**
191 * For all variables in this scope, see if they are only used once.
192 * If it looks safe to do so, inline them.
193 */
194 private void doInlinesForScope(NodeTraversal t, ReferenceMap referenceMap) {
195
196 boolean maybeModifiedArguments =
197 maybeEscapedOrModifiedArguments(t.getScope(), referenceMap);
198 for (Iterator<Var> it = t.getScope().getVars(); it.hasNext();) {
199 Var v = it.next();
200
201 ReferenceCollection referenceInfo = referenceMap.getReferences(v);
202
203 // referenceInfo will be null if we're in constants-only mode
204 // and the variable is not a constant.
205 if (referenceInfo == null || isVarInlineForbidden(v)) {
206 // Never try to inline exported variables or variables that
207 // were not collected or variables that have already been inlined.
208 continue;
209 } else if (isInlineableDeclaredConstant(v, referenceInfo)) {
210 Reference init = referenceInfo.getInitializingReferenceForConstants();
211 Node value = init.getAssignedValue();
212 inlineDeclaredConstant(v, value, referenceInfo.references);
213 staleVars.add(v);
214 } else if (mode == Mode.CONSTANTS_ONLY) {
215 // If we're in constants-only mode, don't run more aggressive
216 // inlining heuristics. See InlineConstantsTest.
217 continue;
218 } else {
219 inlineNonConstants(v, referenceInfo, maybeModifiedArguments);
220 }
221 }
222 }
223
224 private boolean maybeEscapedOrModifiedArguments(
225 Scope scope, ReferenceMap referenceMap) {
226 if (scope.isLocal()) {
227 Var arguments = scope.getArgumentsVar();
228 ReferenceCollection refs = referenceMap.getReferences(arguments);
229 if (refs != null && !refs.references.isEmpty()) {
230 for (Reference ref : refs.references) {
231 Node refNode = ref.getNode();
232 Node refParent = ref.getParent();
233 // Any reference that is not a read of the arguments property
234 // consider a escape of the arguments object.
235 if (!(NodeUtil.isGet(refParent)
236 && refNode == ref.getParent().getFirstChild()
237 && !isLValue(refParent))) {
238 return true;
239 }
240 }
241 }
242 }
243 return false;
244 }
245
246 private boolean isLValue(Node n) {
247 Node parent = n.getParent();
248 return (parent.isInc()
249 || parent.isDec()
250 || (NodeUtil.isAssignmentOp(parent)
251 && parent.getFirstChild() == n));
252 }
253
254 private void inlineNonConstants(
255 Var v, ReferenceCollection referenceInfo,
256 boolean maybeModifiedArguments) {
257 int refCount = referenceInfo.references.size();
258 Reference declaration = referenceInfo.references.get(0);
259 Reference init = referenceInfo.getInitializingReference();
260 int firstRefAfterInit = (declaration == init) ? 2 : 3;
261
262 if (refCount > 1 &&
263 isImmutableAndWellDefinedVariable(v, referenceInfo)) {
264 // if the variable is referenced more than once, we can only
265 // inline it if it's immutable and never defined before referenced.
266 Node value;
267 if (init != null) {
268 value = init.getAssignedValue();
269 } else {
270 // Create a new node for variable that is never initialized.
271 Node srcLocation = declaration.getNode();
272 value = NodeUtil.newUndefinedNode(srcLocation);
273 }
274 Preconditions.checkNotNull(value);
275 inlineWellDefinedVariable(v, value, referenceInfo.references);
276 staleVars.add(v);
277 } else if (refCount == firstRefAfterInit) {
278 // The variable likely only read once, try some more
279 // complex inlining heuristics.
280 Reference reference = referenceInfo.references.get(
281 firstRefAfterInit - 1);
282 if (canInline(declaration, init, reference)) {
283 inline(v, declaration, init, reference);
284 staleVars.add(v);
285 }
286 } else if (declaration != init && refCount == 2) {
287 if (isValidDeclaration(declaration) && isValidInitialization(init)) {
288 // The only reference is the initialization, remove the assignment and
289 // the variable declaration.
290 Node value = init.getAssignedValue();
291 Preconditions.checkNotNull(value);
292 inlineWellDefinedVariable(v, value, referenceInfo.references);
293 staleVars.add(v);
294 }
295 }
296
297 // If this variable was not inlined normally, check if we can
298 // inline an alias of it. (If the variable was inlined, then the
299 // reference data is out of sync. We're better off just waiting for
300 // the next pass.)
301 if (!maybeModifiedArguments &&
302 !staleVars.contains(v) && referenceInfo.isWellDefined() &&
303 referenceInfo.isAssignedOnceInLifetime()) {
304 List<Reference> refs = referenceInfo.references;
305 for (int i = 1 /* start from a read */; i < refs.size(); i++) {
306 Node nameNode = refs.get(i).getNode();
307 if (aliasCandidates.containsKey(nameNode)) {
308 AliasCandidate candidate = aliasCandidates.get(nameNode);
309 if (!staleVars.contains(candidate.alias) &&
310 !isVarInlineForbidden(candidate.alias)) {
311 Reference aliasInit;
312 aliasInit = candidate.refInfo.getInitializingReference();
313 Node value = aliasInit.getAssignedValue();
314 Preconditions.checkNotNull(value);
315 inlineWellDefinedVariable(candidate.alias,
316 value,
317 candidate.refInfo.references);
318 staleVars.add(candidate.alias);
319 }
320 }
321 }
322 }
323 }
324
325 /**
326 * If there are any variable references in the given node tree, blacklist
327 * them to prevent the pass from trying to inline the variable.
328 */
329 private void blacklistVarReferencesInTree(Node root, Scope scope) {
330 for (Node c = root.getFirstChild(); c != null; c = c.getNext()) {
331 blacklistVarReferencesInTree(c, scope);
332 }
333
334 if (root.isName()) {
335 staleVars.add(scope.getVar(root.getString()));
336 }
337 }
338
339 /**
340 * Whether the given variable is forbidden from being inlined.
341 */
342 private boolean isVarInlineForbidden(Var var) {
343 // A variable may not be inlined if:
344 // 1) The variable is exported,
345 // 2) A reference to the variable has been inlined. We're downstream
346 // of the mechanism that creates variable references, so we don't
347 // have a good way to update the reference. Just punt on it.
348 // 3) Don't inline the special RENAME_PROPERTY_FUNCTION_NAME
349 return var.isExtern()
350 || compiler.getCodingConvention().isExported(var.name)
351 || RenameProperties.RENAME_PROPERTY_FUNCTION_NAME.equals(var.name)
352 || staleVars.contains(var);
353 }
354
355 /**
356 * Do the actual work of inlining a single declaration into a single
357 * reference.
358 */
359 private void inline(Var v, Reference declaration,
360 Reference init, Reference reference) {
361 Node value = init.getAssignedValue();
362 Preconditions.checkState(value != null);
363 // Check for function declarations before the value is moved in the AST.
364 boolean isFunctionDeclaration = NodeUtil.isFunctionDeclaration(value);
365
366 inlineValue(v, reference, value.detachFromParent());
367 if (declaration != init) {
368 Node expressRoot = init.getGrandparent();
369 Preconditions.checkState(expressRoot.isExprResult());
370 NodeUtil.removeChild(expressRoot.getParent(), expressRoot);
371 }
372
373 // Function declarations have already been removed.
374 if (!isFunctionDeclaration) {
375 removeDeclaration(declaration);
376 } else {
377 compiler.reportCodeChange();
378 }
379 }
380
381 /**
382 * Inline an immutable variable into all of its references.
383 */
384 private void inlineWellDefinedVariable(Var v, Node value,
385 List<Reference> refSet) {
386 Reference decl = refSet.get(0);
387 for (int i = 1; i < refSet.size(); i++) {
388 inlineValue(v, refSet.get(i), value.cloneTree());
389 }
390 removeDeclaration(decl);
391 }
392
393 /**
394 * Inline a declared constant.
395 */
396 private void inlineDeclaredConstant(Var v, Node value,
397 List<Reference> refSet) {
398 // Replace the references with the constant value
399 Reference decl = null;
400
401 for (Reference r : refSet) {
402 if (r.getNode() == v.getNameNode()) {
403 decl = r;
404 } else {
405 inlineValue(v, r, value.cloneTree());
406 }
407 }
408
409 removeDeclaration(decl);
410 }
411
412 /**
413 * Remove the given VAR declaration.
414 */
415 private void removeDeclaration(Reference declaration) {
416 Node varNode = declaration.getParent();
417 Node grandparent = declaration.getGrandparent();
418
419 varNode.removeChild(declaration.getNode());
420
421 // Remove var node if empty
422 if (!varNode.hasChildren()) {
423 Preconditions.checkState(varNode.isVar());
424 NodeUtil.removeChild(grandparent, varNode);
425 }
426
427 compiler.reportCodeChange();
428 }
429
430 /**
431 * Replace the given reference with the given value node.
432 *
433 * @param v The variable that's referenced.
434 * @param ref The reference to replace.
435 * @param value The node tree to replace it with. This tree should be safe
436 * to re-parent.
437 */
438 private void inlineValue(Var v, Reference ref, Node value) {
439 if (ref.isSimpleAssignmentToName()) {
440 // This is the initial assignment.
441 ref.getGrandparent().replaceChild(ref.getParent(), value);
442 } else {
443 ref.getParent().replaceChild(ref.getNode(), value);
444 }
445
446 blacklistVarReferencesInTree(value, v.scope);
447 compiler.reportCodeChange();
448 }
449
450 /**
451 * Determines whether the given variable is declared as a constant
452 * and may be inlined.
453 */
454 private boolean isInlineableDeclaredConstant(Var var,
455 ReferenceCollection refInfo) {
456 if (!identifyConstants.apply(var)) {
457 return false;
458 }
459
460 if (!refInfo.isAssignedOnceInLifetime()) {
461 return false;
462 }
463
464 Reference init = refInfo.getInitializingReferenceForConstants();
465 if (init == null) {
466 return false;
467 }
468
469 Node value = init.getAssignedValue();
470 if (value == null) {
471 // This constant is either externally defined or initialized indirectly
472 // (e.g. in an function expression used to hide
473 // temporary variables), so the constant is ineligible for inlining.
474 return false;
475 }
476
477 // Is the constant's value immutable?
478 if (!NodeUtil.isImmutableValue(value)) {
479 return false;
480 }
481
482 // Determine if we should really inline a String or not.
483 return !value.isString() ||
484 isStringWorthInlining(var, refInfo.references);
485 }
486
487 /**
488 * Compute whether the given string is worth inlining.
489 */
490 private boolean isStringWorthInlining(Var var, List<Reference> refs) {
491 if (!inlineAllStrings && !var.isDefine()) {
492 int len = var.getInitialValue().getString().length() + "''".length();
493
494 // if not inlined: var xx="value"; .. xx .. xx ..
495 // The 4 bytes per reference is just a heuristic:
496 // 2 bytes per var name plus maybe 2 bytes if we don't inline, e.g.
497 // in the case of "foo " + CONST + " bar"
498 int noInlineBytes = "var xx=;".length() + len +
499 4 * (refs.size() - 1);
500
501 // if inlined:
502 // I'm going to assume that half of the quotes will be eliminated
503 // thanks to constant folding, therefore I subtract 1 (2/2=1) from
504 // the string length.
505 int inlineBytes = (len - 1) * (refs.size() - 1);
506
507 // Not inlining if doing so uses more bytes, or this constant is being
508 // defined.
509 return noInlineBytes >= inlineBytes;
510 }
511
512 return true;
513 }
514
515 /**
516 * @return true if the provided reference and declaration can be safely
517 * inlined according to our criteria
518 */
519 private boolean canInline(
520 Reference declaration,
521 Reference initialization,
522 Reference reference) {
523 if (!isValidDeclaration(declaration)
524 || !isValidInitialization(initialization)
525 || !isValidReference(reference)) {
526 return false;
527 }
528
529 // If the value is read more than once, skip it.
530 // VAR declarations and EXPR_RESULT don't need the value, but other
531 // ASSIGN expressions parents do.
532 if (declaration != initialization &&
533 !initialization.getGrandparent().isExprResult()) {
534 return false;
535 }
536
537 // Be very conservative and do no cross control structures or
538 // scope boundaries
539 if (declaration.getBasicBlock() != initialization.getBasicBlock()
540 || declaration.getBasicBlock() != reference.getBasicBlock()) {
541 return false;
542 }
543
544 // Do not inline into a call node. This would change
545 // the context in which it was being called. For example,
546 // var a = b.c;
547 // a();
548 // should not be inlined, because it calls a in the context of b
549 // rather than the context of the window.
550 // var a = b.c;
551 // f(a)
552 // is OK.
553 Node value = initialization.getAssignedValue();
554 Preconditions.checkState(value != null);
555 if (value.isGetProp()
556 && reference.getParent().isCall()
557 && reference.getParent().getFirstChild() == reference.getNode()) {
558 return false;
559 }
560
561 if (value.isFunction()) {
562 Node callNode = reference.getParent();
563 if (reference.getParent().isCall()) {
564 CodingConvention convention = compiler.getCodingConvention();
565 // Bug 2388531: Don't inline subclass definitions into class defining
566 // calls as this confused class removing logic.
567 SubclassRelationship relationship =
568 convention.getClassesDefinedByCall(callNode);
569 if (relationship != null) {
570 return false;
571 }
572
573 // issue 668: Don't inline singleton getter methods
574 // calls as this confused class removing logic.
575 if (convention.getSingletonGetterClassName(callNode) != null) {
576 return false;
577 }
578 }
579 }
580
581 return canMoveAggressively(value) ||
582 canMoveModerately(initialization, reference);
583 }
584
585 /**
586 * If the value is a literal, we can cross more boundaries to inline it.
587 */
588 private boolean canMoveAggressively(Node value) {
589 // Function expressions and other mutable objects can move within
590 // the same basic block.
591 return NodeUtil.isLiteralValue(value, true)
592 || value.isFunction();
593 }
594
595 /**
596 * If the value of a variable is not constant, then it may read or modify
597 * state. Therefore it cannot be moved past anything else that may modify
598 * the value being read or read values that are modified.
599 */
600 private boolean canMoveModerately(
601 Reference initialization,
602 Reference reference) {
603 // Check if declaration can be inlined without passing
604 // any side-effect causing nodes.
605 Iterator<Node> it;
606 if (initialization.getParent().isVar()) {
607 it = NodeIterators.LocalVarMotion.forVar(
608 initialization.getNode(), // NAME
609 initialization.getParent(), // VAR
610 initialization.getGrandparent()); // VAR container
611 } else if (initialization.getParent().isAssign()) {
612 Preconditions.checkState(
613 initialization.getGrandparent().isExprResult());
614 it = NodeIterators.LocalVarMotion.forAssign(
615 initialization.getNode(), // NAME
616 initialization.getParent(), // ASSIGN
617 initialization.getGrandparent(), // EXPR_RESULT
618 initialization.getGrandparent().getParent()); // EXPR container
619 } else {
620 throw new IllegalStateException("Unexpected initialization parent " +
621 initialization.getParent().toStringTree());
622 }
623 Node targetName = reference.getNode();
624 while (it.hasNext()) {
625 Node curNode = it.next();
626 if (curNode == targetName) {
627 return true;
628 }
629 }
630
631 return false;
632 }
633
634 /**
635 * @return true if the reference is a normal VAR or FUNCTION declaration.
636 */
637 private boolean isValidDeclaration(Reference declaration) {
638 return (declaration.getParent().isVar()
639 && !declaration.getGrandparent().isFor())
640 || NodeUtil.isFunctionDeclaration(declaration.getParent());
641 }
642
643 /**
644 * @return Whether there is a initial value.
645 */
646 private boolean isValidInitialization(Reference initialization) {
647 if (initialization == null) {
648 return false;
649 } else if (initialization.isDeclaration()) {
650 // The reference is a FUNCTION declaration or normal VAR declaration
651 // with a value.
652 if (!NodeUtil.isFunctionDeclaration(initialization.getParent())
653 && initialization.getNode().getFirstChild() == null) {
654 return false;
655 }
656 } else {
657 Node parent = initialization.getParent();
658 Preconditions.checkState(
659 parent.isAssign()
660 && parent.getFirstChild() == initialization.getNode());
661 }
662
663 Node n = initialization.getAssignedValue();
664 if (n.isFunction()) {
665 return compiler.getCodingConvention().isInlinableFunction(n);
666 }
667
668 return true;
669 }
670
671 /**
672 * @return true if the reference is a candidate for inlining
673 */
674 private boolean isValidReference(Reference reference) {
675 return !reference.isDeclaration() && !reference.isLvalue();
676 }
677
678 /**
679 * Determines whether the reference collection describes a variable that
680 * is initialized to an immutable value, never modified, and defined before
681 * every reference.
682 */
683 private boolean isImmutableAndWellDefinedVariable(Var v,
684 ReferenceCollection refInfo) {
685 List<Reference> refSet = refInfo.references;
686 int startingReadRef = 1;
687 Reference refDecl = refSet.get(0);
688 if (!isValidDeclaration(refDecl)) {
689 return false;
690 }
691
692 boolean isNeverAssigned = refInfo.isNeverAssigned();
693 // For values that are never assigned, only the references need to be
694 // checked.
695 if (!isNeverAssigned) {
696 Reference refInit = refInfo.getInitializingReference();
697 if (!isValidInitialization(refInit)) {
698 return false;
699 }
700
701 if (refDecl != refInit) {
702 Preconditions.checkState(refInit == refSet.get(1));
703 startingReadRef = 2;
704 }
705
706 if (!refInfo.isWellDefined()) {
707 return false;
708 }
709
710 Node value = refInit.getAssignedValue();
711 Preconditions.checkNotNull(value);
712
713 boolean isImmutableValueWorthInlining =
714 NodeUtil.isImmutableValue(value) &&
715 (!value.isString() ||
716 isStringWorthInlining(v, refInfo.references));
717 boolean isInlinableThisAlias =
718 value.isThis() &&
719 !refInfo.isEscaped();
720 if (!isImmutableValueWorthInlining && !isInlinableThisAlias) {
721 return false;
722 }
723 }
724
725 for (int i = startingReadRef; i < refSet.size(); i++) {
726 Reference ref = refSet.get(i);
727 if (!isValidReference(ref)) {
728 return false;
729 }
730 }
731
732 return true;
733 }
734 }
735 }