1 /*
2 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package jdk.nashorn.internal.codegen;
27
28 import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.PRIVATE;
29 import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.STATIC;
30 import static jdk.nashorn.internal.codegen.CompilerConstants.ARGUMENTS;
31 import static jdk.nashorn.internal.codegen.CompilerConstants.CALLEE;
32 import static jdk.nashorn.internal.codegen.CompilerConstants.GET_MAP;
33 import static jdk.nashorn.internal.codegen.CompilerConstants.GET_STRING;
34 import static jdk.nashorn.internal.codegen.CompilerConstants.QUICK_PREFIX;
35 import static jdk.nashorn.internal.codegen.CompilerConstants.REGEX_PREFIX;
36 import static jdk.nashorn.internal.codegen.CompilerConstants.RETURN;
37 import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE;
38 import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_ARRAY_ARG;
39 import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_PREFIX;
40 import static jdk.nashorn.internal.codegen.CompilerConstants.THIS;
41 import static jdk.nashorn.internal.codegen.CompilerConstants.VARARGS;
42 import static jdk.nashorn.internal.codegen.CompilerConstants.constructorNoLookup;
43 import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup;
44 import static jdk.nashorn.internal.codegen.CompilerConstants.methodDescriptor;
45 import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
46 import static jdk.nashorn.internal.codegen.CompilerConstants.staticField;
47 import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
48 import static jdk.nashorn.internal.ir.Symbol.IS_INTERNAL;
49 import static jdk.nashorn.internal.ir.Symbol.IS_TEMP;
50 import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_FAST_SCOPE;
51 import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
52 import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_STRICT;
53
54 import java.io.PrintWriter;
55 import java.util.ArrayList;
56 import java.util.Arrays;
57 import java.util.EnumSet;
58 import java.util.Iterator;
59 import java.util.LinkedList;
60 import java.util.List;
61 import java.util.TreeMap;
62
63 import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
64 import jdk.nashorn.internal.codegen.CompilerConstants.Call;
65 import jdk.nashorn.internal.codegen.RuntimeCallSite.SpecializedRuntimeNode;
66 import jdk.nashorn.internal.codegen.types.ArrayType;
67 import jdk.nashorn.internal.codegen.types.Type;
68 import jdk.nashorn.internal.ir.AccessNode;
69 import jdk.nashorn.internal.ir.BaseNode;
70 import jdk.nashorn.internal.ir.BinaryNode;
71 import jdk.nashorn.internal.ir.Block;
72 import jdk.nashorn.internal.ir.BreakNode;
73 import jdk.nashorn.internal.ir.BreakableNode;
74 import jdk.nashorn.internal.ir.CallNode;
75 import jdk.nashorn.internal.ir.CaseNode;
76 import jdk.nashorn.internal.ir.CatchNode;
77 import jdk.nashorn.internal.ir.ContinueNode;
78 import jdk.nashorn.internal.ir.EmptyNode;
79 import jdk.nashorn.internal.ir.ExecuteNode;
80 import jdk.nashorn.internal.ir.ForNode;
81 import jdk.nashorn.internal.ir.FunctionNode;
82 import jdk.nashorn.internal.ir.LexicalContext;
83 import jdk.nashorn.internal.ir.FunctionNode.CompilationState;
84 import jdk.nashorn.internal.ir.IdentNode;
85 import jdk.nashorn.internal.ir.IfNode;
86 import jdk.nashorn.internal.ir.IndexNode;
87 import jdk.nashorn.internal.ir.LexicalContextNode;
88 import jdk.nashorn.internal.ir.LiteralNode;
89 import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode;
90 import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode.ArrayUnit;
91 import jdk.nashorn.internal.ir.LoopNode;
92 import jdk.nashorn.internal.ir.Node;
93 import jdk.nashorn.internal.ir.ObjectNode;
94 import jdk.nashorn.internal.ir.PropertyNode;
95 import jdk.nashorn.internal.ir.ReturnNode;
96 import jdk.nashorn.internal.ir.RuntimeNode;
97 import jdk.nashorn.internal.ir.RuntimeNode.Request;
98 import jdk.nashorn.internal.ir.SplitNode;
99 import jdk.nashorn.internal.ir.Statement;
100 import jdk.nashorn.internal.ir.SwitchNode;
101 import jdk.nashorn.internal.ir.Symbol;
102 import jdk.nashorn.internal.ir.TernaryNode;
103 import jdk.nashorn.internal.ir.ThrowNode;
104 import jdk.nashorn.internal.ir.TryNode;
105 import jdk.nashorn.internal.ir.UnaryNode;
106 import jdk.nashorn.internal.ir.VarNode;
107 import jdk.nashorn.internal.ir.WhileNode;
108 import jdk.nashorn.internal.ir.WithNode;
109 import jdk.nashorn.internal.ir.debug.ASTWriter;
110 import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
111 import jdk.nashorn.internal.ir.visitor.NodeVisitor;
112 import jdk.nashorn.internal.parser.Lexer.RegexToken;
113 import jdk.nashorn.internal.parser.TokenType;
114 import jdk.nashorn.internal.runtime.Context;
115 import jdk.nashorn.internal.runtime.Debug;
116 import jdk.nashorn.internal.runtime.DebugLogger;
117 import jdk.nashorn.internal.runtime.ECMAException;
118 import jdk.nashorn.internal.runtime.JSType;
119 import jdk.nashorn.internal.runtime.Property;
120 import jdk.nashorn.internal.runtime.PropertyMap;
121 import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
122 import jdk.nashorn.internal.runtime.Scope;
123 import jdk.nashorn.internal.runtime.ScriptFunction;
124 import jdk.nashorn.internal.runtime.ScriptObject;
125 import jdk.nashorn.internal.runtime.ScriptRuntime;
126 import jdk.nashorn.internal.runtime.Source;
127 import jdk.nashorn.internal.runtime.Undefined;
128 import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
129
130 /**
131 * This is the lowest tier of the code generator. It takes lowered ASTs emitted
132 * from Lower and emits Java byte code. The byte code emission logic is broken
133 * out into MethodEmitter. MethodEmitter works internally with a type stack, and
134 * keeps track of the contents of the byte code stack. This way we avoid a large
135 * number of special cases on the form
136 * <pre>
137 * if (type == INT) {
138 * visitInsn(ILOAD, slot);
139 * } else if (type == DOUBLE) {
140 * visitInsn(DOUBLE, slot);
141 * }
142 * </pre>
143 * This quickly became apparent when the code generator was generalized to work
144 * with all types, and not just numbers or objects.
145 * <p>
146 * The CodeGenerator visits nodes only once, tags them as resolved and emits
147 * bytecode for them.
148 */
149 final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContext> {
150
151 /** Name of the Global object, cannot be referred to as .class, @see CodeGenerator */
152 private static final String GLOBAL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "Global";
153
154 /** Name of the ScriptFunctionImpl, cannot be referred to as .class @see FunctionObjectCreator */
155 private static final String SCRIPTFUNCTION_IMPL_OBJECT = Compiler.OBJECTS_PACKAGE + '/' + "ScriptFunctionImpl";
156
157 /** Constant data & installation. The only reason the compiler keeps this is because it is assigned
158 * by reflection in class installation */
159 private final Compiler compiler;
160
161 /** Call site flags given to the code generator to be used for all generated call sites */
162 private final int callSiteFlags;
163
164 /** How many regexp fields have been emitted */
165 private int regexFieldCount;
166
167 /** Line number for last statement. If we encounter a new line number, line number bytecode information
168 * needs to be generated */
169 private int lastLineNumber = -1;
170
171 /** When should we stop caching regexp expressions in fields to limit bytecode size? */
172 private static final int MAX_REGEX_FIELDS = 2 * 1024;
173
174 /** Current method emitter */
175 private MethodEmitter method;
176
177 /** Current compile unit */
178 private CompileUnit unit;
179
180 private static final DebugLogger LOG = new DebugLogger("codegen", "nashorn.codegen.debug");
181
182
183 /**
184 * Constructor.
185 *
186 * @param compiler
187 */
188 CodeGenerator(final Compiler compiler) {
189 super(new CodeGeneratorLexicalContext());
190 this.compiler = compiler;
191 this.callSiteFlags = compiler.getEnv()._callsite_flags;
192 }
193
194 /**
195 * Gets the call site flags, adding the strict flag if the current function
196 * being generated is in strict mode
197 *
198 * @return the correct flags for a call site in the current function
199 */
200 int getCallSiteFlags() {
201 return lc.getCurrentFunction().isStrict() ? callSiteFlags | CALLSITE_STRICT : callSiteFlags;
202 }
203
204 /**
205 * Load an identity node
206 *
207 * @param identNode an identity node to load
208 * @return the method generator used
209 */
210 private MethodEmitter loadIdent(final IdentNode identNode) {
211 final Symbol symbol = identNode.getSymbol();
212
213 if (!symbol.isScope()) {
214 assert symbol.hasSlot() || symbol.isParam();
215 return method.load(symbol);
216 }
217
218 final String name = symbol.getName();
219 final Source source = lc.getCurrentFunction().getSource();
220
221 if (CompilerConstants.__FILE__.name().equals(name)) {
222 return method.load(source.getName());
223 } else if (CompilerConstants.__DIR__.name().equals(name)) {
224 return method.load(source.getBase());
225 } else if (CompilerConstants.__LINE__.name().equals(name)) {
226 return method.load(source.getLine(identNode.position())).convert(Type.OBJECT);
227 } else {
228 assert identNode.getSymbol().isScope() : identNode + " is not in scope!";
229
230 final int flags = CALLSITE_SCOPE | getCallSiteFlags();
231 method.loadCompilerConstant(SCOPE);
232
233 if (isFastScope(symbol)) {
234 // Only generate shared scope getter for fast-scope symbols so we know we can dial in correct scope.
235 if (symbol.getUseCount() > SharedScopeCall.FAST_SCOPE_GET_THRESHOLD) {
236 return loadSharedScopeVar(identNode.getType(), symbol, flags);
237 }
238 return loadFastScopeVar(identNode.getType(), symbol, flags, identNode.isFunction());
239 }
240 return method.dynamicGet(identNode.getType(), identNode.getName(), flags, identNode.isFunction());
241 }
242 }
243
244 /**
245 * Check if this symbol can be accessed directly with a putfield or getfield or dynamic load
246 *
247 * @param function function to check for fast scope
248 * @return true if fast scope
249 */
250 private boolean isFastScope(final Symbol symbol) {
251 if (!symbol.isScope()) {
252 return false;
253 }
254
255 if (!lc.inDynamicScope()) {
256 // If there's no with or eval in context, and the symbol is marked as scoped, it is fast scoped. Such a
257 // symbol must either be global, or its defining block must need scope.
258 assert symbol.isGlobal() || lc.getDefiningBlock(symbol).needsScope() : symbol.getName();
259 return true;
260 }
261
262 if (symbol.isGlobal()) {
263 // Shortcut: if there's a with or eval in context, globals can't be fast scoped
264 return false;
265 }
266
267 // Otherwise, check if there's a dynamic scope between use of the symbol and its definition
268 final String name = symbol.getName();
269 boolean previousWasBlock = false;
270 for (final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) {
271 final LexicalContextNode node = it.next();
272 if (node instanceof Block) {
273 // If this block defines the symbol, then we can fast scope the symbol.
274 final Block block = (Block)node;
275 if (block.getExistingSymbol(name) == symbol) {
276 assert block.needsScope();
277 return true;
278 }
279 previousWasBlock = true;
280 } else {
281 if ((node instanceof WithNode && previousWasBlock) || (node instanceof FunctionNode && CodeGeneratorLexicalContext.isFunctionDynamicScope((FunctionNode)node))) {
282 // If we hit a scope that can have symbols introduced into it at run time before finding the defining
283 // block, the symbol can't be fast scoped. A WithNode only counts if we've immediately seen a block
284 // before - its block. Otherwise, we are currently processing the WithNode's expression, and that's
285 // obviously not subjected to introducing new symbols.
286 return false;
287 }
288 previousWasBlock = false;
289 }
290 }
291 // Should've found the symbol defined in a block
292 throw new AssertionError();
293 }
294
295 private MethodEmitter loadSharedScopeVar(final Type valueType, final Symbol symbol, final int flags) {
296 method.load(isFastScope(symbol) ? getScopeProtoDepth(lc.getCurrentBlock(), symbol) : -1);
297 final SharedScopeCall scopeCall = lc.getScopeGet(unit, valueType, symbol, flags | CALLSITE_FAST_SCOPE);
298 return scopeCall.generateInvoke(method);
299 }
300
301 private MethodEmitter loadFastScopeVar(final Type valueType, final Symbol symbol, final int flags, final boolean isMethod) {
302 loadFastScopeProto(symbol, false);
303 return method.dynamicGet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE, isMethod);
304 }
305
306 private MethodEmitter storeFastScopeVar(final Type valueType, final Symbol symbol, final int flags) {
307 loadFastScopeProto(symbol, true);
308 method.dynamicSet(valueType, symbol.getName(), flags | CALLSITE_FAST_SCOPE);
309 return method;
310 }
311
312 private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
313 int depth = 0;
314 final String name = symbol.getName();
315 for(final Iterator<Block> blocks = lc.getBlocks(startingBlock); blocks.hasNext();) {
316 final Block currentBlock = blocks.next();
317 if (currentBlock.getExistingSymbol(name) == symbol) {
318 return depth;
319 }
320 if (currentBlock.needsScope()) {
321 ++depth;
322 }
323 }
324 return -1;
325 }
326
327 private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
328 final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
329 assert depth != -1;
330 if (depth > 0) {
331 if (swap) {
332 method.swap();
333 }
334 for (int i = 0; i < depth; i++) {
335 method.invoke(ScriptObject.GET_PROTO);
336 }
337 if (swap) {
338 method.swap();
339 }
340 }
341 }
342
343 /**
344 * Generate code that loads this node to the stack. This method is only
345 * public to be accessible from the maps sub package. Do not call externally
346 *
347 * @param node node to load
348 *
349 * @return the method emitter used
350 */
351 MethodEmitter load(final Node node) {
352 return load(node, false);
353 }
354
355 private MethodEmitter load(final Node node, final boolean baseAlreadyOnStack) {
356 final Symbol symbol = node.getSymbol();
357
358 // If we lack symbols, we just generate what we see.
359 if (symbol == null) {
360 node.accept(this);
361 return method;
362 }
363
364 /*
365 * The load may be of type IdentNode, e.g. "x", AccessNode, e.g. "x.y"
366 * or IndexNode e.g. "x[y]". Both AccessNodes and IndexNodes are
367 * BaseNodes and the logic for loading the base object is reused
368 */
369 final CodeGenerator codegen = this;
370
371 node.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
372 @Override
373 public boolean enterIdentNode(final IdentNode identNode) {
374 loadIdent(identNode);
375 return false;
376 }
377
378 @Override
379 public boolean enterAccessNode(final AccessNode accessNode) {
380 if (!baseAlreadyOnStack) {
381 load(accessNode.getBase()).convert(Type.OBJECT);
382 }
383 assert method.peekType().isObject();
384 method.dynamicGet(node.getType(), accessNode.getProperty().getName(), getCallSiteFlags(), accessNode.isFunction());
385 return false;
386 }
387
388 @Override
389 public boolean enterIndexNode(final IndexNode indexNode) {
390 if (!baseAlreadyOnStack) {
391 load(indexNode.getBase()).convert(Type.OBJECT);
392 load(indexNode.getIndex());
393 }
394 method.dynamicGetIndex(node.getType(), getCallSiteFlags(), indexNode.isFunction());
395 return false;
396 }
397
398 @Override
399 public boolean enterFunctionNode(FunctionNode functionNode) {
400 // function nodes will always leave a constructed function object on stack, no need to load the symbol
401 // separately as in enterDefault()
402 functionNode.accept(codegen);
403 return false;
404 }
405
406 @Override
407 public boolean enterDefault(final Node otherNode) {
408 otherNode.accept(codegen); // generate code for whatever we are looking at.
409 method.load(symbol); // load the final symbol to the stack (or nop if no slot, then result is already there)
410 return false;
411 }
412 });
413
414 return method;
415 }
416
417 @Override
418 public boolean enterAccessNode(final AccessNode accessNode) {
419 load(accessNode);
420 return false;
421 }
422
423 /**
424 * Initialize a specific set of vars to undefined. This has to be done at
425 * the start of each method for local variables that aren't passed as
426 * parameters.
427 *
428 * @param symbols list of symbols.
429 */
430 private void initSymbols(final Iterable<Symbol> symbols) {
431 final LinkedList<Symbol> numbers = new LinkedList<>();
432 final LinkedList<Symbol> objects = new LinkedList<>();
433
434 for (final Symbol symbol : symbols) {
435 /*
436 * The following symbols are guaranteed to be defined and thus safe
437 * from having undefined written to them: parameters internals this
438 *
439 * Otherwise we must, unless we perform control/escape analysis,
440 * assign them undefined.
441 */
442 final boolean isInternal = symbol.isParam() || symbol.isInternal() || symbol.isThis() || !symbol.canBeUndefined();
443
444 if (symbol.hasSlot() && !isInternal) {
445 assert symbol.getSymbolType().isNumber() || symbol.getSymbolType().isObject() : "no potentially undefined narrower local vars than doubles are allowed: " + symbol + " in " + lc.getCurrentFunction();
446 if (symbol.getSymbolType().isNumber()) {
447 numbers.add(symbol);
448 } else if (symbol.getSymbolType().isObject()) {
449 objects.add(symbol);
450 }
451 }
452 }
453
454 initSymbols(numbers, Type.NUMBER);
455 initSymbols(objects, Type.OBJECT);
456 }
457
458 private void initSymbols(final LinkedList<Symbol> symbols, final Type type) {
459 if (symbols.isEmpty()) {
460 return;
461 }
462
463 method.loadUndefined(type);
464 while (!symbols.isEmpty()) {
465 final Symbol symbol = symbols.removeFirst();
466 if (!symbols.isEmpty()) {
467 method.dup();
468 }
469 method.store(symbol);
470 }
471 }
472
473 /**
474 * Create symbol debug information.
475 *
476 * @param block block containing symbols.
477 */
478 private void symbolInfo(final Block block) {
479 for (final Symbol symbol : block.getSymbols()) {
480 if (symbol.hasSlot()) {
481 method.localVariable(symbol, block.getEntryLabel(), block.getBreakLabel());
482 }
483 }
484 }
485
486 @Override
487 public boolean enterBlock(final Block block) {
488 method.label(block.getEntryLabel());
489 initLocals(block);
490
491 return true;
492 }
493
494 @Override
495 public Node leaveBlock(final Block block) {
496 method.label(block.getBreakLabel());
497 symbolInfo(block);
498
499 if (block.needsScope() && !block.isTerminal()) {
500 popBlockScope(block);
501 }
502 return block;
503 }
504
505 private void popBlockScope(final Block block) {
506 final Label exitLabel = new Label("block_exit");
507 final Label recoveryLabel = new Label("block_catch");
508 final Label skipLabel = new Label("skip_catch");
509
510 /* pop scope a la try-finally */
511 method.loadCompilerConstant(SCOPE);
512 method.invoke(ScriptObject.GET_PROTO);
513 method.storeCompilerConstant(SCOPE);
514 method._goto(skipLabel);
515 method.label(exitLabel);
516
517 method._catch(recoveryLabel);
518 method.loadCompilerConstant(SCOPE);
519 method.invoke(ScriptObject.GET_PROTO);
520 method.storeCompilerConstant(SCOPE);
521 method.athrow();
522 method.label(skipLabel);
523 method._try(block.getEntryLabel(), exitLabel, recoveryLabel, Throwable.class);
524 }
525
526 @Override
527 public boolean enterBreakNode(final BreakNode breakNode) {
528 lineNumber(breakNode);
529
530 final BreakableNode breakFrom = lc.getBreakable(breakNode.getLabel());
531 for (int i = 0; i < lc.getScopeNestingLevelTo(breakFrom); i++) {
532 closeWith();
533 }
534 method.splitAwareGoto(lc, breakFrom.getBreakLabel());
535
536 return false;
537 }
538
539 private int loadArgs(final List<Node> args) {
540 return loadArgs(args, null, false, args.size());
541 }
542
543 private int loadArgs(final List<Node> args, final String signature, final boolean isVarArg, final int argCount) {
544 // arg have already been converted to objects here.
545 if (isVarArg || argCount > LinkerCallSite.ARGLIMIT) {
546 loadArgsArray(args);
547 return 1;
548 }
549
550 // pad with undefined if size is too short. argCount is the real number of args
551 int n = 0;
552 final Type[] params = signature == null ? null : Type.getMethodArguments(signature);
553 for (final Node arg : args) {
554 assert arg != null;
555 load(arg);
556 if (n >= argCount) {
557 method.pop(); // we had to load the arg for its side effects
558 } else if (params != null) {
559 method.convert(params[n]);
560 }
561 n++;
562 }
563
564 while (n < argCount) {
565 method.loadUndefined(Type.OBJECT);
566 n++;
567 }
568
569 return argCount;
570 }
571
572 @Override
573 public boolean enterCallNode(final CallNode callNode) {
574 lineNumber(callNode);
575
576 final List<Node> args = callNode.getArgs();
577 final Node function = callNode.getFunction();
578 final Block currentBlock = lc.getCurrentBlock();
579 final CodeGeneratorLexicalContext codegenLexicalContext = lc;
580
581 function.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
582
583 private MethodEmitter sharedScopeCall(final IdentNode identNode, final int flags) {
584 final Symbol symbol = identNode.getSymbol();
585 int scopeCallFlags = flags;
586 method.loadCompilerConstant(SCOPE);
587 if (isFastScope(symbol)) {
588 method.load(getScopeProtoDepth(currentBlock, symbol));
589 scopeCallFlags |= CALLSITE_FAST_SCOPE;
590 } else {
591 method.load(-1); // Bypass fast-scope code in shared callsite
592 }
593 loadArgs(args);
594 final Type[] paramTypes = method.getTypesFromStack(args.size());
595 final SharedScopeCall scopeCall = codegenLexicalContext.getScopeCall(unit, symbol, identNode.getType(), callNode.getType(), paramTypes, scopeCallFlags);
596 return scopeCall.generateInvoke(method);
597 }
598
599 private void scopeCall(final IdentNode node, final int flags) {
600 load(node);
601 method.convert(Type.OBJECT); // foo() makes no sense if foo == 3
602 // ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
603 method.loadNull(); //the 'this'
604 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), flags);
605 }
606
607 private void evalCall(final IdentNode node, final int flags) {
608 load(node);
609 method.convert(Type.OBJECT); // foo() makes no sense if foo == 3
610
611 final Label not_eval = new Label("not_eval");
612 final Label eval_done = new Label("eval_done");
613
614 // check if this is the real built-in eval
615 method.dup();
616 globalIsEval();
617
618 method.ifeq(not_eval);
619 // We don't need ScriptFunction object for 'eval'
620 method.pop();
621
622 method.loadCompilerConstant(SCOPE); // Load up self (scope).
623
624 final CallNode.EvalArgs evalArgs = callNode.getEvalArgs();
625 // load evaluated code
626 load(evalArgs.getCode());
627 method.convert(Type.OBJECT);
628 // special/extra 'eval' arguments
629 load(evalArgs.getThis());
630 method.load(evalArgs.getLocation());
631 method.load(evalArgs.getStrictMode());
632 method.convert(Type.OBJECT);
633
634 // direct call to Global.directEval
635 globalDirectEval();
636 method.convert(callNode.getType());
637 method._goto(eval_done);
638
639 method.label(not_eval);
640 // This is some scope 'eval' or global eval replaced by user
641 // but not the built-in ECMAScript 'eval' function call
642 method.loadNull();
643 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), flags);
644
645 method.label(eval_done);
646 }
647
648 @Override
649 public boolean enterIdentNode(final IdentNode node) {
650 final Symbol symbol = node.getSymbol();
651
652 if (symbol.isScope()) {
653 final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
654 final int useCount = symbol.getUseCount();
655
656 // Threshold for generating shared scope callsite is lower for fast scope symbols because we know
657 // we can dial in the correct scope. However, we also need to enable it for non-fast scopes to
658 // support huge scripts like mandreel.js.
659 if (callNode.isEval()) {
660 evalCall(node, flags);
661 } else if (useCount <= SharedScopeCall.FAST_SCOPE_CALL_THRESHOLD
662 || (!isFastScope(symbol) && useCount <= SharedScopeCall.SLOW_SCOPE_CALL_THRESHOLD)
663 || CodeGenerator.this.lc.inDynamicScope()) {
664 scopeCall(node, flags);
665 } else {
666 sharedScopeCall(node, flags);
667 }
668 assert method.peekType().equals(callNode.getType()) : method.peekType() + "!=" + callNode.getType();
669 } else {
670 enterDefault(node);
671 }
672
673 return false;
674 }
675
676 @Override
677 public boolean enterAccessNode(final AccessNode node) {
678 load(node.getBase());
679 method.convert(Type.OBJECT);
680 method.dup();
681 method.dynamicGet(node.getType(), node.getProperty().getName(), getCallSiteFlags(), true);
682 method.swap();
683 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags());
684 assert method.peekType().equals(callNode.getType());
685
686 return false;
687 }
688
689 @Override
690 public boolean enterFunctionNode(final FunctionNode origCallee) {
691 // NOTE: visiting the callee will leave a constructed ScriptFunction object on the stack if
692 // callee.needsCallee() == true
693 final FunctionNode callee = (FunctionNode)origCallee.accept(CodeGenerator.this);
694
695 final boolean isVarArg = callee.isVarArg();
696 final int argCount = isVarArg ? -1 : callee.getParameters().size();
697
698 final String signature = new FunctionSignature(true, callee.needsCallee(), callee.getReturnType(), isVarArg ? null : callee.getParameters()).toString();
699
700 if (callee.isStrict()) { // self is undefined
701 method.loadUndefined(Type.OBJECT);
702 } else { // get global from scope (which is the self)
703 globalInstance();
704 }
705 loadArgs(args, signature, isVarArg, argCount);
706 assert callee.getCompileUnit() != null : "no compile unit for " + callee.getName() + " " + Debug.id(callee) + " " + callNode;
707 method.invokestatic(callee.getCompileUnit().getUnitClassName(), callee.getName(), signature);
708 assert method.peekType().equals(callee.getReturnType()) : method.peekType() + " != " + callee.getReturnType();
709 return false;
710 }
711
712 @Override
713 public boolean enterIndexNode(final IndexNode node) {
714 load(node.getBase());
715 method.convert(Type.OBJECT);
716 method.dup();
717 load(node.getIndex());
718 final Type indexType = node.getIndex().getType();
719 if (indexType.isObject() || indexType.isBoolean()) {
720 method.convert(Type.OBJECT); //TODO
721 }
722 method.dynamicGetIndex(node.getType(), getCallSiteFlags(), true);
723 method.swap();
724 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags());
725 assert method.peekType().equals(callNode.getType());
726
727 return false;
728 }
729
730 @Override
731 protected boolean enterDefault(final Node node) {
732 // Load up function.
733 load(function);
734 method.convert(Type.OBJECT); //TODO, e.g. booleans can be used as functions
735 method.loadNull(); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
736 method.dynamicCall(callNode.getType(), 2 + loadArgs(args), getCallSiteFlags() | CALLSITE_SCOPE);
737 assert method.peekType().equals(callNode.getType());
738
739 return false;
740 }
741 });
742
743 method.store(callNode.getSymbol());
744
745 return false;
746 }
747
748 @Override
749 public boolean enterContinueNode(final ContinueNode continueNode) {
750 lineNumber(continueNode);
751
752 final LoopNode continueTo = lc.getContinueTo(continueNode.getLabel());
753 for (int i = 0; i < lc.getScopeNestingLevelTo(continueTo); i++) {
754 closeWith();
755 }
756 method.splitAwareGoto(lc, continueTo.getContinueLabel());
757
758 return false;
759 }
760
761 @Override
762 public boolean enterEmptyNode(final EmptyNode emptyNode) {
763 lineNumber(emptyNode);
764
765 return false;
766 }
767
768 @Override
769 public boolean enterExecuteNode(final ExecuteNode executeNode) {
770 lineNumber(executeNode);
771
772 final Node expression = executeNode.getExpression();
773 expression.accept(this);
774
775 return false;
776 }
777
778 @Override
779 public boolean enterForNode(final ForNode forNode) {
780 lineNumber(forNode);
781
782 if (forNode.isForIn()) {
783 enterForIn(forNode);
784 } else {
785 enterFor(forNode);
786 }
787
788 return false;
789 }
790
791 private void enterFor(final ForNode forNode) {
792 final Node init = forNode.getInit();
793 final Node test = forNode.getTest();
794 final Block body = forNode.getBody();
795 final Node modify = forNode.getModify();
796
797 if (init != null) {
798 init.accept(this);
799 }
800
801 final Label loopLabel = new Label("loop");
802 final Label testLabel = new Label("test");
803
804 method._goto(testLabel);
805 method.label(loopLabel);
806 body.accept(this);
807 method.label(forNode.getContinueLabel());
808
809 if (!body.isTerminal() && modify != null) {
810 load(modify);
811 }
812
813 method.label(testLabel);
814 if (test != null) {
815 new BranchOptimizer(this, method).execute(test, loopLabel, true);
816 } else {
817 method._goto(loopLabel);
818 }
819
820 method.label(forNode.getBreakLabel());
821 }
822
823 private void enterForIn(final ForNode forNode) {
824 final Block body = forNode.getBody();
825 final Node modify = forNode.getModify();
826
827 final Symbol iter = forNode.getIterator();
828 final Label loopLabel = new Label("loop");
829
830 Node init = forNode.getInit();
831
832 // We have to evaluate the optional initializer expression
833 // of the iterator variable of the for-in statement.
834 if (init instanceof VarNode) {
835 init.accept(this);
836 init = ((VarNode)init).getName();
837 }
838
839 load(modify);
840 assert modify.getType().isObject();
841 method.invoke(forNode.isForEach() ? ScriptRuntime.TO_VALUE_ITERATOR : ScriptRuntime.TO_PROPERTY_ITERATOR);
842 method.store(iter);
843 method._goto(forNode.getContinueLabel());
844 method.label(loopLabel);
845
846 new Store<Node>(init) {
847 @Override
848 protected void storeNonDiscard() {
849 return;
850 }
851 @Override
852 protected void evaluate() {
853 method.load(iter);
854 method.invoke(interfaceCallNoLookup(Iterator.class, "next", Object.class));
855 }
856 }.store();
857
858 body.accept(this);
859
860 method.label(forNode.getContinueLabel());
861 method.load(iter);
862 method.invoke(interfaceCallNoLookup(Iterator.class, "hasNext", boolean.class));
863 method.ifne(loopLabel);
864 method.label(forNode.getBreakLabel());
865 }
866
867 /**
868 * Initialize the slots in a frame to undefined.
869 *
870 * @param block block with local vars.
871 */
872 private void initLocals(final Block block) {
873 lc.nextFreeSlot(block);
874
875 final boolean isFunctionBody = lc.isFunctionBody();
876
877 final FunctionNode function = lc.getCurrentFunction();
878 if (isFunctionBody) {
879 /* Fix the predefined slots so they have numbers >= 0, like varargs. */
880 if (function.needsParentScope()) {
881 initParentScope();
882 }
883 if (function.needsArguments()) {
884 initArguments(function);
885 }
886 }
887
888 /*
889 * Determine if block needs scope, if not, just do initSymbols for this block.
890 */
891 if (block.needsScope()) {
892 /*
893 * Determine if function is varargs and consequently variables have to
894 * be in the scope.
895 */
896 final boolean varsInScope = function.allVarsInScope();
897
898 // TODO for LET we can do better: if *block* does not contain any eval/with, we don't need its vars in scope.
899
900 final List<String> nameList = new ArrayList<>();
901 final List<Symbol> locals = new ArrayList<>();
902
903 // Initalize symbols and values
904 final List<Symbol> newSymbols = new ArrayList<>();
905 final List<Symbol> values = new ArrayList<>();
906
907 final boolean hasArguments = function.needsArguments();
908
909 for (final Symbol symbol : block.getSymbols()) {
910
911 if (symbol.isInternal() || symbol.isThis() || symbol.isTemp()) {
912 continue;
913 }
914
915 if (symbol.isVar()) {
916 if (varsInScope || symbol.isScope()) {
917 nameList.add(symbol.getName());
918 newSymbols.add(symbol);
919 values.add(null);
920 assert symbol.isScope() : "scope for " + symbol + " should have been set in Lower already " + function.getName();
921 assert !symbol.hasSlot() : "slot for " + symbol + " should have been removed in Lower already" + function.getName();
922 } else {
923 assert symbol.hasSlot() : symbol + " should have a slot only, no scope";
924 locals.add(symbol);
925 }
926 } else if (symbol.isParam() && (varsInScope || hasArguments || symbol.isScope())) {
927 nameList.add(symbol.getName());
928 newSymbols.add(symbol);
929 values.add(hasArguments ? null : symbol);
930 assert symbol.isScope() : "scope for " + symbol + " should have been set in Lower already " + function.getName() + " varsInScope="+varsInScope+" hasArguments="+hasArguments+" symbol.isScope()=" + symbol.isScope();
931 assert !(hasArguments && symbol.hasSlot()) : "slot for " + symbol + " should have been removed in Lower already " + function.getName();
932 }
933 }
934
935 // we may have locals that need to be initialized
936 initSymbols(locals);
937
938 /*
939 * Create a new object based on the symbols and values, generate
940 * bootstrap code for object
941 */
942 final FieldObjectCreator<Symbol> foc = new FieldObjectCreator<Symbol>(this, nameList, newSymbols, values, true, hasArguments) {
943 @Override
944 protected Type getValueType(final Symbol value) {
945 return value.getSymbolType();
946 }
947
948 @Override
949 protected void loadValue(final Symbol value) {
950 method.load(value);
951 }
952
953 @Override
954 protected void loadScope(MethodEmitter m) {
955 if (function.needsParentScope()) {
956 m.loadCompilerConstant(SCOPE);
957 } else {
958 m.loadNull();
959 }
960 }
961 };
962 foc.makeObject(method);
963
964 // runScript(): merge scope into global
965 if (isFunctionBody && function.isProgram()) {
966 method.invoke(ScriptRuntime.MERGE_SCOPE);
967 }
968
969 method.storeCompilerConstant(SCOPE);
970 } else {
971 // Since we don't have a scope, parameters didn't get assigned array indices by the FieldObjectCreator, so
972 // we need to assign them separately here.
973 int nextParam = 0;
974 if (isFunctionBody && function.isVarArg()) {
975 for (final IdentNode param : function.getParameters()) {
976 param.getSymbol().setFieldIndex(nextParam++);
977 }
978 }
979
980 initSymbols(block.getSymbols());
981 }
982
983 // Debugging: print symbols? @see --print-symbols flag
984 printSymbols(block, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
985 }
986
987 private void initArguments(final FunctionNode function) {
988 method.loadCompilerConstant(VARARGS);
989 if (function.needsCallee()) {
990 method.loadCompilerConstant(CALLEE);
991 } else {
992 // If function is strict mode, "arguments.callee" is not populated, so we don't necessarily need the
993 // caller.
994 assert function.isStrict();
995 method.loadNull();
996 }
997 method.load(function.getParameters().size());
998 globalAllocateArguments();
999 method.storeCompilerConstant(ARGUMENTS);
1000 }
1001
1002 private void initParentScope() {
1003 method.loadCompilerConstant(CALLEE);
1004 method.invoke(ScriptFunction.GET_SCOPE);
1005 method.storeCompilerConstant(SCOPE);
1006 }
1007
1008 @Override
1009 public boolean enterFunctionNode(final FunctionNode functionNode) {
1010 if (functionNode.isLazy()) {
1011 // Must do it now; can't postpone it until leaveFunctionNode()
1012 newFunctionObject(functionNode, functionNode);
1013 return false;
1014 }
1015
1016 LOG.info("=== BEGIN ", functionNode.getName());
1017
1018 assert functionNode.getCompileUnit() != null : "no compile unit for " + functionNode.getName() + " " + Debug.id(functionNode);
1019 unit = lc.pushCompileUnit(functionNode.getCompileUnit());
1020 assert lc.hasCompileUnits();
1021
1022 method = lc.pushMethodEmitter(unit.getClassEmitter().method(functionNode));
1023 // Mark end for variable tables.
1024 method.begin();
1025
1026 return true;
1027 }
1028
1029 @Override
1030 public Node leaveFunctionNode(final FunctionNode functionNode) {
1031 try {
1032 method.end(); // wrap up this method
1033 unit = lc.popCompileUnit(functionNode.getCompileUnit());
1034 method = lc.popMethodEmitter(method);
1035 LOG.info("=== END ", functionNode.getName());
1036
1037 final FunctionNode newFunctionNode = functionNode.setState(lc, CompilationState.EMITTED);
1038
1039 newFunctionObject(newFunctionNode, functionNode);
1040 return newFunctionNode;
1041 } catch (final Throwable t) {
1042 Context.printStackTrace(t);
1043 final VerifyError e = new VerifyError("Code generation bug in \"" + functionNode.getName() + "\": likely stack misaligned: " + t + " " + functionNode.getSource().getName());
1044 e.initCause(t);
1045 throw e;
1046 }
1047 }
1048
1049 @Override
1050 public boolean enterIdentNode(final IdentNode identNode) {
1051 return false;
1052 }
1053
1054 @Override
1055 public boolean enterIfNode(final IfNode ifNode) {
1056 lineNumber(ifNode);
1057
1058 final Node test = ifNode.getTest();
1059 final Block pass = ifNode.getPass();
1060 final Block fail = ifNode.getFail();
1061
1062 final Label failLabel = new Label("if_fail");
1063 final Label afterLabel = fail == null ? failLabel : new Label("if_done");
1064
1065 new BranchOptimizer(this, method).execute(test, failLabel, false);
1066
1067 boolean passTerminal = false;
1068 boolean failTerminal = false;
1069
1070 pass.accept(this);
1071 if (!pass.hasTerminalFlags()) {
1072 method._goto(afterLabel); //don't fallthru to fail block
1073 } else {
1074 passTerminal = pass.isTerminal();
1075 }
1076
1077 if (fail != null) {
1078 method.label(failLabel);
1079 fail.accept(this);
1080 failTerminal = fail.isTerminal();
1081 }
1082
1083 //if if terminates, put the after label there
1084 if (!passTerminal || !failTerminal) {
1085 method.label(afterLabel);
1086 }
1087
1088 return false;
1089 }
1090
1091 @Override
1092 public boolean enterIndexNode(final IndexNode indexNode) {
1093 load(indexNode);
1094 return false;
1095 }
1096
1097 private void lineNumber(final Statement statement) {
1098 final int lineNumber = statement.getLineNumber();
1099 if (lineNumber != lastLineNumber) {
1100 method.lineNumber(statement.getLineNumber());
1101 }
1102 lastLineNumber = lineNumber;
1103 }
1104
1105 /**
1106 * Load a list of nodes as an array of a specific type
1107 * The array will contain the visited nodes.
1108 *
1109 * @param arrayLiteralNode the array of contents
1110 * @param arrayType the type of the array, e.g. ARRAY_NUMBER or ARRAY_OBJECT
1111 *
1112 * @return the method generator that was used
1113 */
1114 private MethodEmitter loadArray(final ArrayLiteralNode arrayLiteralNode, final ArrayType arrayType) {
1115 assert arrayType == Type.INT_ARRAY || arrayType == Type.NUMBER_ARRAY || arrayType == Type.OBJECT_ARRAY;
1116
1117 final Node[] nodes = arrayLiteralNode.getValue();
1118 final Object presets = arrayLiteralNode.getPresets();
1119 final int[] postsets = arrayLiteralNode.getPostsets();
1120 final Class<?> type = arrayType.getTypeClass();
1121 final List<ArrayUnit> units = arrayLiteralNode.getUnits();
1122
1123 loadConstant(presets);
1124
1125 final Type elementType = arrayType.getElementType();
1126
1127 if (units != null) {
1128 final MethodEmitter savedMethod = method;
1129
1130 for (final ArrayUnit arrayUnit : units) {
1131 unit = lc.pushCompileUnit(arrayUnit.getCompileUnit());
1132
1133 final String className = unit.getUnitClassName();
1134 final String name = lc.getCurrentFunction().uniqueName(SPLIT_PREFIX.symbolName());
1135 final String signature = methodDescriptor(type, Object.class, ScriptFunction.class, ScriptObject.class, type);
1136
1137 final MethodEmitter me = unit.getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature);
1138 method = lc.pushMethodEmitter(me);
1139
1140 method.setFunctionNode(lc.getCurrentFunction());
1141 method.begin();
1142
1143 fixScopeSlot();
1144
1145 method.load(arrayType, SPLIT_ARRAY_ARG.slot());
1146
1147 for (int i = arrayUnit.getLo(); i < arrayUnit.getHi(); i++) {
1148 storeElement(nodes, elementType, postsets[i]);
1149 }
1150
1151 method._return();
1152 method.end();
1153 method = lc.popMethodEmitter(me);
1154
1155 assert method == savedMethod;
1156 method.loadCompilerConstant(THIS);
1157 method.swap();
1158 method.loadCompilerConstant(CALLEE);
1159 method.swap();
1160 method.loadCompilerConstant(SCOPE);
1161 method.swap();
1162 method.invokestatic(className, name, signature);
1163
1164 unit = lc.popCompileUnit(unit);
1165 }
1166
1167 return method;
1168 }
1169
1170 for (final int postset : postsets) {
1171 storeElement(nodes, elementType, postset);
1172 }
1173
1174 return method;
1175 }
1176
1177 private void storeElement(final Node[] nodes, final Type elementType, final int index) {
1178 method.dup();
1179 method.load(index);
1180
1181 final Node element = nodes[index];
1182
1183 if (element == null) {
1184 method.loadEmpty(elementType);
1185 } else {
1186 assert elementType.isEquivalentTo(element.getType()) : "array element type doesn't match array type";
1187 load(element);
1188 }
1189
1190 method.arraystore();
1191 }
1192
1193 private MethodEmitter loadArgsArray(final List<Node> args) {
1194 final Object[] array = new Object[args.size()];
1195 loadConstant(array);
1196
1197 for (int i = 0; i < args.size(); i++) {
1198 method.dup();
1199 method.load(i);
1200 load(args.get(i)).convert(Type.OBJECT); //has to be upcast to object or we fail
1201 method.arraystore();
1202 }
1203
1204 return method;
1205 }
1206
1207 /**
1208 * Load a constant from the constant array. This is only public to be callable from the objects
1209 * subpackage. Do not call directly.
1210 *
1211 * @param string string to load
1212 */
1213 void loadConstant(final String string) {
1214 final String unitClassName = unit.getUnitClassName();
1215 final ClassEmitter classEmitter = unit.getClassEmitter();
1216 final int index = compiler.getConstantData().add(string);
1217
1218 method.load(index);
1219 method.invokestatic(unitClassName, GET_STRING.symbolName(), methodDescriptor(String.class, int.class));
1220 classEmitter.needGetConstantMethod(String.class);
1221 }
1222
1223 /**
1224 * Load a constant from the constant array. This is only public to be callable from the objects
1225 * subpackage. Do not call directly.
1226 *
1227 * @param object object to load
1228 */
1229 void loadConstant(final Object object) {
1230 final String unitClassName = unit.getUnitClassName();
1231 final ClassEmitter classEmitter = unit.getClassEmitter();
1232 final int index = compiler.getConstantData().add(object);
1233 final Class<?> cls = object.getClass();
1234
1235 if (cls == PropertyMap.class) {
1236 method.load(index);
1237 method.invokestatic(unitClassName, GET_MAP.symbolName(), methodDescriptor(PropertyMap.class, int.class));
1238 classEmitter.needGetConstantMethod(PropertyMap.class);
1239 } else if (cls.isArray()) {
1240 method.load(index);
1241 final String methodName = ClassEmitter.getArrayMethodName(cls);
1242 method.invokestatic(unitClassName, methodName, methodDescriptor(cls, int.class));
1243 classEmitter.needGetConstantMethod(cls);
1244 } else {
1245 method.loadConstants().load(index).arrayload();
1246 if (cls != Object.class) {
1247 method.checkcast(cls);
1248 }
1249 }
1250 }
1251
1252 // literal values
1253 private MethodEmitter load(final LiteralNode<?> node) {
1254 final Object value = node.getValue();
1255
1256 if (value == null) {
1257 method.loadNull();
1258 } else if (value instanceof Undefined) {
1259 method.loadUndefined(Type.OBJECT);
1260 } else if (value instanceof String) {
1261 final String string = (String)value;
1262
1263 if (string.length() > (MethodEmitter.LARGE_STRING_THRESHOLD / 3)) { // 3 == max bytes per encoded char
1264 loadConstant(string);
1265 } else {
1266 method.load(string);
1267 }
1268 } else if (value instanceof RegexToken) {
1269 loadRegex((RegexToken)value);
1270 } else if (value instanceof Boolean) {
1271 method.load((Boolean)value);
1272 } else if (value instanceof Integer) {
1273 method.load((Integer)value);
1274 } else if (value instanceof Long) {
1275 method.load((Long)value);
1276 } else if (value instanceof Double) {
1277 method.load((Double)value);
1278 } else if (node instanceof ArrayLiteralNode) {
1279 final ArrayType type = (ArrayType)node.getType();
1280 loadArray((ArrayLiteralNode)node, type);
1281 globalAllocateArray(type);
1282 } else {
1283 assert false : "Unknown literal for " + node.getClass() + " " + value.getClass() + " " + value;
1284 }
1285
1286 return method;
1287 }
1288
1289 private MethodEmitter loadRegexToken(final RegexToken value) {
1290 method.load(value.getExpression());
1291 method.load(value.getOptions());
1292 return globalNewRegExp();
1293 }
1294
1295 private MethodEmitter loadRegex(final RegexToken regexToken) {
1296 if (regexFieldCount > MAX_REGEX_FIELDS) {
1297 return loadRegexToken(regexToken);
1298 }
1299 // emit field
1300 final String regexName = lc.getCurrentFunction().uniqueName(REGEX_PREFIX.symbolName());
1301 final ClassEmitter classEmitter = unit.getClassEmitter();
1302
1303 classEmitter.field(EnumSet.of(PRIVATE, STATIC), regexName, Object.class);
1304 regexFieldCount++;
1305
1306 // get field, if null create new regex, finally clone regex object
1307 method.getStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
1308 method.dup();
1309 final Label cachedLabel = new Label("cached");
1310 method.ifnonnull(cachedLabel);
1311
1312 method.pop();
1313 loadRegexToken(regexToken);
1314 method.dup();
1315 method.putStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
1316
1317 method.label(cachedLabel);
1318 globalRegExpCopy();
1319
1320 return method;
1321 }
1322
1323 @SuppressWarnings("rawtypes")
1324 @Override
1325 public boolean enterLiteralNode(final LiteralNode literalNode) {
1326 assert literalNode.getSymbol() != null : literalNode + " has no symbol";
1327 load(literalNode).store(literalNode.getSymbol());
1328 return false;
1329 }
1330
1331 @Override
1332 public boolean enterObjectNode(final ObjectNode objectNode) {
1333 final List<Node> elements = objectNode.getElements();
1334 final int size = elements.size();
1335
1336 final List<String> keys = new ArrayList<>();
1337 final List<Symbol> symbols = new ArrayList<>();
1338 final List<Node> values = new ArrayList<>();
1339
1340 boolean hasGettersSetters = false;
1341
1342 for (int i = 0; i < size; i++) {
1343 final PropertyNode propertyNode = (PropertyNode)elements.get(i);
1344 final Node value = propertyNode.getValue();
1345 final String key = propertyNode.getKeyName();
1346 final Symbol symbol = value == null ? null : propertyNode.getSymbol();
1347
1348 if (value == null) {
1349 hasGettersSetters = true;
1350 }
1351
1352 keys.add(key);
1353 symbols.add(symbol);
1354 values.add(value);
1355 }
1356
1357 new FieldObjectCreator<Node>(this, keys, symbols, values) {
1358 @Override
1359 protected Type getValueType(final Node node) {
1360 return node.getType();
1361 }
1362
1363 @Override
1364 protected void loadValue(final Node node) {
1365 load(node);
1366 }
1367
1368 /**
1369 * Ensure that the properties start out as object types so that
1370 * we can do putfield initializations instead of dynamicSetIndex
1371 * which would be the case to determine initial property type
1372 * otherwise.
1373 *
1374 * Use case, it's very expensive to do a million var x = {a:obj, b:obj}
1375 * just to have to invalidate them immediately on initialization
1376 *
1377 * see NASHORN-594
1378 */
1379 @Override
1380 protected MapCreator newMapCreator(final Class<?> fieldObjectClass) {
1381 return new MapCreator(fieldObjectClass, keys, symbols) {
1382 @Override
1383 protected int getPropertyFlags(final Symbol symbol, final boolean isVarArg) {
1384 return super.getPropertyFlags(symbol, isVarArg) | Property.IS_ALWAYS_OBJECT;
1385 }
1386 };
1387 }
1388
1389 }.makeObject(method);
1390
1391 method.dup();
1392 globalObjectPrototype();
1393 method.invoke(ScriptObject.SET_PROTO);
1394
1395 if (!hasGettersSetters) {
1396 method.store(objectNode.getSymbol());
1397 return false;
1398 }
1399
1400 for (final Node element : elements) {
1401 final PropertyNode propertyNode = (PropertyNode)element;
1402 final Object key = propertyNode.getKey();
1403 final FunctionNode getter = propertyNode.getGetter();
1404 final FunctionNode setter = propertyNode.getSetter();
1405
1406 if (getter == null && setter == null) {
1407 continue;
1408 }
1409
1410 method.dup().loadKey(key);
1411
1412 if (getter == null) {
1413 method.loadNull();
1414 } else {
1415 getter.accept(this);
1416 }
1417
1418 if (setter == null) {
1419 method.loadNull();
1420 } else {
1421 setter.accept(this);
1422 }
1423
1424 method.invoke(ScriptObject.SET_USER_ACCESSORS);
1425 }
1426
1427 method.store(objectNode.getSymbol());
1428
1429 return false;
1430 }
1431
1432 @Override
1433 public boolean enterReturnNode(final ReturnNode returnNode) {
1434 lineNumber(returnNode);
1435
1436 method.registerReturn();
1437
1438 final Type returnType = lc.getCurrentFunction().getReturnType();
1439
1440 final Node expression = returnNode.getExpression();
1441 if (expression != null) {
1442 load(expression);
1443 } else {
1444 method.loadUndefined(returnType);
1445 }
1446
1447 method._return(returnType);
1448
1449 return false;
1450 }
1451
1452 private static boolean isNullLiteral(final Node node) {
1453 return node instanceof LiteralNode<?> && ((LiteralNode<?>) node).isNull();
1454 }
1455
1456 private boolean nullCheck(final RuntimeNode runtimeNode, final List<Node> args, final String signature) {
1457 final Request request = runtimeNode.getRequest();
1458
1459 if (!Request.isEQ(request) && !Request.isNE(request)) {
1460 return false;
1461 }
1462
1463 assert args.size() == 2 : "EQ or NE or TYPEOF need two args";
1464
1465 Node lhs = args.get(0);
1466 Node rhs = args.get(1);
1467
1468 if (isNullLiteral(lhs)) {
1469 final Node tmp = lhs;
1470 lhs = rhs;
1471 rhs = tmp;
1472 }
1473
1474 if (isNullLiteral(rhs)) {
1475 final Label trueLabel = new Label("trueLabel");
1476 final Label falseLabel = new Label("falseLabel");
1477 final Label endLabel = new Label("end");
1478
1479 load(lhs);
1480 method.dup();
1481 if (Request.isEQ(request)) {
1482 method.ifnull(trueLabel);
1483 } else if (Request.isNE(request)) {
1484 method.ifnonnull(trueLabel);
1485 } else {
1486 assert false : "Invalid request " + request;
1487 }
1488
1489 method.label(falseLabel);
1490 load(rhs);
1491 method.invokestatic(CompilerConstants.className(ScriptRuntime.class), request.toString(), signature);
1492 method._goto(endLabel);
1493
1494 method.label(trueLabel);
1495 // if NE (not strict) this can be "undefined != null" which is supposed to be false
1496 if (request == Request.NE) {
1497 method.loadUndefined(Type.OBJECT);
1498 final Label isUndefined = new Label("isUndefined");
1499 final Label afterUndefinedCheck = new Label("afterUndefinedCheck");
1500 method.if_acmpeq(isUndefined);
1501 // not undefined
1502 method.load(true);
1503 method._goto(afterUndefinedCheck);
1504 method.label(isUndefined);
1505 method.load(false);
1506 method.label(afterUndefinedCheck);
1507 } else {
1508 method.pop();
1509 method.load(true);
1510 }
1511 method.label(endLabel);
1512 method.convert(runtimeNode.getType());
1513 method.store(runtimeNode.getSymbol());
1514
1515 return true;
1516 }
1517
1518 return false;
1519 }
1520
1521 private boolean specializationCheck(final RuntimeNode.Request request, final Node node, final List<Node> args) {
1522 if (!request.canSpecialize()) {
1523 return false;
1524 }
1525
1526 assert args.size() == 2;
1527 final Type returnType = node.getType();
1528
1529 load(args.get(0));
1530 load(args.get(1));
1531
1532 Request finalRequest = request;
1533
1534 //if the request is a comparison, i.e. one that can be reversed
1535 //it keeps its semantic, but make sure that the object comes in
1536 //last
1537 final Request reverse = Request.reverse(request);
1538 if (method.peekType().isObject() && reverse != null) { //rhs is object
1539 if (!method.peekType(1).isObject()) { //lhs is not object
1540 method.swap(); //prefer object as lhs
1541 finalRequest = reverse;
1542 }
1543 }
1544
1545 method.dynamicRuntimeCall(
1546 new SpecializedRuntimeNode(
1547 finalRequest,
1548 new Type[] {
1549 method.peekType(1),
1550 method.peekType()
1551 },
1552 returnType).getInitialName(),
1553 returnType,
1554 finalRequest);
1555
1556 method.convert(node.getType());
1557 method.store(node.getSymbol());
1558
1559 return true;
1560 }
1561
1562 private static boolean isReducible(final Request request) {
1563 return Request.isComparison(request) || request == Request.ADD;
1564 }
1565
1566 @Override
1567 public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
1568 /*
1569 * First check if this should be something other than a runtime node
1570 * AccessSpecializer might have changed the type
1571 *
1572 * TODO - remove this - Access Specializer will always know after Attr/Lower
1573 */
1574 if (runtimeNode.isPrimitive() && !runtimeNode.isFinal() && isReducible(runtimeNode.getRequest())) {
1575 final Node lhs = runtimeNode.getArgs().get(0);
1576 assert runtimeNode.getArgs().size() > 1 : runtimeNode + " must have two args";
1577 final Node rhs = runtimeNode.getArgs().get(1);
1578
1579 final Type type = runtimeNode.getType();
1580 final Symbol symbol = runtimeNode.getSymbol();
1581
1582 switch (runtimeNode.getRequest()) {
1583 case EQ:
1584 case EQ_STRICT:
1585 return enterCmp(lhs, rhs, Condition.EQ, type, symbol);
1586 case NE:
1587 case NE_STRICT:
1588 return enterCmp(lhs, rhs, Condition.NE, type, symbol);
1589 case LE:
1590 return enterCmp(lhs, rhs, Condition.LE, type, symbol);
1591 case LT:
1592 return enterCmp(lhs, rhs, Condition.LT, type, symbol);
1593 case GE:
1594 return enterCmp(lhs, rhs, Condition.GE, type, symbol);
1595 case GT:
1596 return enterCmp(lhs, rhs, Condition.GT, type, symbol);
1597 case ADD:
1598 Type widest = Type.widest(lhs.getType(), rhs.getType());
1599 load(lhs);
1600 method.convert(widest);
1601 load(rhs);
1602 method.convert(widest);
1603 method.add();
1604 method.convert(type);
1605 method.store(symbol);
1606 return false;
1607 default:
1608 // it's ok to send this one on with only primitive arguments, maybe INSTANCEOF(true, true) or similar
1609 // assert false : runtimeNode + " has all primitive arguments. This is an inconsistent state";
1610 break;
1611 }
1612 }
1613
1614 // Get the request arguments.
1615 final List<Node> args = runtimeNode.getArgs();
1616
1617 if (nullCheck(runtimeNode, args, new FunctionSignature(false, false, runtimeNode.getType(), args).toString())) {
1618 return false;
1619 }
1620
1621 if (!runtimeNode.isFinal() && specializationCheck(runtimeNode.getRequest(), runtimeNode, args)) {
1622 return false;
1623 }
1624
1625 for (final Node arg : runtimeNode.getArgs()) {
1626 load(arg).convert(Type.OBJECT); //TODO this should not be necessary below Lower
1627 }
1628
1629 method.invokestatic(
1630 CompilerConstants.className(ScriptRuntime.class),
1631 runtimeNode.getRequest().toString(),
1632 new FunctionSignature(
1633 false,
1634 false,
1635 runtimeNode.getType(),
1636 runtimeNode.getArgs().size()).toString());
1637 method.convert(runtimeNode.getType());
1638 method.store(runtimeNode.getSymbol());
1639
1640 return false;
1641 }
1642
1643 @Override
1644 public boolean enterSplitNode(final SplitNode splitNode) {
1645 lineNumber(splitNode);
1646
1647 final CompileUnit splitCompileUnit = splitNode.getCompileUnit();
1648
1649 final FunctionNode fn = lc.getCurrentFunction();
1650 final String className = splitCompileUnit.getUnitClassName();
1651 final String name = splitNode.getName();
1652
1653 final Class<?> rtype = fn.getReturnType().getTypeClass();
1654 final boolean needsArguments = fn.needsArguments();
1655 final Class<?>[] ptypes = needsArguments ?
1656 new Class<?>[] {ScriptFunction.class, Object.class, ScriptObject.class, Object.class} :
1657 new Class<?>[] {ScriptFunction.class, Object.class, ScriptObject.class};
1658
1659 final MethodEmitter caller = method;
1660 unit = lc.pushCompileUnit(splitCompileUnit);
1661
1662 final Call splitCall = staticCallNoLookup(
1663 className,
1664 name,
1665 methodDescriptor(rtype, ptypes));
1666
1667 final MethodEmitter splitEmitter =
1668 splitCompileUnit.getClassEmitter().method(
1669 splitNode,
1670 name,
1671 rtype,
1672 ptypes);
1673
1674 method = lc.pushMethodEmitter(splitEmitter);
1675 method.setFunctionNode(fn);
1676
1677 if (fn.needsCallee()) {
1678 caller.loadCompilerConstant(CALLEE);
1679 } else {
1680 caller.loadNull();
1681 }
1682 caller.loadCompilerConstant(THIS);
1683 caller.loadCompilerConstant(SCOPE);
1684 if (needsArguments) {
1685 caller.loadCompilerConstant(ARGUMENTS);
1686 }
1687 caller.invoke(splitCall);
1688 caller.storeCompilerConstant(RETURN);
1689
1690 method.begin();
1691
1692 method.loadUndefined(fn.getReturnType());
1693 method.storeCompilerConstant(RETURN);
1694
1695 fixScopeSlot();
1696
1697 return true;
1698 }
1699
1700 private void fixScopeSlot() {
1701 if (lc.getCurrentFunction().compilerConstant(SCOPE).getSlot() != SCOPE.slot()) {
1702 // TODO hack to move the scope to the expected slot (that's needed because split methods reuse the same slots as the root method)
1703 method.load(Type.typeFor(ScriptObject.class), SCOPE.slot());
1704 method.storeCompilerConstant(SCOPE);
1705 }
1706 }
1707
1708 @Override
1709 public Node leaveSplitNode(final SplitNode splitNode) {
1710 assert method instanceof SplitMethodEmitter;
1711 final boolean hasReturn = method.hasReturn();
1712 final List<Label> targets = method.getExternalTargets();
1713
1714 try {
1715 // Wrap up this method.
1716
1717 method.loadCompilerConstant(RETURN);
1718 method._return(lc.getCurrentFunction().getReturnType());
1719 method.end();
1720
1721 unit = lc.popCompileUnit(splitNode.getCompileUnit());
1722 method = lc.popMethodEmitter(method);
1723
1724 } catch (final Throwable t) {
1725 Context.printStackTrace(t);
1726 final VerifyError e = new VerifyError("Code generation bug in \"" + splitNode.getName() + "\": likely stack misaligned: " + t + " " + lc.getCurrentFunction().getSource().getName());
1727 e.initCause(t);
1728 throw e;
1729 }
1730
1731 // Handle return from split method if there was one.
1732 final MethodEmitter caller = method;
1733 final int targetCount = targets.size();
1734
1735 //no external jump targets or return in switch node
1736 if (!hasReturn && targets.isEmpty()) {
1737 return splitNode;
1738 }
1739
1740 caller.loadCompilerConstant(SCOPE);
1741 caller.checkcast(Scope.class);
1742 caller.invoke(Scope.GET_SPLIT_STATE);
1743
1744 final Label breakLabel = new Label("no_split_state");
1745 // Split state is -1 for no split state, 0 for return, 1..n+1 for break/continue
1746
1747 //the common case is that we don't need a switch
1748 if (targetCount == 0) {
1749 assert hasReturn;
1750 caller.ifne(breakLabel);
1751 //has to be zero
1752 caller.label(new Label("split_return"));
1753 method.loadCompilerConstant(RETURN);
1754 caller._return(lc.getCurrentFunction().getReturnType());
1755 caller.label(breakLabel);
1756 } else {
1757 assert !targets.isEmpty();
1758
1759 final int low = hasReturn ? 0 : 1;
1760 final int labelCount = targetCount + 1 - low;
1761 final Label[] labels = new Label[labelCount];
1762
1763 for (int i = 0; i < labelCount; i++) {
1764 labels[i] = new Label(i == 0 ? "split_return" : "split_" + targets.get(i - 1));
1765 }
1766 caller.tableswitch(low, targetCount, breakLabel, labels);
1767 for (int i = low; i <= targetCount; i++) {
1768 caller.label(labels[i - low]);
1769 if (i == 0) {
1770 caller.loadCompilerConstant(RETURN);
1771 caller._return(lc.getCurrentFunction().getReturnType());
1772 } else {
1773 // Clear split state.
1774 caller.loadCompilerConstant(SCOPE);
1775 caller.checkcast(Scope.class);
1776 caller.load(-1);
1777 caller.invoke(Scope.SET_SPLIT_STATE);
1778 caller.splitAwareGoto(lc, targets.get(i - 1));
1779 }
1780 }
1781 caller.label(breakLabel);
1782 }
1783
1784 return splitNode;
1785 }
1786
1787 @Override
1788 public boolean enterSwitchNode(final SwitchNode switchNode) {
1789 lineNumber(switchNode);
1790
1791 final Node expression = switchNode.getExpression();
1792 final Symbol tag = switchNode.getTag();
1793 final boolean allInteger = tag.getSymbolType().isInteger();
1794 final List<CaseNode> cases = switchNode.getCases();
1795 final CaseNode defaultCase = switchNode.getDefaultCase();
1796 final Label breakLabel = switchNode.getBreakLabel();
1797
1798 Label defaultLabel = breakLabel;
1799 boolean hasDefault = false;
1800
1801 if (defaultCase != null) {
1802 defaultLabel = defaultCase.getEntry();
1803 hasDefault = true;
1804 }
1805
1806 if (cases.isEmpty()) {
1807 method.label(breakLabel);
1808 return false;
1809 }
1810
1811 if (allInteger) {
1812 // Tree for sorting values.
1813 final TreeMap<Integer, Label> tree = new TreeMap<>();
1814
1815 // Build up sorted tree.
1816 for (final CaseNode caseNode : cases) {
1817 final Node test = caseNode.getTest();
1818
1819 if (test != null) {
1820 final Integer value = (Integer)((LiteralNode<?>)test).getValue();
1821 final Label entry = caseNode.getEntry();
1822
1823 // Take first duplicate.
1824 if (!(tree.containsKey(value))) {
1825 tree.put(value, entry);
1826 }
1827 }
1828 }
1829
1830 // Copy values and labels to arrays.
1831 final int size = tree.size();
1832 final Integer[] values = tree.keySet().toArray(new Integer[size]);
1833 final Label[] labels = tree.values().toArray(new Label[size]);
1834
1835 // Discern low, high and range.
1836 final int lo = values[0];
1837 final int hi = values[size - 1];
1838 final int range = hi - lo + 1;
1839
1840 // Find an unused value for default.
1841 int deflt = Integer.MIN_VALUE;
1842 for (final int value : values) {
1843 if (deflt == value) {
1844 deflt++;
1845 } else if (deflt < value) {
1846 break;
1847 }
1848 }
1849
1850 // Load switch expression.
1851 load(expression);
1852 final Type type = expression.getType();
1853
1854 // If expression not int see if we can convert, if not use deflt to trigger default.
1855 if (!type.isInteger()) {
1856 method.load(deflt);
1857 method.invoke(staticCallNoLookup(ScriptRuntime.class, "switchTagAsInt", int.class, type.getTypeClass(), int.class));
1858 }
1859
1860 // If reasonable size and not too sparse (80%), use table otherwise use lookup.
1861 if (range > 0 && range < 4096 && range < (size * 5 / 4)) {
1862 final Label[] table = new Label[range];
1863 Arrays.fill(table, defaultLabel);
1864
1865 for (int i = 0; i < size; i++) {
1866 final int value = values[i];
1867 table[value - lo] = labels[i];
1868 }
1869
1870 method.tableswitch(lo, hi, defaultLabel, table);
1871 } else {
1872 final int[] ints = new int[size];
1873 for (int i = 0; i < size; i++) {
1874 ints[i] = values[i];
1875 }
1876
1877 method.lookupswitch(defaultLabel, ints, labels);
1878 }
1879 } else {
1880 load(expression);
1881
1882 if (expression.getType().isInteger()) {
1883 method.convert(Type.NUMBER).dup();
1884 method.store(tag);
1885 method.conditionalJump(Condition.NE, true, defaultLabel);
1886 } else {
1887 method.store(tag);
1888 }
1889
1890 for (final CaseNode caseNode : cases) {
1891 final Node test = caseNode.getTest();
1892
1893 if (test != null) {
1894 method.load(tag);
1895 load(test);
1896 method.invoke(ScriptRuntime.EQ_STRICT);
1897 method.ifne(caseNode.getEntry());
1898 }
1899 }
1900
1901 method._goto(hasDefault ? defaultLabel : breakLabel);
1902 }
1903
1904 for (final CaseNode caseNode : cases) {
1905 method.label(caseNode.getEntry());
1906 caseNode.getBody().accept(this);
1907 }
1908
1909 if (!switchNode.isTerminal()) {
1910 method.label(breakLabel);
1911 }
1912
1913 return false;
1914 }
1915
1916 @Override
1917 public boolean enterThrowNode(final ThrowNode throwNode) {
1918 lineNumber(throwNode);
1919
1920 if (throwNode.isSyntheticRethrow()) {
1921 //do not wrap whatever this is in an ecma exception, just rethrow it
1922 load(throwNode.getExpression());
1923 method.athrow();
1924 return false;
1925 }
1926
1927 method._new(ECMAException.class).dup();
1928
1929 final Source source = lc.getCurrentFunction().getSource();
1930
1931 final Node expression = throwNode.getExpression();
1932 final int position = throwNode.position();
1933 final int line = source.getLine(position);
1934 final int column = source.getColumn(position);
1935
1936 load(expression);
1937 assert expression.getType().isObject();
1938
1939 method.load(source.getName());
1940 method.load(line);
1941 method.load(column);
1942 method.invoke(ECMAException.THROW_INIT);
1943
1944 method.athrow();
1945
1946 return false;
1947 }
1948
1949 @Override
1950 public boolean enterTryNode(final TryNode tryNode) {
1951 lineNumber(tryNode);
1952
1953 final Block body = tryNode.getBody();
1954 final List<Block> catchBlocks = tryNode.getCatchBlocks();
1955 final Symbol symbol = tryNode.getException();
1956 final Label entry = new Label("try");
1957 final Label recovery = new Label("catch");
1958 final Label exit = tryNode.getExit();
1959 final Label skip = new Label("skip");
1960
1961 method.label(entry);
1962
1963 body.accept(this);
1964
1965 if (!body.hasTerminalFlags()) {
1966 method._goto(skip);
1967 }
1968
1969 method.label(exit);
1970
1971 method._catch(recovery);
1972 method.store(symbol);
1973
1974 for (int i = 0; i < catchBlocks.size(); i++) {
1975 final Block catchBlock = catchBlocks.get(i);
1976
1977 //TODO this is very ugly - try not to call enter/leave methods directly
1978 //better to use the implicit lexical context scoping given by the visitor's
1979 //accept method.
1980 lc.push(catchBlock);
1981 enterBlock(catchBlock);
1982
1983 final CatchNode catchNode = (CatchNode)catchBlocks.get(i).getStatements().get(0);
1984 final IdentNode exception = catchNode.getException();
1985 final Node exceptionCondition = catchNode.getExceptionCondition();
1986 final Block catchBody = catchNode.getBody();
1987
1988 new Store<IdentNode>(exception) {
1989 @Override
1990 protected void storeNonDiscard() {
1991 return;
1992 }
1993
1994 @Override
1995 protected void evaluate() {
1996 if (catchNode.isSyntheticRethrow()) {
1997 method.load(symbol);
1998 return;
1999 }
2000 /*
2001 * If caught object is an instance of ECMAException, then
2002 * bind obj.thrown to the script catch var. Or else bind the
2003 * caught object itself to the script catch var.
2004 */
2005 final Label notEcmaException = new Label("no_ecma_exception");
2006 method.load(symbol).dup()._instanceof(ECMAException.class).ifeq(notEcmaException);
2007 method.checkcast(ECMAException.class); //TODO is this necessary?
2008 method.getField(ECMAException.THROWN);
2009 method.label(notEcmaException);
2010 }
2011 }.store();
2012
2013 final Label next;
2014
2015 if (exceptionCondition != null) {
2016 next = new Label("next");
2017 load(exceptionCondition).convert(Type.BOOLEAN).ifeq(next);
2018 } else {
2019 next = null;
2020 }
2021
2022 catchBody.accept(this);
2023
2024 if (i + 1 != catchBlocks.size() && !catchBody.hasTerminalFlags()) {
2025 method._goto(skip);
2026 }
2027
2028 if (next != null) {
2029 if (i + 1 == catchBlocks.size()) {
2030 // no next catch block - rethrow if condition failed
2031 method._goto(skip);
2032 method.label(next);
2033 method.load(symbol).athrow();
2034 } else {
2035 method.label(next);
2036 }
2037 }
2038
2039 leaveBlock(catchBlock);
2040 lc.pop(catchBlock);
2041 }
2042
2043 method.label(skip);
2044 method._try(entry, exit, recovery, Throwable.class);
2045
2046 // Finally body is always inlined elsewhere so it doesn't need to be emitted
2047
2048 return false;
2049 }
2050
2051 @Override
2052 public boolean enterVarNode(final VarNode varNode) {
2053
2054 final Node init = varNode.getInit();
2055
2056 if (init == null) {
2057 return false;
2058 }
2059
2060 lineNumber(varNode);
2061
2062 final Symbol varSymbol = varNode.getSymbol();
2063 assert varSymbol != null : "variable node " + varNode + " requires a symbol";
2064
2065 assert method != null;
2066
2067 final boolean needsScope = varSymbol.isScope();
2068 if (needsScope) {
2069 method.loadCompilerConstant(SCOPE);
2070 }
2071 load(init);
2072
2073 if (needsScope) {
2074 int flags = CALLSITE_SCOPE | getCallSiteFlags();
2075 final IdentNode identNode = varNode.getName();
2076 final Type type = identNode.getType();
2077 if (isFastScope(varSymbol)) {
2078 storeFastScopeVar(type, varSymbol, flags);
2079 } else {
2080 method.dynamicSet(type, identNode.getName(), flags);
2081 }
2082 } else {
2083 assert varNode.getType() == varNode.getName().getType() : "varNode type=" + varNode.getType() + " nametype=" + varNode.getName().getType() + " inittype=" + init.getType();
2084
2085 method.convert(varNode.getType()); // aw: convert moved here
2086 method.store(varSymbol);
2087 }
2088
2089 return false;
2090 }
2091
2092 @Override
2093 public boolean enterWhileNode(final WhileNode whileNode) {
2094 lineNumber(whileNode);
2095
2096 final Node test = whileNode.getTest();
2097 final Block body = whileNode.getBody();
2098 final Label breakLabel = whileNode.getBreakLabel();
2099 final Label continueLabel = whileNode.getContinueLabel();
2100 final Label loopLabel = new Label("loop");
2101
2102 if (!whileNode.isDoWhile()) {
2103 method._goto(continueLabel);
2104 }
2105
2106 method.label(loopLabel);
2107 body.accept(this);
2108 if (!whileNode.isTerminal()) {
2109 method.label(continueLabel);
2110 new BranchOptimizer(this, method).execute(test, loopLabel, true);
2111 method.label(breakLabel);
2112 }
2113
2114 return false;
2115 }
2116
2117 private void closeWith() {
2118 if (method.hasScope()) {
2119 method.loadCompilerConstant(SCOPE);
2120 method.invoke(ScriptRuntime.CLOSE_WITH);
2121 method.storeCompilerConstant(SCOPE);
2122 }
2123 }
2124
2125 @Override
2126 public boolean enterWithNode(final WithNode withNode) {
2127 final Node expression = withNode.getExpression();
2128 final Node body = withNode.getBody();
2129
2130 // It is possible to have a "pathological" case where the with block does not reference *any* identifiers. It's
2131 // pointless, but legal. In that case, if nothing else in the method forced the assignment of a slot to the
2132 // scope object, its' possible that it won't have a slot assigned. In this case we'll only evaluate expression
2133 // for its side effect and visit the body, and not bother opening and closing a WithObject.
2134 final boolean hasScope = method.hasScope();
2135
2136 final Label tryLabel;
2137 if (hasScope) {
2138 tryLabel = new Label("with_try");
2139 method.label(tryLabel);
2140 method.loadCompilerConstant(SCOPE);
2141 } else {
2142 tryLabel = null;
2143 }
2144
2145 load(expression);
2146 assert expression.getType().isObject() : "with expression needs to be object: " + expression;
2147
2148 if (hasScope) {
2149 // Construct a WithObject if we have a scope
2150 method.invoke(ScriptRuntime.OPEN_WITH);
2151 method.storeCompilerConstant(SCOPE);
2152 } else {
2153 // We just loaded the expression for its side effect; discard it
2154 method.pop();
2155 }
2156
2157
2158 // Always process body
2159 body.accept(this);
2160
2161 if (hasScope) {
2162 // Ensure we always close the WithObject
2163 final Label endLabel = new Label("with_end");
2164 final Label catchLabel = new Label("with_catch");
2165 final Label exitLabel = new Label("with_exit");
2166
2167 if (!body.isTerminal()) {
2168 closeWith();
2169 method._goto(exitLabel);
2170 }
2171
2172 method.label(endLabel);
2173
2174 method._catch(catchLabel);
2175 closeWith();
2176 method.athrow();
2177
2178 method.label(exitLabel);
2179
2180 method._try(tryLabel, endLabel, catchLabel);
2181 }
2182 return false;
2183 }
2184
2185 @Override
2186 public boolean enterADD(final UnaryNode unaryNode) {
2187 load(unaryNode.rhs());
2188 assert unaryNode.rhs().getType().isNumber() : unaryNode.rhs().getType() + " "+ unaryNode.getSymbol();
2189 method.store(unaryNode.getSymbol());
2190
2191 return false;
2192 }
2193
2194 @Override
2195 public boolean enterBIT_NOT(final UnaryNode unaryNode) {
2196 load(unaryNode.rhs()).convert(Type.INT).load(-1).xor().store(unaryNode.getSymbol());
2197 return false;
2198 }
2199
2200 // do this better with convert calls to method. TODO
2201 @Override
2202 public boolean enterCONVERT(final UnaryNode unaryNode) {
2203 final Node rhs = unaryNode.rhs();
2204 final Type to = unaryNode.getType();
2205
2206 if (to.isObject() && rhs instanceof LiteralNode) {
2207 final LiteralNode<?> literalNode = (LiteralNode<?>)rhs;
2208 final Object value = literalNode.getValue();
2209
2210 if (value instanceof Number) {
2211 assert !to.isArray() : "type hygiene - cannot convert number to array: (" + to.getTypeClass().getSimpleName() + ')' + value;
2212 if (value instanceof Integer) {
2213 method.load((Integer)value);
2214 } else if (value instanceof Long) {
2215 method.load((Long)value);
2216 } else if (value instanceof Double) {
2217 method.load((Double)value);
2218 } else {
2219 assert false;
2220 }
2221 method.convert(Type.OBJECT);
2222 } else if (value instanceof Boolean) {
2223 method.getField(staticField(Boolean.class, value.toString().toUpperCase(), Boolean.class));
2224 } else {
2225 load(rhs);
2226 method.convert(unaryNode.getType());
2227 }
2228 } else {
2229 load(rhs);
2230 method.convert(unaryNode.getType());
2231 }
2232
2233 method.store(unaryNode.getSymbol());
2234
2235 return false;
2236 }
2237
2238 @Override
2239 public boolean enterDECINC(final UnaryNode unaryNode) {
2240 final Node rhs = unaryNode.rhs();
2241 final Type type = unaryNode.getType();
2242 final TokenType tokenType = unaryNode.tokenType();
2243 final boolean isPostfix = tokenType == TokenType.DECPOSTFIX || tokenType == TokenType.INCPOSTFIX;
2244 final boolean isIncrement = tokenType == TokenType.INCPREFIX || tokenType == TokenType.INCPOSTFIX;
2245
2246 assert !type.isObject();
2247
2248 new SelfModifyingStore<UnaryNode>(unaryNode, rhs) {
2249
2250 @Override
2251 protected void evaluate() {
2252 load(rhs, true);
2253
2254 method.convert(type);
2255 if (!isPostfix) {
2256 if (type.isInteger()) {
2257 method.load(isIncrement ? 1 : -1);
2258 } else if (type.isLong()) {
2259 method.load(isIncrement ? 1L : -1L);
2260 } else {
2261 method.load(isIncrement ? 1.0 : -1.0);
2262 }
2263 method.add();
2264 }
2265 }
2266
2267 @Override
2268 protected void storeNonDiscard() {
2269 super.storeNonDiscard();
2270 if (isPostfix) {
2271 if (type.isInteger()) {
2272 method.load(isIncrement ? 1 : -1);
2273 } else if (type.isLong()) {
2274 method.load(isIncrement ? 1L : 1L);
2275 } else {
2276 method.load(isIncrement ? 1.0 : -1.0);
2277 }
2278 method.add();
2279 }
2280 }
2281 }.store();
2282
2283 return false;
2284 }
2285
2286 @Override
2287 public boolean enterDISCARD(final UnaryNode unaryNode) {
2288 final Node rhs = unaryNode.rhs();
2289
2290 lc.pushDiscard(rhs);
2291 load(rhs);
2292
2293 if (lc.getCurrentDiscard() == rhs) {
2294 assert !rhs.isAssignment();
2295 method.pop();
2296 lc.popDiscard();
2297 }
2298
2299 return false;
2300 }
2301
2302 @Override
2303 public boolean enterNEW(final UnaryNode unaryNode) {
2304 final CallNode callNode = (CallNode)unaryNode.rhs();
2305 final List<Node> args = callNode.getArgs();
2306
2307 // Load function reference.
2308 load(callNode.getFunction()).convert(Type.OBJECT); // must detect type error
2309
2310 method.dynamicNew(1 + loadArgs(args), getCallSiteFlags());
2311 method.store(unaryNode.getSymbol());
2312
2313 return false;
2314 }
2315
2316 @Override
2317 public boolean enterNOT(final UnaryNode unaryNode) {
2318 final Node rhs = unaryNode.rhs();
2319
2320 load(rhs);
2321
2322 final Label trueLabel = new Label("true");
2323 final Label afterLabel = new Label("after");
2324
2325 method.convert(Type.BOOLEAN);
2326 method.ifne(trueLabel);
2327 method.load(true);
2328 method._goto(afterLabel);
2329 method.label(trueLabel);
2330 method.load(false);
2331 method.label(afterLabel);
2332 method.store(unaryNode.getSymbol());
2333
2334 return false;
2335 }
2336
2337 @Override
2338 public boolean enterSUB(final UnaryNode unaryNode) {
2339 load(unaryNode.rhs()).neg().store(unaryNode.getSymbol());
2340
2341 return false;
2342 }
2343
2344 private Node enterNumericAdd(final Node lhs, final Node rhs, final Type type, final Symbol symbol) {
2345 assert lhs.getType().equals(rhs.getType()) && lhs.getType().equals(type) : lhs.getType() + " != " + rhs.getType() + " != " + type + " " + new ASTWriter(lhs) + " " + new ASTWriter(rhs);
2346 load(lhs);
2347 load(rhs);
2348 method.add(); //if the symbol is optimistic, it always needs to be written, not on the stack?
2349 method.store(symbol);
2350 return null;
2351 }
2352
2353 @Override
2354 public boolean enterADD(final BinaryNode binaryNode) {
2355 final Node lhs = binaryNode.lhs();
2356 final Node rhs = binaryNode.rhs();
2357
2358 final Type type = binaryNode.getType();
2359 if (type.isNumeric()) {
2360 enterNumericAdd(lhs, rhs, type, binaryNode.getSymbol());
2361 } else {
2362 load(lhs).convert(Type.OBJECT);
2363 load(rhs).convert(Type.OBJECT);
2364 method.add();
2365 method.store(binaryNode.getSymbol());
2366 }
2367
2368 return false;
2369 }
2370
2371 private boolean enterAND_OR(final BinaryNode binaryNode) {
2372 final Node lhs = binaryNode.lhs();
2373 final Node rhs = binaryNode.rhs();
2374
2375 final Label skip = new Label("skip");
2376
2377 load(lhs).convert(Type.OBJECT).dup().convert(Type.BOOLEAN);
2378
2379 if (binaryNode.tokenType() == TokenType.AND) {
2380 method.ifeq(skip);
2381 } else {
2382 method.ifne(skip);
2383 }
2384
2385 method.pop();
2386 load(rhs).convert(Type.OBJECT);
2387 method.label(skip);
2388 method.store(binaryNode.getSymbol());
2389
2390 return false;
2391 }
2392
2393 @Override
2394 public boolean enterAND(final BinaryNode binaryNode) {
2395 return enterAND_OR(binaryNode);
2396 }
2397
2398 @Override
2399 public boolean enterASSIGN(final BinaryNode binaryNode) {
2400 final Node lhs = binaryNode.lhs();
2401 final Node rhs = binaryNode.rhs();
2402
2403 final Type lhsType = lhs.getType();
2404 final Type rhsType = rhs.getType();
2405
2406 if (!lhsType.isEquivalentTo(rhsType)) {
2407 //this is OK if scoped, only locals are wrong
2408 assert !(lhs instanceof IdentNode) || lhs.getSymbol().isScope() : new ASTWriter(binaryNode);
2409 }
2410
2411 new Store<BinaryNode>(binaryNode, lhs) {
2412 @Override
2413 protected void evaluate() {
2414 load(rhs);
2415 }
2416 }.store();
2417
2418 return false;
2419 }
2420
2421 /**
2422 * Helper class for assignment ops, e.g. *=, += and so on..
2423 */
2424 private abstract class AssignOp extends SelfModifyingStore<BinaryNode> {
2425
2426 /** The type of the resulting operation */
2427 private final Type opType;
2428
2429 /**
2430 * Constructor
2431 *
2432 * @param node the assign op node
2433 */
2434 AssignOp(final BinaryNode node) {
2435 this(node.getType(), node);
2436 }
2437
2438 /**
2439 * Constructor
2440 *
2441 * @param opType type of the computation - overriding the type of the node
2442 * @param node the assign op node
2443 */
2444 AssignOp(final Type opType, final BinaryNode node) {
2445 super(node, node.lhs());
2446 this.opType = opType;
2447 }
2448
2449 protected abstract void op();
2450
2451 @Override
2452 protected void evaluate() {
2453 load(assignNode.lhs(), true).convert(opType);
2454 load(assignNode.rhs()).convert(opType);
2455 op();
2456 method.convert(assignNode.getType());
2457 }
2458 }
2459
2460 @Override
2461 public boolean enterASSIGN_ADD(final BinaryNode binaryNode) {
2462 assert RuntimeNode.Request.ADD.canSpecialize();
2463 final Type lhsType = binaryNode.lhs().getType();
2464 final Type rhsType = binaryNode.rhs().getType();
2465 final boolean specialize = binaryNode.getType() == Type.OBJECT;
2466
2467 new AssignOp(binaryNode) {
2468
2469 @Override
2470 protected void op() {
2471 if (specialize) {
2472 method.dynamicRuntimeCall(
2473 new SpecializedRuntimeNode(
2474 Request.ADD,
2475 new Type[] {
2476 lhsType,
2477 rhsType,
2478 },
2479 Type.OBJECT).getInitialName(),
2480 Type.OBJECT,
2481 Request.ADD);
2482 } else {
2483 method.add();
2484 }
2485 }
2486
2487 @Override
2488 protected void evaluate() {
2489 super.evaluate();
2490 }
2491 }.store();
2492
2493 return false;
2494 }
2495
2496 @Override
2497 public boolean enterASSIGN_BIT_AND(final BinaryNode binaryNode) {
2498 new AssignOp(Type.INT, binaryNode) {
2499 @Override
2500 protected void op() {
2501 method.and();
2502 }
2503 }.store();
2504
2505 return false;
2506 }
2507
2508 @Override
2509 public boolean enterASSIGN_BIT_OR(final BinaryNode binaryNode) {
2510 new AssignOp(Type.INT, binaryNode) {
2511 @Override
2512 protected void op() {
2513 method.or();
2514 }
2515 }.store();
2516
2517 return false;
2518 }
2519
2520 @Override
2521 public boolean enterASSIGN_BIT_XOR(final BinaryNode binaryNode) {
2522 new AssignOp(Type.INT, binaryNode) {
2523 @Override
2524 protected void op() {
2525 method.xor();
2526 }
2527 }.store();
2528
2529 return false;
2530 }
2531
2532 @Override
2533 public boolean enterASSIGN_DIV(final BinaryNode binaryNode) {
2534 new AssignOp(binaryNode) {
2535 @Override
2536 protected void op() {
2537 method.div();
2538 }
2539 }.store();
2540
2541 return false;
2542 }
2543
2544 @Override
2545 public boolean enterASSIGN_MOD(final BinaryNode binaryNode) {
2546 new AssignOp(binaryNode) {
2547 @Override
2548 protected void op() {
2549 method.rem();
2550 }
2551 }.store();
2552
2553 return false;
2554 }
2555
2556 @Override
2557 public boolean enterASSIGN_MUL(final BinaryNode binaryNode) {
2558 new AssignOp(binaryNode) {
2559 @Override
2560 protected void op() {
2561 method.mul();
2562 }
2563 }.store();
2564
2565 return false;
2566 }
2567
2568 @Override
2569 public boolean enterASSIGN_SAR(final BinaryNode binaryNode) {
2570 new AssignOp(Type.INT, binaryNode) {
2571 @Override
2572 protected void op() {
2573 method.sar();
2574 }
2575 }.store();
2576
2577 return false;
2578 }
2579
2580 @Override
2581 public boolean enterASSIGN_SHL(final BinaryNode binaryNode) {
2582 new AssignOp(Type.INT, binaryNode) {
2583 @Override
2584 protected void op() {
2585 method.shl();
2586 }
2587 }.store();
2588
2589 return false;
2590 }
2591
2592 @Override
2593 public boolean enterASSIGN_SHR(final BinaryNode binaryNode) {
2594 new AssignOp(Type.INT, binaryNode) {
2595 @Override
2596 protected void op() {
2597 method.shr();
2598 method.convert(Type.LONG).load(JSType.MAX_UINT).and();
2599 }
2600 }.store();
2601
2602 return false;
2603 }
2604
2605 @Override
2606 public boolean enterASSIGN_SUB(final BinaryNode binaryNode) {
2607 new AssignOp(binaryNode) {
2608 @Override
2609 protected void op() {
2610 method.sub();
2611 }
2612 }.store();
2613
2614 return false;
2615 }
2616
2617 /**
2618 * Helper class for binary arithmetic ops
2619 */
2620 private abstract class BinaryArith {
2621
2622 protected abstract void op();
2623
2624 protected void evaluate(final BinaryNode node) {
2625 load(node.lhs());
2626 load(node.rhs());
2627 op();
2628 method.store(node.getSymbol());
2629 }
2630 }
2631
2632 @Override
2633 public boolean enterBIT_AND(final BinaryNode binaryNode) {
2634 new BinaryArith() {
2635 @Override
2636 protected void op() {
2637 method.and();
2638 }
2639 }.evaluate(binaryNode);
2640
2641 return false;
2642 }
2643
2644 @Override
2645 public boolean enterBIT_OR(final BinaryNode binaryNode) {
2646 new BinaryArith() {
2647 @Override
2648 protected void op() {
2649 method.or();
2650 }
2651 }.evaluate(binaryNode);
2652
2653 return false;
2654 }
2655
2656 @Override
2657 public boolean enterBIT_XOR(final BinaryNode binaryNode) {
2658 new BinaryArith() {
2659 @Override
2660 protected void op() {
2661 method.xor();
2662 }
2663 }.evaluate(binaryNode);
2664
2665 return false;
2666 }
2667
2668 private boolean enterComma(final BinaryNode binaryNode) {
2669 final Node lhs = binaryNode.lhs();
2670 final Node rhs = binaryNode.rhs();
2671
2672 load(lhs);
2673 load(rhs);
2674 method.store(binaryNode.getSymbol());
2675
2676 return false;
2677 }
2678
2679 @Override
2680 public boolean enterCOMMARIGHT(final BinaryNode binaryNode) {
2681 return enterComma(binaryNode);
2682 }
2683
2684 @Override
2685 public boolean enterCOMMALEFT(final BinaryNode binaryNode) {
2686 return enterComma(binaryNode);
2687 }
2688
2689 @Override
2690 public boolean enterDIV(final BinaryNode binaryNode) {
2691 new BinaryArith() {
2692 @Override
2693 protected void op() {
2694 method.div();
2695 }
2696 }.evaluate(binaryNode);
2697
2698 return false;
2699 }
2700
2701 private boolean enterCmp(final Node lhs, final Node rhs, final Condition cond, final Type type, final Symbol symbol) {
2702 final Type lhsType = lhs.getType();
2703 final Type rhsType = rhs.getType();
2704
2705 final Type widest = Type.widest(lhsType, rhsType);
2706 assert widest.isNumeric() || widest.isBoolean() : widest;
2707
2708 load(lhs);
2709 method.convert(widest);
2710 load(rhs);
2711 method.convert(widest);
2712
2713 final Label trueLabel = new Label("trueLabel");
2714 final Label afterLabel = new Label("skip");
2715
2716 method.conditionalJump(cond, trueLabel);
2717
2718 method.load(Boolean.FALSE);
2719 method._goto(afterLabel);
2720 method.label(trueLabel);
2721 method.load(Boolean.TRUE);
2722 method.label(afterLabel);
2723
2724 method.convert(type);
2725 method.store(symbol);
2726
2727 return false;
2728 }
2729
2730 private boolean enterCmp(final BinaryNode binaryNode, final Condition cond) {
2731 return enterCmp(binaryNode.lhs(), binaryNode.rhs(), cond, binaryNode.getType(), binaryNode.getSymbol());
2732 }
2733
2734 @Override
2735 public boolean enterEQ(final BinaryNode binaryNode) {
2736 return enterCmp(binaryNode, Condition.EQ);
2737 }
2738
2739 @Override
2740 public boolean enterEQ_STRICT(final BinaryNode binaryNode) {
2741 return enterCmp(binaryNode, Condition.EQ);
2742 }
2743
2744 @Override
2745 public boolean enterGE(final BinaryNode binaryNode) {
2746 return enterCmp(binaryNode, Condition.GE);
2747 }
2748
2749 @Override
2750 public boolean enterGT(final BinaryNode binaryNode) {
2751 return enterCmp(binaryNode, Condition.GT);
2752 }
2753
2754 @Override
2755 public boolean enterLE(final BinaryNode binaryNode) {
2756 return enterCmp(binaryNode, Condition.LE);
2757 }
2758
2759 @Override
2760 public boolean enterLT(final BinaryNode binaryNode) {
2761 return enterCmp(binaryNode, Condition.LT);
2762 }
2763
2764 @Override
2765 public boolean enterMOD(final BinaryNode binaryNode) {
2766 new BinaryArith() {
2767 @Override
2768 protected void op() {
2769 method.rem();
2770 }
2771 }.evaluate(binaryNode);
2772
2773 return false;
2774 }
2775
2776 @Override
2777 public boolean enterMUL(final BinaryNode binaryNode) {
2778 new BinaryArith() {
2779 @Override
2780 protected void op() {
2781 method.mul();
2782 }
2783 }.evaluate(binaryNode);
2784
2785 return false;
2786 }
2787
2788 @Override
2789 public boolean enterNE(final BinaryNode binaryNode) {
2790 return enterCmp(binaryNode, Condition.NE);
2791 }
2792
2793 @Override
2794 public boolean enterNE_STRICT(final BinaryNode binaryNode) {
2795 return enterCmp(binaryNode, Condition.NE);
2796 }
2797
2798 @Override
2799 public boolean enterOR(final BinaryNode binaryNode) {
2800 return enterAND_OR(binaryNode);
2801 }
2802
2803 @Override
2804 public boolean enterSAR(final BinaryNode binaryNode) {
2805 new BinaryArith() {
2806 @Override
2807 protected void op() {
2808 method.sar();
2809 }
2810 }.evaluate(binaryNode);
2811
2812 return false;
2813 }
2814
2815 @Override
2816 public boolean enterSHL(final BinaryNode binaryNode) {
2817 new BinaryArith() {
2818 @Override
2819 protected void op() {
2820 method.shl();
2821 }
2822 }.evaluate(binaryNode);
2823
2824 return false;
2825 }
2826
2827 @Override
2828 public boolean enterSHR(final BinaryNode binaryNode) {
2829 new BinaryArith() {
2830 @Override
2831 protected void op() {
2832 method.shr();
2833 method.convert(Type.LONG).load(JSType.MAX_UINT).and();
2834 }
2835 }.evaluate(binaryNode);
2836
2837 return false;
2838 }
2839
2840 @Override
2841 public boolean enterSUB(final BinaryNode binaryNode) {
2842 new BinaryArith() {
2843 @Override
2844 protected void op() {
2845 method.sub();
2846 }
2847 }.evaluate(binaryNode);
2848
2849 return false;
2850 }
2851
2852 @Override
2853 public boolean enterTernaryNode(final TernaryNode ternaryNode) {
2854 final Node lhs = ternaryNode.lhs();
2855 final Node rhs = ternaryNode.rhs();
2856 final Node third = ternaryNode.third();
2857
2858 final Symbol symbol = ternaryNode.getSymbol();
2859 final Label falseLabel = new Label("ternary_false");
2860 final Label exitLabel = new Label("ternary_exit");
2861
2862 Type widest = Type.widest(rhs.getType(), third.getType());
2863 if (rhs.getType().isArray() || third.getType().isArray()) { //loadArray creates a Java array type on the stack, calls global allocate, which creates a native array type
2864 widest = Type.OBJECT;
2865 }
2866
2867 load(lhs);
2868 assert lhs.getType().isBoolean() : "lhs in ternary must be boolean";
2869
2870 // we still keep the conversion here as the AccessSpecializer can have separated the types, e.g. var y = x ? x=55 : 17
2871 // will left as (Object)x=55 : (Object)17 by Lower. Then the first term can be {I}x=55 of type int, which breaks the
2872 // symmetry for the temporary slot for this TernaryNode. This is evidence that we assign types and explicit conversions
2873 // to early, or Apply the AccessSpecializer too late. We are mostly probably looking for a separate type pass to
2874 // do this property. Then we never need any conversions in CodeGenerator
2875 method.ifeq(falseLabel);
2876 load(rhs);
2877 method.convert(widest);
2878 method._goto(exitLabel);
2879 method.label(falseLabel);
2880 load(third);
2881 method.convert(widest);
2882 method.label(exitLabel);
2883 method.store(symbol);
2884
2885 return false;
2886 }
2887
2888 /**
2889 * Generate all shared scope calls generated during codegen.
2890 */
2891 protected void generateScopeCalls() {
2892 for (final SharedScopeCall scopeAccess : lc.getScopeCalls()) {
2893 scopeAccess.generateScopeCall();
2894 }
2895 }
2896
2897 /**
2898 * Debug code used to print symbols
2899 *
2900 * @param block the block we are in
2901 * @param ident identifier for block or function where applicable
2902 */
2903 @SuppressWarnings("resource")
2904 private void printSymbols(final Block block, final String ident) {
2905 if (!compiler.getEnv()._print_symbols) {
2906 return;
2907 }
2908
2909 final PrintWriter out = compiler.getEnv().getErr();
2910 out.println("[BLOCK in '" + ident + "']");
2911 if (!block.printSymbols(out)) {
2912 out.println("<no symbols>");
2913 }
2914 out.println();
2915 }
2916
2917
2918 /**
2919 * The difference between a store and a self modifying store is that
2920 * the latter may load part of the target on the stack, e.g. the base
2921 * of an AccessNode or the base and index of an IndexNode. These are used
2922 * both as target and as an extra source. Previously it was problematic
2923 * for self modifying stores if the target/lhs didn't belong to one
2924 * of three trivial categories: IdentNode, AcessNodes, IndexNodes. In that
2925 * case it was evaluated and tagged as "resolved", which meant at the second
2926 * time the lhs of this store was read (e.g. in a = a (second) + b for a += b,
2927 * it would be evaluated to a nop in the scope and cause stack underflow
2928 *
2929 * see NASHORN-703
2930 *
2931 * @param <T>
2932 */
2933 private abstract class SelfModifyingStore<T extends Node> extends Store<T> {
2934 protected SelfModifyingStore(final T assignNode, final Node target) {
2935 super(assignNode, target);
2936 }
2937
2938 @Override
2939 protected boolean isSelfModifying() {
2940 return true;
2941 }
2942 }
2943
2944 /**
2945 * Helper class to generate stores
2946 */
2947 private abstract class Store<T extends Node> {
2948
2949 /** An assignment node, e.g. x += y */
2950 protected final T assignNode;
2951
2952 /** The target node to store to, e.g. x */
2953 private final Node target;
2954
2955 /** How deep on the stack do the arguments go if this generates an indy call */
2956 private int depth;
2957
2958 /** If we have too many arguments, we need temporary storage, this is stored in 'quick' */
2959 private Symbol quick;
2960
2961 /**
2962 * Constructor
2963 *
2964 * @param assignNode the node representing the whole assignment
2965 * @param target the target node of the assignment (destination)
2966 */
2967 protected Store(final T assignNode, final Node target) {
2968 this.assignNode = assignNode;
2969 this.target = target;
2970 }
2971
2972 /**
2973 * Constructor
2974 *
2975 * @param assignNode the node representing the whole assignment
2976 */
2977 protected Store(final T assignNode) {
2978 this(assignNode, assignNode);
2979 }
2980
2981 /**
2982 * Is this a self modifying store operation, e.g. *= or ++
2983 * @return true if self modifying store
2984 */
2985 protected boolean isSelfModifying() {
2986 return false;
2987 }
2988
2989 private void prologue() {
2990 final Symbol targetSymbol = target.getSymbol();
2991 final Symbol scopeSymbol = lc.getCurrentFunction().compilerConstant(SCOPE);
2992
2993 /**
2994 * This loads the parts of the target, e.g base and index. they are kept
2995 * on the stack throughout the store and used at the end to execute it
2996 */
2997
2998 target.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
2999 @Override
3000 public boolean enterIdentNode(final IdentNode node) {
3001 if (targetSymbol.isScope()) {
3002 method.load(scopeSymbol);
3003 depth++;
3004 }
3005 return false;
3006 }
3007
3008 private void enterBaseNode() {
3009 assert target instanceof BaseNode : "error - base node " + target + " must be instanceof BaseNode";
3010 final BaseNode baseNode = (BaseNode)target;
3011 final Node base = baseNode.getBase();
3012
3013 load(base);
3014 method.convert(Type.OBJECT);
3015 depth += Type.OBJECT.getSlots();
3016
3017 if (isSelfModifying()) {
3018 method.dup();
3019 }
3020 }
3021
3022 @Override
3023 public boolean enterAccessNode(final AccessNode node) {
3024 enterBaseNode();
3025 return false;
3026 }
3027
3028 @Override
3029 public boolean enterIndexNode(final IndexNode node) {
3030 enterBaseNode();
3031
3032 final Node index = node.getIndex();
3033 // could be boolean here as well
3034 load(index);
3035 if (!index.getType().isNumeric()) {
3036 method.convert(Type.OBJECT);
3037 }
3038 depth += index.getType().getSlots();
3039
3040 if (isSelfModifying()) {
3041 //convert "base base index" to "base index base index"
3042 method.dup(1);
3043 }
3044
3045 return false;
3046 }
3047
3048 });
3049 }
3050
3051 private Symbol quickSymbol(final Type type) {
3052 return quickSymbol(type, QUICK_PREFIX.symbolName());
3053 }
3054
3055 /**
3056 * Quick symbol generates an extra local variable, always using the same
3057 * slot, one that is available after the end of the frame.
3058 *
3059 * @param type the type of the symbol
3060 * @param prefix the prefix for the variable name for the symbol
3061 *
3062 * @return the quick symbol
3063 */
3064 private Symbol quickSymbol(final Type type, final String prefix) {
3065 final String name = lc.getCurrentFunction().uniqueName(prefix);
3066 final Symbol symbol = new Symbol(name, IS_TEMP | IS_INTERNAL);
3067
3068 symbol.setType(type);
3069
3070 symbol.setSlot(lc.quickSlot(symbol));
3071
3072 return symbol;
3073 }
3074
3075 // store the result that "lives on" after the op, e.g. "i" in i++ postfix.
3076 protected void storeNonDiscard() {
3077 if (lc.getCurrentDiscard() == assignNode) {
3078 assert assignNode.isAssignment();
3079 lc.popDiscard();
3080 return;
3081 }
3082
3083 final Symbol symbol = assignNode.getSymbol();
3084 if (symbol.hasSlot()) {
3085 method.dup().store(symbol);
3086 return;
3087 }
3088
3089 if (method.dup(depth) == null) {
3090 method.dup();
3091 this.quick = quickSymbol(method.peekType());
3092 method.store(quick);
3093 }
3094 }
3095
3096 private void epilogue() {
3097 /**
3098 * Take the original target args from the stack and use them
3099 * together with the value to be stored to emit the store code
3100 *
3101 * The case that targetSymbol is in scope (!hasSlot) and we actually
3102 * need to do a conversion on non-equivalent types exists, but is
3103 * very rare. See for example test/script/basic/access-specializer.js
3104 */
3105 method.convert(target.getType());
3106
3107 target.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
3108 @Override
3109 protected boolean enterDefault(Node node) {
3110 throw new AssertionError("Unexpected node " + node + " in store epilogue");
3111 }
3112
3113 @Override
3114 public boolean enterUnaryNode(final UnaryNode node) {
3115 if (node.tokenType() == TokenType.CONVERT && node.getSymbol() != null) {
3116 method.convert(node.rhs().getType());
3117 }
3118 return true;
3119 }
3120
3121 @Override
3122 public boolean enterIdentNode(final IdentNode node) {
3123 final Symbol symbol = node.getSymbol();
3124 assert symbol != null;
3125 if (symbol.isScope()) {
3126 if (isFastScope(symbol)) {
3127 storeFastScopeVar(node.getType(), symbol, CALLSITE_SCOPE | getCallSiteFlags());
3128 } else {
3129 method.dynamicSet(node.getType(), node.getName(), CALLSITE_SCOPE | getCallSiteFlags());
3130 }
3131 } else {
3132 method.store(symbol);
3133 }
3134 return false;
3135
3136 }
3137
3138 @Override
3139 public boolean enterAccessNode(final AccessNode node) {
3140 method.dynamicSet(node.getProperty().getType(), node.getProperty().getName(), getCallSiteFlags());
3141 return false;
3142 }
3143
3144 @Override
3145 public boolean enterIndexNode(final IndexNode node) {
3146 method.dynamicSetIndex(getCallSiteFlags());
3147 return false;
3148 }
3149 });
3150
3151
3152 // whatever is on the stack now is the final answer
3153 }
3154
3155 protected abstract void evaluate();
3156
3157 void store() {
3158 prologue();
3159 evaluate(); // leaves an operation of whatever the operationType was on the stack
3160 storeNonDiscard();
3161 epilogue();
3162 if (quick != null) {
3163 method.load(quick);
3164 }
3165 }
3166 }
3167
3168 private void newFunctionObject(final FunctionNode functionNode, final FunctionNode originalFunctionNode) {
3169 assert lc.peek() == functionNode;
3170 // We don't emit a ScriptFunction on stack for:
3171 // 1. the outermost compiled function (as there's no code being generated in its outer context that'd need it
3172 // as a callee), and
3173 // 2. for functions that are immediately called upon definition and they don't need a callee, e.g. (function(){})().
3174 // Such immediately-called functions are invoked using INVOKESTATIC (see enterFunctionNode() of the embedded
3175 // visitor of enterCallNode() for details), and if they don't need a callee, they don't have it on their
3176 // static method's parameter list.
3177 if (lc.getOutermostFunction() == functionNode ||
3178 (!functionNode.needsCallee()) && lc.isFunctionDefinedInCurrentCall(originalFunctionNode)) {
3179 return;
3180 }
3181
3182 final boolean isLazy = functionNode.isLazy();
3183
3184 new ObjectCreator(this, new ArrayList<String>(), new ArrayList<Symbol>(), false, false) {
3185 @Override
3186 protected void makeObject(final MethodEmitter m) {
3187 final String className = SCRIPTFUNCTION_IMPL_OBJECT;
3188
3189 m._new(className).dup();
3190 loadConstant(new RecompilableScriptFunctionData(functionNode, compiler.getCodeInstaller(), Compiler.binaryName(getClassName()), makeMap()));
3191
3192 if (isLazy || functionNode.needsParentScope()) {
3193 m.loadCompilerConstant(SCOPE);
3194 } else {
3195 m.loadNull();
3196 }
3197 m.invoke(constructorNoLookup(className, RecompilableScriptFunctionData.class, ScriptObject.class));
3198 }
3199 }.makeObject(method);
3200 }
3201
3202 /*
3203 * Globals are special. We cannot refer to any Global (or NativeObject) class by .class, as they are different
3204 * for different contexts. As far as I can tell, the only NativeObject that we need to deal with like this
3205 * is from the code pipeline is Global
3206 */
3207 private MethodEmitter globalInstance() {
3208 return method.invokestatic(GLOBAL_OBJECT, "instance", "()L" + GLOBAL_OBJECT + ';');
3209 }
3210
3211 private MethodEmitter globalObjectPrototype() {
3212 return method.invokestatic(GLOBAL_OBJECT, "objectPrototype", methodDescriptor(ScriptObject.class));
3213 }
3214
3215 private MethodEmitter globalAllocateArguments() {
3216 return method.invokestatic(GLOBAL_OBJECT, "allocateArguments", methodDescriptor(ScriptObject.class, Object[].class, Object.class, int.class));
3217 }
3218
3219 private MethodEmitter globalNewRegExp() {
3220 return method.invokestatic(GLOBAL_OBJECT, "newRegExp", methodDescriptor(Object.class, String.class, String.class));
3221 }
3222
3223 private MethodEmitter globalRegExpCopy() {
3224 return method.invokestatic(GLOBAL_OBJECT, "regExpCopy", methodDescriptor(Object.class, Object.class));
3225 }
3226
3227 private MethodEmitter globalAllocateArray(final ArrayType type) {
3228 //make sure the native array is treated as an array type
3229 return method.invokestatic(GLOBAL_OBJECT, "allocate", "(" + type.getDescriptor() + ")Ljdk/nashorn/internal/objects/NativeArray;");
3230 }
3231
3232 private MethodEmitter globalIsEval() {
3233 return method.invokestatic(GLOBAL_OBJECT, "isEval", methodDescriptor(boolean.class, Object.class));
3234 }
3235
3236 private MethodEmitter globalDirectEval() {
3237 return method.invokestatic(GLOBAL_OBJECT, "directEval",
3238 methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, Object.class));
3239 }
3240 }
--- EOF ---