Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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.javascript.jscomp.DefinitionsRemover.Definition;
22 import com.google.javascript.rhino.IR;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.jstype.FunctionType;
25 import com.google.javascript.rhino.jstype.JSType;
26 import com.google.javascript.rhino.jstype.JSTypeNative;
27 import com.google.javascript.rhino.jstype.JSTypeRegistry;
28 import com.google.javascript.rhino.jstype.ObjectType;
29
30 import java.util.Collection;
31 import java.util.List;
32
33 /**
34 * Rewrites prototyped methods calls as static calls that take "this"
35 * as their first argument. This transformation simplifies the call
36 * graph so smart name removal, cross module code motion and other
37 * passes can do more.
38 *
39 * <p>This pass should only be used in production code if property
40 * and variable renaming are turned on. Resulting code may also
41 * benefit from --collapse_anonymous_functions and
42 * --collapse_variable_declarations
43 *
44 * <p>This pass only rewrites functions that are part of an objects
45 * prototype. Functions that access the "arguments" variable
46 * arguments object are not eligible for this optimization.
47 *
48 * <p>For example:
49 * <pre>
50 * A.prototype.accumulate = function(value) {
51 * this.total += value; return this.total
52 * }
53 * var total = a.accumulate(2)
54 * </pre>
55 *
56 * <p>will be rewritten as:
57 *
58 * <pre>
59 * var accumulate = function(self, value) {
60 * self.total += value; return self.total
61 * }
62 * var total = accumulate(a, 2)
63 * </pre>
64 *
65 */
66 class DevirtualizePrototypeMethods
67 implements OptimizeCalls.CallGraphCompilerPass,
68 SpecializationAwareCompilerPass {
69 private final AbstractCompiler compiler;
70 private SpecializeModule.SpecializationState specializationState;
71
72 DevirtualizePrototypeMethods(AbstractCompiler compiler) {
73 this.compiler = compiler;
74 }
75
76 @Override
77 public void enableSpecialization(SpecializeModule.SpecializationState state) {
78 this.specializationState = state;
79 }
80
81 @Override
82 public void process(Node externs, Node root) {
83 SimpleDefinitionFinder defFinder = new SimpleDefinitionFinder(compiler);
84 defFinder.process(externs, root);
85 process(externs, root, defFinder);
86 }
87
88 @Override
89 public void process(
90 Node externs, Node root, SimpleDefinitionFinder definitions) {
91 for (DefinitionSite defSite : definitions.getDefinitionSites()) {
92 rewriteDefinitionIfEligible(defSite, definitions);
93 }
94 }
95
96 /**
97 * Determines if the name node acts as the function name in a call expression.
98 */
99 private static boolean isCall(UseSite site) {
100 Node node = site.node;
101 Node parent = node.getParent();
102 return (parent.getFirstChild() == node) && parent.isCall();
103 }
104
105 /**
106 * Determines if the current node is a function prototype definition.
107 */
108 private static boolean isPrototypeMethodDefinition(Node node) {
109 Node parent = node.getParent();
110 if (parent == null) {
111 return false;
112 }
113 Node gramp = parent.getParent();
114 if (gramp == null) {
115 return false;
116 }
117
118 if (node.isGetProp()) {
119 if (parent.getFirstChild() != node) {
120 return false;
121 }
122
123 if (!NodeUtil.isExprAssign(gramp)) {
124 return false;
125 }
126
127 Node functionNode = parent.getLastChild();
128 if ((functionNode == null) || !functionNode.isFunction()) {
129 return false;
130 }
131
132 Node nameNode = node.getFirstChild();
133 return nameNode.isGetProp() &&
134 nameNode.getLastChild().getString().equals("prototype");
135 } else if (node.isStringKey()) {
136 Preconditions.checkState(parent.isObjectLit());
137
138 if (!gramp.isAssign()) {
139 return false;
140 }
141
142 if (gramp.getLastChild() != parent) {
143 return false;
144 }
145
146 Node greatGramp = gramp.getParent();
147 if (greatGramp == null || !greatGramp.isExprResult()) {
148 return false;
149 }
150
151 Node functionNode = node.getFirstChild();
152 if ((functionNode == null) || !functionNode.isFunction()) {
153 return false;
154 }
155
156 Node target = gramp.getFirstChild();
157 return target.isGetProp() &&
158 target.getLastChild().getString().equals("prototype");
159 } else {
160 return false;
161 }
162 }
163
164 private String getMethodName(Node node) {
165 if (node.isGetProp()) {
166 return node.getLastChild().getString();
167 } else if (node.isStringKey()) {
168 return node.getString();
169 } else {
170 throw new IllegalStateException("unexpected");
171 }
172 }
173
174 /**
175 * @returns The new name for a rewritten method.
176 */
177 private String getRewrittenMethodName(String originalMethodName) {
178 return "JSCompiler_StaticMethods_" + originalMethodName;
179 }
180
181 /**
182 * Rewrites method definition and call sites if the method is
183 * defined in the global scope exactly once.
184 *
185 * Definition and use site information is provided by the
186 * {@link SimpleDefinitionFinder} passed in as an argument.
187 *
188 * @param defSite definition site to process.
189 * @param defFinder structure that hold Node -> Definition and
190 * Definition -> [UseSite] maps.
191 */
192 private void rewriteDefinitionIfEligible(DefinitionSite defSite,
193 SimpleDefinitionFinder defFinder) {
194 if (defSite.inExterns ||
195 !defSite.inGlobalScope ||
196 !isEligibleDefinition(defFinder, defSite)) {
197 return;
198 }
199
200 Node node = defSite.node;
201 if (!isPrototypeMethodDefinition(node)) {
202 return;
203 }
204
205 for (Node ancestor = node.getParent();
206 ancestor != null;
207 ancestor = ancestor.getParent()) {
208 if (NodeUtil.isControlStructure(ancestor)) {
209 return;
210 }
211 }
212
213 // TODO(user) The code only works if there is a single definition
214 // associated with a property name. Once this pass starts using
215 // the NameReferenceGraph to disambiguate call sites, it will be
216 // necessary to consider type information when generating static
217 // method names and/or append unique ids to duplicate static
218 // method names.
219 // Whatever scheme we use should not break stable renaming.
220 String newMethodName = getRewrittenMethodName(
221 getMethodName(node));
222 rewriteDefinition(node, newMethodName);
223 rewriteCallSites(defFinder, defSite.definition, newMethodName);
224 }
225
226 /**
227 * Determines if a method definition is eligible for rewrite as a
228 * global function. In order to be eligible for rewrite, the
229 * definition must:
230 *
231 * - Refer to a function that takes a fixed number of arguments.
232 * - Function must not be exported.
233 * - Function must be used at least once.
234 * - Property is never accessed outside a function call context.
235 * - The definition under consideration must be the only possible
236 * choice at each call site.
237 * - Definition must happen in a module loaded before the first use.
238 */
239 private boolean isEligibleDefinition(SimpleDefinitionFinder defFinder,
240 DefinitionSite definitionSite) {
241
242 Definition definition = definitionSite.definition;
243 JSModule definitionModule = definitionSite.module;
244
245 // Only functions may be rewritten.
246 // Functions that access "arguments" are not eligible since
247 // rewrite changes the structure of this object.
248 Node rValue = definition.getRValue();
249 if (rValue == null ||
250 !rValue.isFunction() ||
251 NodeUtil.isVarArgsFunction(rValue)) {
252 return false;
253 }
254
255 // Exporting a method prevents rewrite.
256 Node lValue = definition.getLValue();
257 if ((lValue == null) ||
258 !lValue.isGetProp()) {
259 return false;
260 }
261 CodingConvention codingConvention = compiler.getCodingConvention();
262 if (codingConvention.isExported(lValue.getLastChild().getString())) {
263 return false;
264 }
265
266 Collection<UseSite> useSites = defFinder.getUseSites(definition);
267
268 // Rewriting unused methods is not sound.
269 if (useSites.isEmpty()) {
270 return false;
271 }
272
273 JSModuleGraph moduleGraph = compiler.getModuleGraph();
274
275 for (UseSite site : useSites) {
276 // Accessing the property directly prevents rewrite.
277 if (!isCall(site)) {
278 return false;
279 }
280
281 Node nameNode = site.node;
282
283 // Don't rewrite methods called in functions that can't be specialized
284 // if we are specializing
285 if (specializationState != null &&
286 !specializationState.canFixupSpecializedFunctionContainingNode(
287 nameNode)) {
288 return false;
289 }
290
291 // Multiple definitions prevent rewrite.
292 Collection<Definition> singleSiteDefinitions =
293 defFinder.getDefinitionsReferencedAt(nameNode);
294 if (singleSiteDefinitions.size() > 1) {
295 return false;
296 }
297 Preconditions.checkState(!singleSiteDefinitions.isEmpty());
298 Preconditions.checkState(singleSiteDefinitions.contains(definition));
299
300 // Accessing the property in a module loaded before the
301 // definition module prevents rewrite; accessing a variable
302 // before definition results in a parse error.
303 JSModule callModule = site.module;
304 if ((definitionModule != callModule) &&
305 ((callModule == null) ||
306 !moduleGraph.dependsOn(callModule, definitionModule))) {
307 return false;
308 }
309 }
310
311 return true;
312 }
313
314 /**
315 * Rewrites object method call sites as calls to global functions
316 * that take "this" as their first argument.
317 *
318 * Before:
319 * o.foo(a, b, c)
320 *
321 * After:
322 * foo(o, a, b, c)
323 */
324 private void rewriteCallSites(SimpleDefinitionFinder defFinder,
325 Definition definition,
326 String newMethodName) {
327 Collection<UseSite> useSites = defFinder.getUseSites(definition);
328 for (UseSite site : useSites) {
329 Node node = site.node;
330 Node parent = node.getParent();
331
332 Node objectNode = node.getFirstChild();
333 node.removeChild(objectNode);
334 parent.replaceChild(node, objectNode);
335 parent.addChildToFront(IR.name(newMethodName).srcref(node));
336 Preconditions.checkState(parent.isCall());
337 parent.putBooleanProp(Node.FREE_CALL, true);
338 compiler.reportCodeChange();
339
340 if (specializationState != null) {
341 specializationState.reportSpecializedFunctionContainingNode(parent);
342 }
343 }
344 }
345
346 /**
347 * Rewrites method definitions as global functions that take "this"
348 * as their first argument.
349 *
350 * Before:
351 * a.prototype.b = function(a, b, c) {...}
352 *
353 * After:
354 * var b = function(self, a, b, c) {...}
355 */
356 private void rewriteDefinition(Node node, String newMethodName) {
357 boolean isObjLitDefKey = node.isStringKey();
358
359 Node parent = node.getParent();
360
361 Node refNode = isObjLitDefKey ? node : parent.getFirstChild();
362 Node newNameNode = IR.name(newMethodName).copyInformationFrom(refNode);
363 Node newVarNode = IR.var(newNameNode).copyInformationFrom(refNode);
364
365 Node functionNode;
366 if (!isObjLitDefKey) {
367 Preconditions.checkState(parent.isAssign());
368 functionNode = parent.getLastChild();
369 Node expr = parent.getParent();
370 Node block = expr.getParent();
371 parent.removeChild(functionNode);
372 newNameNode.addChildToFront(functionNode);
373 block.replaceChild(expr, newVarNode);
374
375 if (specializationState != null) {
376 specializationState.reportRemovedFunction(functionNode, block);
377 }
378 } else {
379 Preconditions.checkState(parent.isObjectLit());
380 functionNode = node.getFirstChild();
381 Node assign = parent.getParent();
382 Node expr = assign.getParent();
383 Node block = expr.getParent();
384
385 node.removeChild(functionNode);
386 parent.removeChild(node);
387 newNameNode.addChildToFront(functionNode);
388 block.addChildAfter(newVarNode, expr);
389
390 if (specializationState != null) {
391 specializationState.reportRemovedFunction(functionNode, block);
392 }
393 }
394
395 // add extra argument
396 String self = newMethodName + "$self";
397 Node argList = functionNode.getFirstChild().getNext();
398 argList.addChildToFront(IR.name(self)
399 .copyInformationFrom(functionNode));
400
401 // rewrite body
402 Node body = functionNode.getLastChild();
403 replaceReferencesToThis(body, self);
404
405 // fix type
406 fixFunctionType(functionNode);
407
408 compiler.reportCodeChange();
409 }
410
411 /**
412 * Creates a new JSType based on the original function type by
413 * adding the original this pointer type to the beginning of the
414 * argument type list and replacing the this pointer type with
415 * NO_TYPE.
416 */
417 private void fixFunctionType(Node functionNode) {
418 FunctionType type = JSType.toMaybeFunctionType(functionNode.getJSType());
419 if (type != null) {
420 JSTypeRegistry typeRegistry = compiler.getTypeRegistry();
421
422 List<JSType> parameterTypes = Lists.newArrayList();
423 parameterTypes.add(type.getTypeOfThis());
424
425 for (Node param : type.getParameters()) {
426 parameterTypes.add(param.getJSType());
427 }
428
429 ObjectType thisType =
430 typeRegistry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE);
431 JSType returnType = type.getReturnType();
432
433 JSType newType = typeRegistry.createFunctionType(
434 thisType, returnType, parameterTypes);
435 functionNode.setJSType(newType);
436 }
437 }
438
439 /**
440 * Replaces references to "this" with references to name. Do not
441 * traverse function boundaries.
442 */
443 private void replaceReferencesToThis(Node node, String name) {
444 if (node.isFunction()) {
445 return;
446 }
447
448 for (Node child : node.children()) {
449 if (child.isThis()) {
450 Node newName = IR.name(name);
451 newName.setJSType(child.getJSType());
452 node.replaceChild(child, newName);
453 } else {
454 replaceReferencesToThis(child, name);
455 }
456 }
457 }
458 }