CodeGenerator.java revision 1438:d09ca2242f2f
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
26package jdk.nashorn.internal.codegen;
27
28import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.PRIVATE;
29import static jdk.nashorn.internal.codegen.ClassEmitter.Flag.STATIC;
30import static jdk.nashorn.internal.codegen.CompilerConstants.ARGUMENTS;
31import static jdk.nashorn.internal.codegen.CompilerConstants.CALLEE;
32import static jdk.nashorn.internal.codegen.CompilerConstants.CREATE_PROGRAM_FUNCTION;
33import static jdk.nashorn.internal.codegen.CompilerConstants.GET_MAP;
34import static jdk.nashorn.internal.codegen.CompilerConstants.GET_STRING;
35import static jdk.nashorn.internal.codegen.CompilerConstants.QUICK_PREFIX;
36import static jdk.nashorn.internal.codegen.CompilerConstants.REGEX_PREFIX;
37import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE;
38import static jdk.nashorn.internal.codegen.CompilerConstants.SPLIT_PREFIX;
39import static jdk.nashorn.internal.codegen.CompilerConstants.THIS;
40import static jdk.nashorn.internal.codegen.CompilerConstants.VARARGS;
41import static jdk.nashorn.internal.codegen.CompilerConstants.interfaceCallNoLookup;
42import static jdk.nashorn.internal.codegen.CompilerConstants.methodDescriptor;
43import static jdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup;
44import static jdk.nashorn.internal.codegen.CompilerConstants.typeDescriptor;
45import static jdk.nashorn.internal.codegen.CompilerConstants.virtualCallNoLookup;
46import static jdk.nashorn.internal.ir.Symbol.HAS_SLOT;
47import static jdk.nashorn.internal.ir.Symbol.IS_INTERNAL;
48import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.INVALID_PROGRAM_POINT;
49import static jdk.nashorn.internal.runtime.UnwarrantedOptimismException.isValid;
50import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_APPLY_TO_CALL;
51import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_DECLARE;
52import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_FAST_SCOPE;
53import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_OPTIMISTIC;
54import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_PROGRAM_POINT_SHIFT;
55import static jdk.nashorn.internal.runtime.linker.NashornCallSiteDescriptor.CALLSITE_SCOPE;
56
57import java.io.PrintWriter;
58import java.util.ArrayDeque;
59import java.util.ArrayList;
60import java.util.Arrays;
61import java.util.BitSet;
62import java.util.Collection;
63import java.util.Collections;
64import java.util.Deque;
65import java.util.EnumSet;
66import java.util.HashMap;
67import java.util.HashSet;
68import java.util.Iterator;
69import java.util.LinkedList;
70import java.util.List;
71import java.util.Map;
72import java.util.Set;
73import java.util.TreeMap;
74import java.util.function.Supplier;
75import jdk.nashorn.internal.AssertsEnabled;
76import jdk.nashorn.internal.IntDeque;
77import jdk.nashorn.internal.codegen.ClassEmitter.Flag;
78import jdk.nashorn.internal.codegen.CompilerConstants.Call;
79import jdk.nashorn.internal.codegen.types.ArrayType;
80import jdk.nashorn.internal.codegen.types.Type;
81import jdk.nashorn.internal.ir.AccessNode;
82import jdk.nashorn.internal.ir.BaseNode;
83import jdk.nashorn.internal.ir.BinaryNode;
84import jdk.nashorn.internal.ir.Block;
85import jdk.nashorn.internal.ir.BlockStatement;
86import jdk.nashorn.internal.ir.BreakNode;
87import jdk.nashorn.internal.ir.CallNode;
88import jdk.nashorn.internal.ir.CaseNode;
89import jdk.nashorn.internal.ir.CatchNode;
90import jdk.nashorn.internal.ir.ContinueNode;
91import jdk.nashorn.internal.ir.EmptyNode;
92import jdk.nashorn.internal.ir.Expression;
93import jdk.nashorn.internal.ir.ExpressionStatement;
94import jdk.nashorn.internal.ir.ForNode;
95import jdk.nashorn.internal.ir.FunctionNode;
96import jdk.nashorn.internal.ir.GetSplitState;
97import jdk.nashorn.internal.ir.IdentNode;
98import jdk.nashorn.internal.ir.IfNode;
99import jdk.nashorn.internal.ir.IndexNode;
100import jdk.nashorn.internal.ir.JoinPredecessorExpression;
101import jdk.nashorn.internal.ir.JumpStatement;
102import jdk.nashorn.internal.ir.JumpToInlinedFinally;
103import jdk.nashorn.internal.ir.LabelNode;
104import jdk.nashorn.internal.ir.LexicalContext;
105import jdk.nashorn.internal.ir.LexicalContextNode;
106import jdk.nashorn.internal.ir.LiteralNode;
107import jdk.nashorn.internal.ir.LiteralNode.ArrayLiteralNode;
108import jdk.nashorn.internal.ir.LiteralNode.PrimitiveLiteralNode;
109import jdk.nashorn.internal.ir.LocalVariableConversion;
110import jdk.nashorn.internal.ir.LoopNode;
111import jdk.nashorn.internal.ir.Node;
112import jdk.nashorn.internal.ir.ObjectNode;
113import jdk.nashorn.internal.ir.Optimistic;
114import jdk.nashorn.internal.ir.PropertyNode;
115import jdk.nashorn.internal.ir.ReturnNode;
116import jdk.nashorn.internal.ir.RuntimeNode;
117import jdk.nashorn.internal.ir.RuntimeNode.Request;
118import jdk.nashorn.internal.ir.SetSplitState;
119import jdk.nashorn.internal.ir.SplitReturn;
120import jdk.nashorn.internal.ir.Splittable;
121import jdk.nashorn.internal.ir.Statement;
122import jdk.nashorn.internal.ir.SwitchNode;
123import jdk.nashorn.internal.ir.Symbol;
124import jdk.nashorn.internal.ir.TernaryNode;
125import jdk.nashorn.internal.ir.ThrowNode;
126import jdk.nashorn.internal.ir.TryNode;
127import jdk.nashorn.internal.ir.UnaryNode;
128import jdk.nashorn.internal.ir.VarNode;
129import jdk.nashorn.internal.ir.WhileNode;
130import jdk.nashorn.internal.ir.WithNode;
131import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
132import jdk.nashorn.internal.ir.visitor.NodeVisitor;
133import jdk.nashorn.internal.objects.Global;
134import jdk.nashorn.internal.parser.Lexer.RegexToken;
135import jdk.nashorn.internal.parser.TokenType;
136import jdk.nashorn.internal.runtime.Context;
137import jdk.nashorn.internal.runtime.Debug;
138import jdk.nashorn.internal.runtime.ECMAException;
139import jdk.nashorn.internal.runtime.JSType;
140import jdk.nashorn.internal.runtime.OptimisticReturnFilters;
141import jdk.nashorn.internal.runtime.PropertyMap;
142import jdk.nashorn.internal.runtime.RecompilableScriptFunctionData;
143import jdk.nashorn.internal.runtime.RewriteException;
144import jdk.nashorn.internal.runtime.Scope;
145import jdk.nashorn.internal.runtime.ScriptEnvironment;
146import jdk.nashorn.internal.runtime.ScriptFunction;
147import jdk.nashorn.internal.runtime.ScriptObject;
148import jdk.nashorn.internal.runtime.ScriptRuntime;
149import jdk.nashorn.internal.runtime.Source;
150import jdk.nashorn.internal.runtime.Undefined;
151import jdk.nashorn.internal.runtime.UnwarrantedOptimismException;
152import jdk.nashorn.internal.runtime.arrays.ArrayData;
153import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
154import jdk.nashorn.internal.runtime.logging.DebugLogger;
155import jdk.nashorn.internal.runtime.logging.Loggable;
156import jdk.nashorn.internal.runtime.logging.Logger;
157import jdk.nashorn.internal.runtime.options.Options;
158
159/**
160 * This is the lowest tier of the code generator. It takes lowered ASTs emitted
161 * from Lower and emits Java byte code. The byte code emission logic is broken
162 * out into MethodEmitter. MethodEmitter works internally with a type stack, and
163 * keeps track of the contents of the byte code stack. This way we avoid a large
164 * number of special cases on the form
165 * <pre>
166 * if (type == INT) {
167 *     visitInsn(ILOAD, slot);
168 * } else if (type == DOUBLE) {
169 *     visitInsn(DOUBLE, slot);
170 * }
171 * </pre>
172 * This quickly became apparent when the code generator was generalized to work
173 * with all types, and not just numbers or objects.
174 * <p>
175 * The CodeGenerator visits nodes only once and emits bytecode for them.
176 */
177@Logger(name="codegen")
178final class CodeGenerator extends NodeOperatorVisitor<CodeGeneratorLexicalContext> implements Loggable {
179
180    private static final Type SCOPE_TYPE = Type.typeFor(ScriptObject.class);
181
182    private static final String GLOBAL_OBJECT = Type.getInternalName(Global.class);
183
184    private static final Call CREATE_REWRITE_EXCEPTION = CompilerConstants.staticCallNoLookup(RewriteException.class,
185            "create", RewriteException.class, UnwarrantedOptimismException.class, Object[].class, String[].class);
186    private static final Call CREATE_REWRITE_EXCEPTION_REST_OF = CompilerConstants.staticCallNoLookup(RewriteException.class,
187            "create", RewriteException.class, UnwarrantedOptimismException.class, Object[].class, String[].class, int[].class);
188
189    private static final Call ENSURE_INT = CompilerConstants.staticCallNoLookup(OptimisticReturnFilters.class,
190            "ensureInt", int.class, Object.class, int.class);
191    private static final Call ENSURE_LONG = CompilerConstants.staticCallNoLookup(OptimisticReturnFilters.class,
192            "ensureLong", long.class, Object.class, int.class);
193    private static final Call ENSURE_NUMBER = CompilerConstants.staticCallNoLookup(OptimisticReturnFilters.class,
194            "ensureNumber", double.class, Object.class, int.class);
195
196    private static final Call CREATE_FUNCTION_OBJECT = CompilerConstants.staticCallNoLookup(ScriptFunction.class,
197            "create", ScriptFunction.class, Object[].class, int.class, ScriptObject.class);
198    private static final Call CREATE_FUNCTION_OBJECT_NO_SCOPE = CompilerConstants.staticCallNoLookup(ScriptFunction.class,
199            "create", ScriptFunction.class, Object[].class, int.class);
200
201    private static final Call TO_NUMBER_FOR_EQ = CompilerConstants.staticCallNoLookup(JSType.class,
202            "toNumberForEq", double.class, Object.class);
203    private static final Call TO_NUMBER_FOR_STRICT_EQ = CompilerConstants.staticCallNoLookup(JSType.class,
204            "toNumberForStrictEq", double.class, Object.class);
205
206
207    private static final Class<?> ITERATOR_CLASS = Iterator.class;
208    static {
209        assert ITERATOR_CLASS == CompilerConstants.ITERATOR_PREFIX.type();
210    }
211    private static final Type ITERATOR_TYPE = Type.typeFor(ITERATOR_CLASS);
212    private static final Type EXCEPTION_TYPE = Type.typeFor(CompilerConstants.EXCEPTION_PREFIX.type());
213
214    private static final Integer INT_ZERO = 0;
215
216    /** Constant data & installation. The only reason the compiler keeps this is because it is assigned
217     *  by reflection in class installation */
218    private final Compiler compiler;
219
220    /** Is the current code submitted by 'eval' call? */
221    private final boolean evalCode;
222
223    /** Call site flags given to the code generator to be used for all generated call sites */
224    private final int callSiteFlags;
225
226    /** How many regexp fields have been emitted */
227    private int regexFieldCount;
228
229    /** Line number for last statement. If we encounter a new line number, line number bytecode information
230     *  needs to be generated */
231    private int lastLineNumber = -1;
232
233    /** When should we stop caching regexp expressions in fields to limit bytecode size? */
234    private static final int MAX_REGEX_FIELDS = 2 * 1024;
235
236    /** Current method emitter */
237    private MethodEmitter method;
238
239    /** Current compile unit */
240    private CompileUnit unit;
241
242    private final DebugLogger log;
243
244    /** From what size should we use spill instead of fields for JavaScript objects? */
245    static final int OBJECT_SPILL_THRESHOLD = Options.getIntProperty("nashorn.spill.threshold", 256);
246
247    private final Set<String> emittedMethods = new HashSet<>();
248
249    // Function Id -> ContinuationInfo. Used by compilation of rest-of function only.
250    private ContinuationInfo continuationInfo;
251
252    private final Deque<Label> scopeEntryLabels = new ArrayDeque<>();
253
254    private static final Label METHOD_BOUNDARY = new Label("");
255    private final Deque<Label> catchLabels = new ArrayDeque<>();
256    // Number of live locals on entry to (and thus also break from) labeled blocks.
257    private final IntDeque labeledBlockBreakLiveLocals = new IntDeque();
258
259    //is this a rest of compilation
260    private final int[] continuationEntryPoints;
261
262    /**
263     * Constructor.
264     *
265     * @param compiler
266     */
267    CodeGenerator(final Compiler compiler, final int[] continuationEntryPoints) {
268        super(new CodeGeneratorLexicalContext());
269        this.compiler                = compiler;
270        this.evalCode                = compiler.getSource().isEvalCode();
271        this.continuationEntryPoints = continuationEntryPoints;
272        this.callSiteFlags           = compiler.getScriptEnvironment()._callsite_flags;
273        this.log                     = initLogger(compiler.getContext());
274    }
275
276    @Override
277    public DebugLogger getLogger() {
278        return log;
279    }
280
281    @Override
282    public DebugLogger initLogger(final Context context) {
283        return context.getLogger(this.getClass());
284    }
285
286    /**
287     * Gets the call site flags, adding the strict flag if the current function
288     * being generated is in strict mode
289     *
290     * @return the correct flags for a call site in the current function
291     */
292    int getCallSiteFlags() {
293        return lc.getCurrentFunction().getCallSiteFlags() | callSiteFlags;
294    }
295
296    /**
297     * Gets the flags for a scope call site.
298     * @param symbol a scope symbol
299     * @return the correct flags for the scope call site
300     */
301    private int getScopeCallSiteFlags(final Symbol symbol) {
302        assert symbol.isScope();
303        final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
304        if (isEvalCode() && symbol.isGlobal()) {
305            return flags; // Don't set fast-scope flag on non-declared globals in eval code - see JDK-8077955.
306        }
307        return isFastScope(symbol) ? flags | CALLSITE_FAST_SCOPE : flags;
308    }
309
310    /**
311     * Are we generating code for 'eval' code?
312     * @return true if currently compiled code is 'eval' code.
313     */
314    boolean isEvalCode() {
315        return evalCode;
316    }
317
318    /**
319     * Are we using dual primitive/object field representation?
320     * @return true if using dual field representation, false for object-only fields
321     */
322    boolean useDualFields() {
323        return compiler.getContext().useDualFields();
324    }
325
326    /**
327     * Load an identity node
328     *
329     * @param identNode an identity node to load
330     * @return the method generator used
331     */
332    private MethodEmitter loadIdent(final IdentNode identNode, final TypeBounds resultBounds) {
333        checkTemporalDeadZone(identNode);
334        final Symbol symbol = identNode.getSymbol();
335
336        if (!symbol.isScope()) {
337            final Type type = identNode.getType();
338            if(type == Type.UNDEFINED) {
339                return method.loadUndefined(resultBounds.widest);
340            }
341
342            assert symbol.hasSlot() || symbol.isParam();
343            return method.load(identNode);
344        }
345
346        assert identNode.getSymbol().isScope() : identNode + " is not in scope!";
347        final int flags = getScopeCallSiteFlags(symbol);
348        if (isFastScope(symbol)) {
349            // Only generate shared scope getter for fast-scope symbols so we know we can dial in correct scope.
350            if (symbol.getUseCount() > SharedScopeCall.FAST_SCOPE_GET_THRESHOLD && !identNode.isOptimistic()) {
351                // As shared scope vars are only used with non-optimistic identifiers, we switch from using TypeBounds to
352                // just a single definitive type, resultBounds.widest.
353                new OptimisticOperation(identNode, TypeBounds.OBJECT) {
354                    @Override
355                    void loadStack() {
356                        method.loadCompilerConstant(SCOPE);
357                    }
358
359                    @Override
360                    void consumeStack() {
361                        loadSharedScopeVar(resultBounds.widest, symbol, flags);
362                    }
363                }.emit();
364            } else {
365                new LoadFastScopeVar(identNode, resultBounds, flags).emit();
366            }
367        } else {
368            //slow scope load, we have no proto depth
369            new LoadScopeVar(identNode, resultBounds, flags).emit();
370        }
371
372        return method;
373    }
374
375    // Any access to LET and CONST variables before their declaration must throw ReferenceError.
376    // This is called the temporal dead zone (TDZ). See https://gist.github.com/rwaldron/f0807a758aa03bcdd58a
377    private void checkTemporalDeadZone(final IdentNode identNode) {
378        if (identNode.isDead()) {
379            method.load(identNode.getSymbol().getName()).invoke(ScriptRuntime.THROW_REFERENCE_ERROR);
380        }
381    }
382
383    // Runtime check for assignment to ES6 const
384    private void checkAssignTarget(final Expression expression) {
385        if (expression instanceof IdentNode && ((IdentNode)expression).getSymbol().isConst()) {
386            method.load(((IdentNode)expression).getSymbol().getName()).invoke(ScriptRuntime.THROW_CONST_TYPE_ERROR);
387        }
388    }
389
390    private boolean isRestOf() {
391        return continuationEntryPoints != null;
392    }
393
394    private boolean isCurrentContinuationEntryPoint(final int programPoint) {
395        return isRestOf() && getCurrentContinuationEntryPoint() == programPoint;
396    }
397
398    private int[] getContinuationEntryPoints() {
399        return isRestOf() ? continuationEntryPoints : null;
400    }
401
402    private int getCurrentContinuationEntryPoint() {
403        return isRestOf() ? continuationEntryPoints[0] : INVALID_PROGRAM_POINT;
404    }
405
406    private boolean isContinuationEntryPoint(final int programPoint) {
407        if (isRestOf()) {
408            assert continuationEntryPoints != null;
409            for (final int cep : continuationEntryPoints) {
410                if (cep == programPoint) {
411                    return true;
412                }
413            }
414        }
415        return false;
416    }
417
418    /**
419     * Check if this symbol can be accessed directly with a putfield or getfield or dynamic load
420     *
421     * @param symbol symbol to check for fast scope
422     * @return true if fast scope
423     */
424    private boolean isFastScope(final Symbol symbol) {
425        if (!symbol.isScope()) {
426            return false;
427        }
428
429        if (!lc.inDynamicScope()) {
430            // If there's no with or eval in context, and the symbol is marked as scoped, it is fast scoped. Such a
431            // symbol must either be global, or its defining block must need scope.
432            assert symbol.isGlobal() || lc.getDefiningBlock(symbol).needsScope() : symbol.getName();
433            return true;
434        }
435
436        if (symbol.isGlobal()) {
437            // Shortcut: if there's a with or eval in context, globals can't be fast scoped
438            return false;
439        }
440
441        // Otherwise, check if there's a dynamic scope between use of the symbol and its definition
442        final String name = symbol.getName();
443        boolean previousWasBlock = false;
444        for (final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) {
445            final LexicalContextNode node = it.next();
446            if (node instanceof Block) {
447                // If this block defines the symbol, then we can fast scope the symbol.
448                final Block block = (Block)node;
449                if (block.getExistingSymbol(name) == symbol) {
450                    assert block.needsScope();
451                    return true;
452                }
453                previousWasBlock = true;
454            } else {
455                if (node instanceof WithNode && previousWasBlock || node instanceof FunctionNode && ((FunctionNode)node).needsDynamicScope()) {
456                    // If we hit a scope that can have symbols introduced into it at run time before finding the defining
457                    // block, the symbol can't be fast scoped. A WithNode only counts if we've immediately seen a block
458                    // before - its block. Otherwise, we are currently processing the WithNode's expression, and that's
459                    // obviously not subjected to introducing new symbols.
460                    return false;
461                }
462                previousWasBlock = false;
463            }
464        }
465        // Should've found the symbol defined in a block
466        throw new AssertionError();
467    }
468
469    private MethodEmitter loadSharedScopeVar(final Type valueType, final Symbol symbol, final int flags) {
470        assert isFastScope(symbol);
471        method.load(getScopeProtoDepth(lc.getCurrentBlock(), symbol));
472        return lc.getScopeGet(unit, symbol, valueType, flags).generateInvoke(method);
473    }
474
475    private class LoadScopeVar extends OptimisticOperation {
476        final IdentNode identNode;
477        private final int flags;
478
479        LoadScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
480            super(identNode, resultBounds);
481            this.identNode = identNode;
482            this.flags = flags;
483        }
484
485        @Override
486        void loadStack() {
487            method.loadCompilerConstant(SCOPE);
488            getProto();
489        }
490
491        void getProto() {
492            //empty
493        }
494
495        @Override
496        void consumeStack() {
497            // If this is either __FILE__, __DIR__, or __LINE__ then load the property initially as Object as we'd convert
498            // it anyway for replaceLocationPropertyPlaceholder.
499            if(identNode.isCompileTimePropertyName()) {
500                method.dynamicGet(Type.OBJECT, identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
501                replaceCompileTimeProperty();
502            } else {
503                dynamicGet(identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
504            }
505        }
506    }
507
508    private class LoadFastScopeVar extends LoadScopeVar {
509        LoadFastScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
510            super(identNode, resultBounds, flags);
511        }
512
513        @Override
514        void getProto() {
515            loadFastScopeProto(identNode.getSymbol(), false);
516        }
517    }
518
519    private MethodEmitter storeFastScopeVar(final Symbol symbol, final int flags) {
520        loadFastScopeProto(symbol, true);
521        method.dynamicSet(symbol.getName(), flags, false);
522        return method;
523    }
524
525    private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
526        //walk up the chain from starting block and when we bump into the current function boundary, add the external
527        //information.
528        final FunctionNode fn   = lc.getCurrentFunction();
529        final int externalDepth = compiler.getScriptFunctionData(fn.getId()).getExternalSymbolDepth(symbol.getName());
530
531        //count the number of scopes from this place to the start of the function
532
533        final int internalDepth = FindScopeDepths.findInternalDepth(lc, fn, startingBlock, symbol);
534        final int scopesToStart = FindScopeDepths.findScopesToStart(lc, fn, startingBlock);
535        int depth = 0;
536        if (internalDepth == -1) {
537            depth = scopesToStart + externalDepth;
538        } else {
539            assert internalDepth <= scopesToStart;
540            depth = internalDepth;
541        }
542
543        return depth;
544    }
545
546    private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
547        final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
548        assert depth != -1 : "Couldn't find scope depth for symbol " + symbol.getName() + " in " + lc.getCurrentFunction();
549        if (depth > 0) {
550            if (swap) {
551                method.swap();
552            }
553            for (int i = 0; i < depth; i++) {
554                method.invoke(ScriptObject.GET_PROTO);
555            }
556            if (swap) {
557                method.swap();
558            }
559        }
560    }
561
562    /**
563     * Generate code that loads this node to the stack, not constraining its type
564     *
565     * @param expr node to load
566     *
567     * @return the method emitter used
568     */
569    private MethodEmitter loadExpressionUnbounded(final Expression expr) {
570        return loadExpression(expr, TypeBounds.UNBOUNDED);
571    }
572
573    private MethodEmitter loadExpressionAsObject(final Expression expr) {
574        return loadExpression(expr, TypeBounds.OBJECT);
575    }
576
577    MethodEmitter loadExpressionAsBoolean(final Expression expr) {
578        return loadExpression(expr, TypeBounds.BOOLEAN);
579    }
580
581    // Test whether conversion from source to target involves a call of ES 9.1 ToPrimitive
582    // with possible side effects from calling an object's toString or valueOf methods.
583    private static boolean noToPrimitiveConversion(final Type source, final Type target) {
584        // Object to boolean conversion does not cause ToPrimitive call
585        return source.isJSPrimitive() || !target.isJSPrimitive() || target.isBoolean();
586    }
587
588    MethodEmitter loadBinaryOperands(final BinaryNode binaryNode) {
589        return loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), TypeBounds.UNBOUNDED.notWiderThan(binaryNode.getWidestOperandType()), false, false);
590    }
591
592    private MethodEmitter loadBinaryOperands(final Expression lhs, final Expression rhs, final TypeBounds explicitOperandBounds, final boolean baseAlreadyOnStack, final boolean forceConversionSeparation) {
593        // ECMAScript 5.1 specification (sections 11.5-11.11 and 11.13) prescribes that when evaluating a binary
594        // expression "LEFT op RIGHT", the order of operations must be: LOAD LEFT, LOAD RIGHT, CONVERT LEFT, CONVERT
595        // RIGHT, EXECUTE OP. Unfortunately, doing it in this order defeats potential optimizations that arise when we
596        // can combine a LOAD with a CONVERT operation (e.g. use a dynamic getter with the conversion target type as its
597        // return value). What we do here is reorder LOAD RIGHT and CONVERT LEFT when possible; it is possible only when
598        // we can prove that executing CONVERT LEFT can't have a side effect that changes the value of LOAD RIGHT.
599        // Basically, if we know that either LEFT already is a primitive value, or does not have to be converted to
600        // a primitive value, or RIGHT is an expression that loads without side effects, then we can do the
601        // reordering and collapse LOAD/CONVERT into a single operation; otherwise we need to do the more costly
602        // separate operations to preserve specification semantics.
603
604        // Operands' load type should not be narrower than the narrowest of the individual operand types, nor narrower
605        // than the lower explicit bound, but it should also not be wider than
606        final Type lhsType = undefinedToNumber(lhs.getType());
607        final Type rhsType = undefinedToNumber(rhs.getType());
608        final Type narrowestOperandType = Type.narrowest(Type.widest(lhsType, rhsType), explicitOperandBounds.widest);
609        final TypeBounds operandBounds = explicitOperandBounds.notNarrowerThan(narrowestOperandType);
610        if (noToPrimitiveConversion(lhsType, explicitOperandBounds.widest) || rhs.isLocal()) {
611            // Can reorder. We might still need to separate conversion, but at least we can do it with reordering
612            if (forceConversionSeparation) {
613                // Can reorder, but can't move conversion into the operand as the operation depends on operands
614                // exact types for its overflow guarantees. E.g. with {L}{%I}expr1 {L}* {L}{%I}expr2 we are not allowed
615                // to merge {L}{%I} into {%L}, as that can cause subsequent overflows; test for JDK-8058610 contains
616                // concrete cases where this could happen.
617                final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
618                loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
619                method.convert(operandBounds.within(method.peekType()));
620                loadExpression(rhs, safeConvertBounds, false);
621                method.convert(operandBounds.within(method.peekType()));
622            } else {
623                // Can reorder and move conversion into the operand. Combine load and convert into single operations.
624                loadExpression(lhs, operandBounds, baseAlreadyOnStack);
625                loadExpression(rhs, operandBounds, false);
626            }
627        } else {
628            // Can't reorder. Load and convert separately.
629            final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
630            loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
631            final Type lhsLoadedType = method.peekType();
632            loadExpression(rhs, safeConvertBounds, false);
633            final Type convertedLhsType = operandBounds.within(method.peekType());
634            if (convertedLhsType != lhsLoadedType) {
635                // Do it conditionally, so that if conversion is a no-op we don't introduce a SWAP, SWAP.
636                method.swap().convert(convertedLhsType).swap();
637            }
638            method.convert(operandBounds.within(method.peekType()));
639        }
640        assert Type.generic(method.peekType()) == operandBounds.narrowest;
641        assert Type.generic(method.peekType(1)) == operandBounds.narrowest;
642
643        return method;
644    }
645
646    /**
647     * Similar to {@link #loadBinaryOperands(BinaryNode)} but used specifically for loading operands of
648     * relational and equality comparison operators where at least one argument is non-object. (When both
649     * arguments are objects, we use {@link ScriptRuntime#EQ(Object, Object)}, {@link ScriptRuntime#LT(Object, Object)}
650     * etc. methods instead. Additionally, {@code ScriptRuntime} methods are used for strict (in)equality comparison
651     * of a boolean to anything that isn't a boolean.) This method handles the special case where one argument
652     * is an object and another is a primitive. Naively, these could also be delegated to {@code ScriptRuntime} methods
653     * by boxing the primitive. However, in all such cases the comparison is performed on numeric values, so it is
654     * possible to strength-reduce the operation by taking the number value of the object argument instead and
655     * comparing that to the primitive value ("primitive" will always be int, long, double, or boolean, and booleans
656     * compare as ints in these cases, so they're essentially numbers too). This method will emit code for loading
657     * arguments for such strength-reduced comparison. When both arguments are primitives, it just delegates to
658     * {@link #loadBinaryOperands(BinaryNode)}.
659     *
660     * @param cmp the comparison operation for which the operands need to be loaded on stack.
661     * @return the current method emitter.
662     */
663    MethodEmitter loadComparisonOperands(final BinaryNode cmp) {
664        final Expression lhs = cmp.lhs();
665        final Expression rhs = cmp.rhs();
666        final Type lhsType = lhs.getType();
667        final Type rhsType = rhs.getType();
668
669        // Only used when not both are object, for that we have ScriptRuntime.LT etc.
670        assert !(lhsType.isObject() && rhsType.isObject());
671
672        if (lhsType.isObject() || rhsType.isObject()) {
673            // We can reorder CONVERT LEFT and LOAD RIGHT only if either the left is a primitive, or the right
674            // is a local. This is more strict than loadBinaryNode reorder criteria, as it can allow JS primitive
675            // types too (notably: String is a JS primitive, but not a JVM primitive). We disallow String otherwise
676            // we would prematurely convert it to number when comparing to an optimistic expression, e.g. in
677            // "Hello" === String("Hello") the RHS starts out as an optimistic-int function call. If we allowed
678            // reordering, we'd end up with ToNumber("Hello") === {I%}String("Hello") that is obviously incorrect.
679            final boolean canReorder = lhsType.isPrimitive() || rhs.isLocal();
680            // If reordering is allowed, and we're using a relational operator (that is, <, <=, >, >=) and not an
681            // (in)equality operator, then we encourage combining of LOAD and CONVERT into a single operation.
682            // This is because relational operators' semantics prescribes vanilla ToNumber() conversion, while
683            // (in)equality operators need the specialized JSType.toNumberFor[Strict]Equals. E.g. in the code snippet
684            // "i < obj.size" (where i is primitive and obj.size is statically an object), ".size" will thus be allowed
685            // to compile as:
686            //   invokedynamic dyn:getProp|getElem|getMethod:size(Object;)D
687            // instead of the more costly:
688            //   invokedynamic dyn:getProp|getElem|getMethod:size(Object;)Object
689            //   invokestatic JSType.toNumber(Object)D
690            // Note also that even if this is allowed, we're only using it on operands that are non-optimistic, as
691            // otherwise the logic for determining effective optimistic-ness would turn an optimistic double return
692            // into a freely coercible one, which would be wrong.
693            final boolean canCombineLoadAndConvert = canReorder && cmp.isRelational();
694
695            // LOAD LEFT
696            loadExpression(lhs, canCombineLoadAndConvert && !lhs.isOptimistic() ? TypeBounds.NUMBER : TypeBounds.UNBOUNDED);
697
698            final Type lhsLoadedType = method.peekType();
699            final TokenType tt = cmp.tokenType();
700            if (canReorder) {
701                // Can reorder CONVERT LEFT and LOAD RIGHT
702                emitObjectToNumberComparisonConversion(method, tt);
703                loadExpression(rhs, canCombineLoadAndConvert && !rhs.isOptimistic() ? TypeBounds.NUMBER : TypeBounds.UNBOUNDED);
704            } else {
705                // Can't reorder CONVERT LEFT and LOAD RIGHT
706                loadExpression(rhs, TypeBounds.UNBOUNDED);
707                if (lhsLoadedType != Type.NUMBER) {
708                    method.swap();
709                    emitObjectToNumberComparisonConversion(method, tt);
710                    method.swap();
711                }
712            }
713
714            // CONVERT RIGHT
715            emitObjectToNumberComparisonConversion(method, tt);
716            return method;
717        }
718        // For primitive operands, just don't do anything special.
719        return loadBinaryOperands(cmp);
720    }
721
722    private static void emitObjectToNumberComparisonConversion(final MethodEmitter method, final TokenType tt) {
723        switch(tt) {
724        case EQ:
725        case NE:
726            if (method.peekType().isObject()) {
727                TO_NUMBER_FOR_EQ.invoke(method);
728                return;
729            }
730            break;
731        case EQ_STRICT:
732        case NE_STRICT:
733            if (method.peekType().isObject()) {
734                TO_NUMBER_FOR_STRICT_EQ.invoke(method);
735                return;
736            }
737            break;
738        default:
739            break;
740        }
741        method.convert(Type.NUMBER);
742    }
743
744    private static Type undefinedToNumber(final Type type) {
745        return type == Type.UNDEFINED ? Type.NUMBER : type;
746    }
747
748    private static final class TypeBounds {
749        final Type narrowest;
750        final Type widest;
751
752        static final TypeBounds UNBOUNDED = new TypeBounds(Type.UNKNOWN, Type.OBJECT);
753        static final TypeBounds INT = exact(Type.INT);
754        static final TypeBounds NUMBER = exact(Type.NUMBER);
755        static final TypeBounds OBJECT = exact(Type.OBJECT);
756        static final TypeBounds BOOLEAN = exact(Type.BOOLEAN);
757
758        static TypeBounds exact(final Type type) {
759            return new TypeBounds(type, type);
760        }
761
762        TypeBounds(final Type narrowest, final Type widest) {
763            assert widest    != null && widest    != Type.UNDEFINED && widest != Type.UNKNOWN : widest;
764            assert narrowest != null && narrowest != Type.UNDEFINED : narrowest;
765            assert !narrowest.widerThan(widest) : narrowest + " wider than " + widest;
766            assert !widest.narrowerThan(narrowest);
767            this.narrowest = Type.generic(narrowest);
768            this.widest = Type.generic(widest);
769        }
770
771        TypeBounds notNarrowerThan(final Type type) {
772            return maybeNew(Type.narrowest(Type.widest(narrowest, type), widest), widest);
773        }
774
775        TypeBounds notWiderThan(final Type type) {
776            return maybeNew(Type.narrowest(narrowest, type), Type.narrowest(widest, type));
777        }
778
779        boolean canBeNarrowerThan(final Type type) {
780            return narrowest.narrowerThan(type);
781        }
782
783        TypeBounds maybeNew(final Type newNarrowest, final Type newWidest) {
784            if(newNarrowest == narrowest && newWidest == widest) {
785                return this;
786            }
787            return new TypeBounds(newNarrowest, newWidest);
788        }
789
790        TypeBounds booleanToInt() {
791            return maybeNew(CodeGenerator.booleanToInt(narrowest), CodeGenerator.booleanToInt(widest));
792        }
793
794        TypeBounds objectToNumber() {
795            return maybeNew(CodeGenerator.objectToNumber(narrowest), CodeGenerator.objectToNumber(widest));
796        }
797
798        Type within(final Type type) {
799            if(type.narrowerThan(narrowest)) {
800                return narrowest;
801            }
802            if(type.widerThan(widest)) {
803                return widest;
804            }
805            return type;
806        }
807
808        @Override
809        public String toString() {
810            return "[" + narrowest + ", " + widest + "]";
811        }
812    }
813
814    private static Type booleanToInt(final Type t) {
815        return t == Type.BOOLEAN ? Type.INT : t;
816    }
817
818    private static Type objectToNumber(final Type t) {
819        return t.isObject() ? Type.NUMBER : t;
820    }
821
822    MethodEmitter loadExpressionAsType(final Expression expr, final Type type) {
823        if(type == Type.BOOLEAN) {
824            return loadExpressionAsBoolean(expr);
825        } else if(type == Type.UNDEFINED) {
826            assert expr.getType() == Type.UNDEFINED;
827            return loadExpressionAsObject(expr);
828        }
829        // having no upper bound preserves semantics of optimistic operations in the expression (by not having them
830        // converted early) and then applies explicit conversion afterwards.
831        return loadExpression(expr, TypeBounds.UNBOUNDED.notNarrowerThan(type)).convert(type);
832    }
833
834    private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds) {
835        return loadExpression(expr, resultBounds, false);
836    }
837
838    /**
839     * Emits code for evaluating an expression and leaving its value on top of the stack, narrowing or widening it if
840     * necessary.
841     * @param expr the expression to load
842     * @param resultBounds the incoming type bounds. The value on the top of the stack is guaranteed to not be of narrower
843     * type than the narrowest bound, or wider type than the widest bound after it is loaded.
844     * @param baseAlreadyOnStack true if the base of an access or index node is already on the stack. Used to avoid
845     * double evaluation of bases in self-assignment expressions to access and index nodes. {@code Type.OBJECT} is used
846     * to indicate the widest possible type.
847     * @return the method emitter
848     */
849    private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds, final boolean baseAlreadyOnStack) {
850
851        /*
852         * The load may be of type IdentNode, e.g. "x", AccessNode, e.g. "x.y"
853         * or IndexNode e.g. "x[y]". Both AccessNodes and IndexNodes are
854         * BaseNodes and the logic for loading the base object is reused
855         */
856        final CodeGenerator codegen = this;
857
858        final boolean isCurrentDiscard = codegen.lc.isCurrentDiscard(expr);
859        expr.accept(new NodeOperatorVisitor<LexicalContext>(new LexicalContext()) {
860            @Override
861            public boolean enterIdentNode(final IdentNode identNode) {
862                loadIdent(identNode, resultBounds);
863                return false;
864            }
865
866            @Override
867            public boolean enterAccessNode(final AccessNode accessNode) {
868                new OptimisticOperation(accessNode, resultBounds) {
869                    @Override
870                    void loadStack() {
871                        if (!baseAlreadyOnStack) {
872                            loadExpressionAsObject(accessNode.getBase());
873                        }
874                        assert method.peekType().isObject();
875                    }
876                    @Override
877                    void consumeStack() {
878                        final int flags = getCallSiteFlags();
879                        dynamicGet(accessNode.getProperty(), flags, accessNode.isFunction(), accessNode.isIndex());
880                    }
881                }.emit(baseAlreadyOnStack ? 1 : 0);
882                return false;
883            }
884
885            @Override
886            public boolean enterIndexNode(final IndexNode indexNode) {
887                new OptimisticOperation(indexNode, resultBounds) {
888                    @Override
889                    void loadStack() {
890                        if (!baseAlreadyOnStack) {
891                            loadExpressionAsObject(indexNode.getBase());
892                            loadExpressionUnbounded(indexNode.getIndex());
893                        }
894                    }
895                    @Override
896                    void consumeStack() {
897                        final int flags = getCallSiteFlags();
898                        dynamicGetIndex(flags, indexNode.isFunction());
899                    }
900                }.emit(baseAlreadyOnStack ? 2 : 0);
901                return false;
902            }
903
904            @Override
905            public boolean enterFunctionNode(final FunctionNode functionNode) {
906                // function nodes will always leave a constructed function object on stack, no need to load the symbol
907                // separately as in enterDefault()
908                lc.pop(functionNode);
909                functionNode.accept(codegen);
910                // NOTE: functionNode.accept() will produce a different FunctionNode that we discard. This incidentally
911                // doesn't cause problems as we're never touching FunctionNode again after it's visited here - codegen
912                // is the last element in the compilation pipeline, the AST it produces is not used externally. So, we
913                // re-push the original functionNode.
914                lc.push(functionNode);
915                return false;
916            }
917
918            @Override
919            public boolean enterASSIGN(final BinaryNode binaryNode) {
920                checkAssignTarget(binaryNode.lhs());
921                loadASSIGN(binaryNode);
922                return false;
923            }
924
925            @Override
926            public boolean enterASSIGN_ADD(final BinaryNode binaryNode) {
927                checkAssignTarget(binaryNode.lhs());
928                loadASSIGN_ADD(binaryNode);
929                return false;
930            }
931
932            @Override
933            public boolean enterASSIGN_BIT_AND(final BinaryNode binaryNode) {
934                checkAssignTarget(binaryNode.lhs());
935                loadASSIGN_BIT_AND(binaryNode);
936                return false;
937            }
938
939            @Override
940            public boolean enterASSIGN_BIT_OR(final BinaryNode binaryNode) {
941                checkAssignTarget(binaryNode.lhs());
942                loadASSIGN_BIT_OR(binaryNode);
943                return false;
944            }
945
946            @Override
947            public boolean enterASSIGN_BIT_XOR(final BinaryNode binaryNode) {
948                checkAssignTarget(binaryNode.lhs());
949                loadASSIGN_BIT_XOR(binaryNode);
950                return false;
951            }
952
953            @Override
954            public boolean enterASSIGN_DIV(final BinaryNode binaryNode) {
955                checkAssignTarget(binaryNode.lhs());
956                loadASSIGN_DIV(binaryNode);
957                return false;
958            }
959
960            @Override
961            public boolean enterASSIGN_MOD(final BinaryNode binaryNode) {
962                checkAssignTarget(binaryNode.lhs());
963                loadASSIGN_MOD(binaryNode);
964                return false;
965            }
966
967            @Override
968            public boolean enterASSIGN_MUL(final BinaryNode binaryNode) {
969                checkAssignTarget(binaryNode.lhs());
970                loadASSIGN_MUL(binaryNode);
971                return false;
972            }
973
974            @Override
975            public boolean enterASSIGN_SAR(final BinaryNode binaryNode) {
976                checkAssignTarget(binaryNode.lhs());
977                loadASSIGN_SAR(binaryNode);
978                return false;
979            }
980
981            @Override
982            public boolean enterASSIGN_SHL(final BinaryNode binaryNode) {
983                checkAssignTarget(binaryNode.lhs());
984                loadASSIGN_SHL(binaryNode);
985                return false;
986            }
987
988            @Override
989            public boolean enterASSIGN_SHR(final BinaryNode binaryNode) {
990                checkAssignTarget(binaryNode.lhs());
991                loadASSIGN_SHR(binaryNode);
992                return false;
993            }
994
995            @Override
996            public boolean enterASSIGN_SUB(final BinaryNode binaryNode) {
997                checkAssignTarget(binaryNode.lhs());
998                loadASSIGN_SUB(binaryNode);
999                return false;
1000            }
1001
1002            @Override
1003            public boolean enterCallNode(final CallNode callNode) {
1004                return loadCallNode(callNode, resultBounds);
1005            }
1006
1007            @Override
1008            public boolean enterLiteralNode(final LiteralNode<?> literalNode) {
1009                loadLiteral(literalNode, resultBounds);
1010                return false;
1011            }
1012
1013            @Override
1014            public boolean enterTernaryNode(final TernaryNode ternaryNode) {
1015                loadTernaryNode(ternaryNode, resultBounds);
1016                return false;
1017            }
1018
1019            @Override
1020            public boolean enterADD(final BinaryNode binaryNode) {
1021                loadADD(binaryNode, resultBounds);
1022                return false;
1023            }
1024
1025            @Override
1026            public boolean enterSUB(final UnaryNode unaryNode) {
1027                loadSUB(unaryNode, resultBounds);
1028                return false;
1029            }
1030
1031            @Override
1032            public boolean enterSUB(final BinaryNode binaryNode) {
1033                loadSUB(binaryNode, resultBounds);
1034                return false;
1035            }
1036
1037            @Override
1038            public boolean enterMUL(final BinaryNode binaryNode) {
1039                loadMUL(binaryNode, resultBounds);
1040                return false;
1041            }
1042
1043            @Override
1044            public boolean enterDIV(final BinaryNode binaryNode) {
1045                loadDIV(binaryNode, resultBounds);
1046                return false;
1047            }
1048
1049            @Override
1050            public boolean enterMOD(final BinaryNode binaryNode) {
1051                loadMOD(binaryNode, resultBounds);
1052                return false;
1053            }
1054
1055            @Override
1056            public boolean enterSAR(final BinaryNode binaryNode) {
1057                loadSAR(binaryNode);
1058                return false;
1059            }
1060
1061            @Override
1062            public boolean enterSHL(final BinaryNode binaryNode) {
1063                loadSHL(binaryNode);
1064                return false;
1065            }
1066
1067            @Override
1068            public boolean enterSHR(final BinaryNode binaryNode) {
1069                loadSHR(binaryNode);
1070                return false;
1071            }
1072
1073            @Override
1074            public boolean enterCOMMALEFT(final BinaryNode binaryNode) {
1075                loadCOMMALEFT(binaryNode, resultBounds);
1076                return false;
1077            }
1078
1079            @Override
1080            public boolean enterCOMMARIGHT(final BinaryNode binaryNode) {
1081                loadCOMMARIGHT(binaryNode, resultBounds);
1082                return false;
1083            }
1084
1085            @Override
1086            public boolean enterAND(final BinaryNode binaryNode) {
1087                loadAND_OR(binaryNode, resultBounds, true);
1088                return false;
1089            }
1090
1091            @Override
1092            public boolean enterOR(final BinaryNode binaryNode) {
1093                loadAND_OR(binaryNode, resultBounds, false);
1094                return false;
1095            }
1096
1097            @Override
1098            public boolean enterNOT(final UnaryNode unaryNode) {
1099                loadNOT(unaryNode);
1100                return false;
1101            }
1102
1103            @Override
1104            public boolean enterADD(final UnaryNode unaryNode) {
1105                loadADD(unaryNode, resultBounds);
1106                return false;
1107            }
1108
1109            @Override
1110            public boolean enterBIT_NOT(final UnaryNode unaryNode) {
1111                loadBIT_NOT(unaryNode);
1112                return false;
1113            }
1114
1115            @Override
1116            public boolean enterBIT_AND(final BinaryNode binaryNode) {
1117                loadBIT_AND(binaryNode);
1118                return false;
1119            }
1120
1121            @Override
1122            public boolean enterBIT_OR(final BinaryNode binaryNode) {
1123                loadBIT_OR(binaryNode);
1124                return false;
1125            }
1126
1127            @Override
1128            public boolean enterBIT_XOR(final BinaryNode binaryNode) {
1129                loadBIT_XOR(binaryNode);
1130                return false;
1131            }
1132
1133            @Override
1134            public boolean enterVOID(final UnaryNode unaryNode) {
1135                loadVOID(unaryNode, resultBounds);
1136                return false;
1137            }
1138
1139            @Override
1140            public boolean enterEQ(final BinaryNode binaryNode) {
1141                loadCmp(binaryNode, Condition.EQ);
1142                return false;
1143            }
1144
1145            @Override
1146            public boolean enterEQ_STRICT(final BinaryNode binaryNode) {
1147                loadCmp(binaryNode, Condition.EQ);
1148                return false;
1149            }
1150
1151            @Override
1152            public boolean enterGE(final BinaryNode binaryNode) {
1153                loadCmp(binaryNode, Condition.GE);
1154                return false;
1155            }
1156
1157            @Override
1158            public boolean enterGT(final BinaryNode binaryNode) {
1159                loadCmp(binaryNode, Condition.GT);
1160                return false;
1161            }
1162
1163            @Override
1164            public boolean enterLE(final BinaryNode binaryNode) {
1165                loadCmp(binaryNode, Condition.LE);
1166                return false;
1167            }
1168
1169            @Override
1170            public boolean enterLT(final BinaryNode binaryNode) {
1171                loadCmp(binaryNode, Condition.LT);
1172                return false;
1173            }
1174
1175            @Override
1176            public boolean enterNE(final BinaryNode binaryNode) {
1177                loadCmp(binaryNode, Condition.NE);
1178                return false;
1179            }
1180
1181            @Override
1182            public boolean enterNE_STRICT(final BinaryNode binaryNode) {
1183                loadCmp(binaryNode, Condition.NE);
1184                return false;
1185            }
1186
1187            @Override
1188            public boolean enterObjectNode(final ObjectNode objectNode) {
1189                loadObjectNode(objectNode);
1190                return false;
1191            }
1192
1193            @Override
1194            public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
1195                loadRuntimeNode(runtimeNode);
1196                return false;
1197            }
1198
1199            @Override
1200            public boolean enterNEW(final UnaryNode unaryNode) {
1201                loadNEW(unaryNode);
1202                return false;
1203            }
1204
1205            @Override
1206            public boolean enterDECINC(final UnaryNode unaryNode) {
1207                checkAssignTarget(unaryNode.getExpression());
1208                loadDECINC(unaryNode);
1209                return false;
1210            }
1211
1212            @Override
1213            public boolean enterJoinPredecessorExpression(final JoinPredecessorExpression joinExpr) {
1214                loadMaybeDiscard(joinExpr, joinExpr.getExpression(), resultBounds);
1215                return false;
1216            }
1217
1218            @Override
1219            public boolean enterGetSplitState(final GetSplitState getSplitState) {
1220                method.loadScope();
1221                method.invoke(Scope.GET_SPLIT_STATE);
1222                return false;
1223            }
1224
1225            @Override
1226            public boolean enterDefault(final Node otherNode) {
1227                // Must have handled all expressions that can legally be encountered.
1228                throw new AssertionError(otherNode.getClass().getName());
1229            }
1230        });
1231        if(!isCurrentDiscard) {
1232            coerceStackTop(resultBounds);
1233        }
1234        return method;
1235    }
1236
1237    private MethodEmitter coerceStackTop(final TypeBounds typeBounds) {
1238        return method.convert(typeBounds.within(method.peekType()));
1239    }
1240
1241    /**
1242     * Closes any still open entries for this block's local variables in the bytecode local variable table.
1243     *
1244     * @param block block containing symbols.
1245     */
1246    private void closeBlockVariables(final Block block) {
1247        for (final Symbol symbol : block.getSymbols()) {
1248            if (symbol.isBytecodeLocal()) {
1249                method.closeLocalVariable(symbol, block.getBreakLabel());
1250            }
1251        }
1252    }
1253
1254    @Override
1255    public boolean enterBlock(final Block block) {
1256        final Label entryLabel = block.getEntryLabel();
1257        if (entryLabel.isBreakTarget()) {
1258            // Entry label is a break target only for an inlined finally block.
1259            assert !method.isReachable();
1260            method.breakLabel(entryLabel, lc.getUsedSlotCount());
1261        } else {
1262            method.label(entryLabel);
1263        }
1264        if(!method.isReachable()) {
1265            return false;
1266        }
1267        if(lc.isFunctionBody() && emittedMethods.contains(lc.getCurrentFunction().getName())) {
1268            return false;
1269        }
1270        initLocals(block);
1271
1272        assert lc.getUsedSlotCount() == method.getFirstTemp();
1273        return true;
1274    }
1275
1276    boolean useOptimisticTypes() {
1277        return !lc.inSplitNode() && compiler.useOptimisticTypes();
1278    }
1279
1280    @Override
1281    public Node leaveBlock(final Block block) {
1282        popBlockScope(block);
1283        method.beforeJoinPoint(block);
1284
1285        closeBlockVariables(block);
1286        lc.releaseSlots();
1287        assert !method.isReachable() || (lc.isFunctionBody() ? 0 : lc.getUsedSlotCount()) == method.getFirstTemp() :
1288            "reachable="+method.isReachable() +
1289            " isFunctionBody=" + lc.isFunctionBody() +
1290            " usedSlotCount=" + lc.getUsedSlotCount() +
1291            " firstTemp=" + method.getFirstTemp();
1292
1293        return block;
1294    }
1295
1296    private void popBlockScope(final Block block) {
1297        final Label breakLabel = block.getBreakLabel();
1298
1299        if(!block.needsScope() || lc.isFunctionBody()) {
1300            emitBlockBreakLabel(breakLabel);
1301            return;
1302        }
1303
1304        final Label beginTryLabel = scopeEntryLabels.pop();
1305        final Label recoveryLabel = new Label("block_popscope_catch");
1306        emitBlockBreakLabel(breakLabel);
1307        final boolean bodyCanThrow = breakLabel.isAfter(beginTryLabel);
1308        if(bodyCanThrow) {
1309            method._try(beginTryLabel, breakLabel, recoveryLabel);
1310        }
1311
1312        Label afterCatchLabel = null;
1313
1314        if(method.isReachable()) {
1315            popScope();
1316            if(bodyCanThrow) {
1317                afterCatchLabel = new Label("block_after_catch");
1318                method._goto(afterCatchLabel);
1319            }
1320        }
1321
1322        if(bodyCanThrow) {
1323            assert !method.isReachable();
1324            method._catch(recoveryLabel);
1325            popScopeException();
1326            method.athrow();
1327        }
1328        if(afterCatchLabel != null) {
1329            method.label(afterCatchLabel);
1330        }
1331    }
1332
1333    private void emitBlockBreakLabel(final Label breakLabel) {
1334        // TODO: this is totally backwards. Block should not be breakable, LabelNode should be breakable.
1335        final LabelNode labelNode = lc.getCurrentBlockLabelNode();
1336        if(labelNode != null) {
1337            // Only have conversions if we're reachable
1338            assert labelNode.getLocalVariableConversion() == null || method.isReachable();
1339            method.beforeJoinPoint(labelNode);
1340            method.breakLabel(breakLabel, labeledBlockBreakLiveLocals.pop());
1341        } else {
1342            method.label(breakLabel);
1343        }
1344    }
1345
1346    private void popScope() {
1347        popScopes(1);
1348    }
1349
1350    /**
1351     * Pop scope as part of an exception handler. Similar to {@code popScope()} but also takes care of adjusting the
1352     * number of scopes that needs to be popped in case a rest-of continuation handler encounters an exception while
1353     * performing a ToPrimitive conversion.
1354     */
1355    private void popScopeException() {
1356        popScope();
1357        final ContinuationInfo ci = getContinuationInfo();
1358        if(ci != null) {
1359            final Label catchLabel = ci.catchLabel;
1360            if(catchLabel != METHOD_BOUNDARY && catchLabel == catchLabels.peek()) {
1361                ++ci.exceptionScopePops;
1362            }
1363        }
1364    }
1365
1366    private void popScopesUntil(final LexicalContextNode until) {
1367        popScopes(lc.getScopeNestingLevelTo(until));
1368    }
1369
1370    private void popScopes(final int count) {
1371        if(count == 0) {
1372            return;
1373        }
1374        assert count > 0; // together with count == 0 check, asserts nonnegative count
1375        if (!method.hasScope()) {
1376            // We can sometimes invoke this method even if the method has no slot for the scope object. Typical example:
1377            // for(;;) { with({}) { break; } }. WithNode normally creates a scope, but if it uses no identifiers and
1378            // nothing else forces creation of a scope in the method, we just won't have the :scope local variable.
1379            return;
1380        }
1381        method.loadCompilerConstant(SCOPE);
1382        for(int i = 0; i < count; ++i) {
1383            method.invoke(ScriptObject.GET_PROTO);
1384        }
1385        method.storeCompilerConstant(SCOPE);
1386    }
1387
1388    @Override
1389    public boolean enterBreakNode(final BreakNode breakNode) {
1390        return enterJumpStatement(breakNode);
1391    }
1392
1393    @Override
1394    public boolean enterJumpToInlinedFinally(final JumpToInlinedFinally jumpToInlinedFinally) {
1395        return enterJumpStatement(jumpToInlinedFinally);
1396    }
1397
1398    private boolean enterJumpStatement(final JumpStatement jump) {
1399        if(!method.isReachable()) {
1400            return false;
1401        }
1402        enterStatement(jump);
1403
1404        method.beforeJoinPoint(jump);
1405        popScopesUntil(jump.getPopScopeLimit(lc));
1406        final Label targetLabel = jump.getTargetLabel(lc);
1407        targetLabel.markAsBreakTarget();
1408        method._goto(targetLabel);
1409
1410        return false;
1411    }
1412
1413    private int loadArgs(final List<Expression> args) {
1414        final int argCount = args.size();
1415        // arg have already been converted to objects here.
1416        if (argCount > LinkerCallSite.ARGLIMIT) {
1417            loadArgsArray(args);
1418            return 1;
1419        }
1420
1421        for (final Expression arg : args) {
1422            assert arg != null;
1423            loadExpressionUnbounded(arg);
1424        }
1425        return argCount;
1426    }
1427
1428    private boolean loadCallNode(final CallNode callNode, final TypeBounds resultBounds) {
1429        lineNumber(callNode.getLineNumber());
1430
1431        final List<Expression> args = callNode.getArgs();
1432        final Expression function = callNode.getFunction();
1433        final Block currentBlock = lc.getCurrentBlock();
1434        final CodeGeneratorLexicalContext codegenLexicalContext = lc;
1435
1436        function.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
1437
1438            private MethodEmitter sharedScopeCall(final IdentNode identNode, final int flags) {
1439                final Symbol symbol = identNode.getSymbol();
1440                final boolean isFastScope = isFastScope(symbol);
1441                new OptimisticOperation(callNode, resultBounds) {
1442                    @Override
1443                    void loadStack() {
1444                        method.loadCompilerConstant(SCOPE);
1445                        if (isFastScope) {
1446                            method.load(getScopeProtoDepth(currentBlock, symbol));
1447                        } else {
1448                            method.load(-1); // Bypass fast-scope code in shared callsite
1449                        }
1450                        loadArgs(args);
1451                    }
1452                    @Override
1453                    void consumeStack() {
1454                        final Type[] paramTypes = method.getTypesFromStack(args.size());
1455                        // We have trouble finding e.g. in Type.typeFor(asm.Type) because it can't see the Context class
1456                        // loader, so we need to weaken reference signatures to Object.
1457                        for(int i = 0; i < paramTypes.length; ++i) {
1458                            paramTypes[i] = Type.generic(paramTypes[i]);
1459                        }
1460                        // As shared scope calls are only used in non-optimistic compilation, we switch from using
1461                        // TypeBounds to just a single definitive type, resultBounds.widest.
1462                        final SharedScopeCall scopeCall = codegenLexicalContext.getScopeCall(unit, symbol,
1463                                identNode.getType(), resultBounds.widest, paramTypes, flags);
1464                        scopeCall.generateInvoke(method);
1465                    }
1466                }.emit();
1467                return method;
1468            }
1469
1470            private void scopeCall(final IdentNode ident, final int flags) {
1471                new OptimisticOperation(callNode, resultBounds) {
1472                    int argsCount;
1473                    @Override
1474                    void loadStack() {
1475                        loadExpressionAsObject(ident); // foo() makes no sense if foo == 3
1476                        // ScriptFunction will see CALLSITE_SCOPE and will bind scope accordingly.
1477                        method.loadUndefined(Type.OBJECT); //the 'this'
1478                        argsCount = loadArgs(args);
1479                    }
1480                    @Override
1481                    void consumeStack() {
1482                        dynamicCall(2 + argsCount, flags, ident.getName());
1483                    }
1484                }.emit();
1485            }
1486
1487            private void evalCall(final IdentNode ident, final int flags) {
1488                final Label invoke_direct_eval  = new Label("invoke_direct_eval");
1489                final Label is_not_eval  = new Label("is_not_eval");
1490                final Label eval_done = new Label("eval_done");
1491
1492                new OptimisticOperation(callNode, resultBounds) {
1493                    int argsCount;
1494                    @Override
1495                    void loadStack() {
1496                        /*
1497                         * We want to load 'eval' to check if it is indeed global builtin eval.
1498                         * If this eval call is inside a 'with' statement, dyn:getMethod|getProp|getElem
1499                         * would be generated if ident is a "isFunction". But, that would result in a
1500                         * bound function from WithObject. We don't want that as bound function as that
1501                         * won't be detected as builtin eval. So, we make ident as "not a function" which
1502                         * results in "dyn:getProp|getElem|getMethod" being generated and so WithObject
1503                         * would return unbounded eval function.
1504                         *
1505                         * Example:
1506                         *
1507                         *  var global = this;
1508                         *  function func() {
1509                         *      with({ eval: global.eval) { eval("var x = 10;") }
1510                         *  }
1511                         */
1512                        loadExpressionAsObject(ident.setIsNotFunction()); // Type.OBJECT as foo() makes no sense if foo == 3
1513                        globalIsEval();
1514                        method.ifeq(is_not_eval);
1515
1516                        // Load up self (scope).
1517                        method.loadCompilerConstant(SCOPE);
1518                        final List<Expression> evalArgs = callNode.getEvalArgs().getArgs();
1519                        // load evaluated code
1520                        loadExpressionAsObject(evalArgs.get(0));
1521                        // load second and subsequent args for side-effect
1522                        final int numArgs = evalArgs.size();
1523                        for (int i = 1; i < numArgs; i++) {
1524                            loadAndDiscard(evalArgs.get(i));
1525                        }
1526                        method._goto(invoke_direct_eval);
1527
1528                        method.label(is_not_eval);
1529                        // load this time but with dyn:getMethod|getProp|getElem
1530                        loadExpressionAsObject(ident); // Type.OBJECT as foo() makes no sense if foo == 3
1531                        // This is some scope 'eval' or global eval replaced by user
1532                        // but not the built-in ECMAScript 'eval' function call
1533                        method.loadNull();
1534                        argsCount = loadArgs(callNode.getArgs());
1535                    }
1536
1537                    @Override
1538                    void consumeStack() {
1539                        // Ordinary call
1540                        dynamicCall(2 + argsCount, flags, "eval");
1541                        method._goto(eval_done);
1542
1543                        method.label(invoke_direct_eval);
1544                        // Special/extra 'eval' arguments. These can be loaded late (in consumeStack) as we know none of
1545                        // them can ever be optimistic.
1546                        method.loadCompilerConstant(THIS);
1547                        method.load(callNode.getEvalArgs().getLocation());
1548                        method.load(CodeGenerator.this.lc.getCurrentFunction().isStrict());
1549                        // direct call to Global.directEval
1550                        globalDirectEval();
1551                        convertOptimisticReturnValue();
1552                        coerceStackTop(resultBounds);
1553                    }
1554                }.emit();
1555
1556                method.label(eval_done);
1557            }
1558
1559            @Override
1560            public boolean enterIdentNode(final IdentNode node) {
1561                final Symbol symbol = node.getSymbol();
1562
1563                if (symbol.isScope()) {
1564                    final int flags = getScopeCallSiteFlags(symbol);
1565                    final int useCount = symbol.getUseCount();
1566
1567                    // Threshold for generating shared scope callsite is lower for fast scope symbols because we know
1568                    // we can dial in the correct scope. However, we also need to enable it for non-fast scopes to
1569                    // support huge scripts like mandreel.js.
1570                    if (callNode.isEval()) {
1571                        evalCall(node, flags);
1572                    } else if (useCount <= SharedScopeCall.FAST_SCOPE_CALL_THRESHOLD
1573                            || !isFastScope(symbol) && useCount <= SharedScopeCall.SLOW_SCOPE_CALL_THRESHOLD
1574                            || CodeGenerator.this.lc.inDynamicScope()
1575                            || callNode.isOptimistic()) {
1576                        scopeCall(node, flags);
1577                    } else {
1578                        sharedScopeCall(node, flags);
1579                    }
1580                    assert method.peekType().equals(resultBounds.within(callNode.getType())) : method.peekType() + " != " + resultBounds + "(" + callNode.getType() + ")";
1581                } else {
1582                    enterDefault(node);
1583                }
1584
1585                return false;
1586            }
1587
1588            @Override
1589            public boolean enterAccessNode(final AccessNode node) {
1590                //check if this is an apply to call node. only real applies, that haven't been
1591                //shadowed from their way to the global scope counts
1592
1593                //call nodes have program points.
1594
1595                final int flags = getCallSiteFlags() | (callNode.isApplyToCall() ? CALLSITE_APPLY_TO_CALL : 0);
1596
1597                new OptimisticOperation(callNode, resultBounds) {
1598                    int argCount;
1599                    @Override
1600                    void loadStack() {
1601                        loadExpressionAsObject(node.getBase());
1602                        method.dup();
1603                        // NOTE: not using a nested OptimisticOperation on this dynamicGet, as we expect to get back
1604                        // a callable object. Nobody in their right mind would optimistically type this call site.
1605                        assert !node.isOptimistic();
1606                        method.dynamicGet(node.getType(), node.getProperty(), flags, true, node.isIndex());
1607                        method.swap();
1608                        argCount = loadArgs(args);
1609                    }
1610                    @Override
1611                    void consumeStack() {
1612                        dynamicCall(2 + argCount, flags, node.toString(false));
1613                    }
1614                }.emit();
1615
1616                return false;
1617            }
1618
1619            @Override
1620            public boolean enterFunctionNode(final FunctionNode origCallee) {
1621                new OptimisticOperation(callNode, resultBounds) {
1622                    FunctionNode callee;
1623                    int argsCount;
1624                    @Override
1625                    void loadStack() {
1626                        callee = (FunctionNode)origCallee.accept(CodeGenerator.this);
1627                        if (callee.isStrict()) { // "this" is undefined
1628                            method.loadUndefined(Type.OBJECT);
1629                        } else { // get global from scope (which is the self)
1630                            globalInstance();
1631                        }
1632                        argsCount = loadArgs(args);
1633                    }
1634
1635                    @Override
1636                    void consumeStack() {
1637                        dynamicCall(2 + argsCount, getCallSiteFlags(), null);
1638                    }
1639                }.emit();
1640                return false;
1641            }
1642
1643            @Override
1644            public boolean enterIndexNode(final IndexNode node) {
1645                new OptimisticOperation(callNode, resultBounds) {
1646                    int argsCount;
1647                    @Override
1648                    void loadStack() {
1649                        loadExpressionAsObject(node.getBase());
1650                        method.dup();
1651                        final Type indexType = node.getIndex().getType();
1652                        if (indexType.isObject() || indexType.isBoolean()) {
1653                            loadExpressionAsObject(node.getIndex()); //TODO boolean
1654                        } else {
1655                            loadExpressionUnbounded(node.getIndex());
1656                        }
1657                        // NOTE: not using a nested OptimisticOperation on this dynamicGetIndex, as we expect to get
1658                        // back a callable object. Nobody in their right mind would optimistically type this call site.
1659                        assert !node.isOptimistic();
1660                        method.dynamicGetIndex(node.getType(), getCallSiteFlags(), true);
1661                        method.swap();
1662                        argsCount = loadArgs(args);
1663                    }
1664                    @Override
1665                    void consumeStack() {
1666                        dynamicCall(2 + argsCount, getCallSiteFlags(), node.toString(false));
1667                    }
1668                }.emit();
1669                return false;
1670            }
1671
1672            @Override
1673            protected boolean enterDefault(final Node node) {
1674                new OptimisticOperation(callNode, resultBounds) {
1675                    int argsCount;
1676                    @Override
1677                    void loadStack() {
1678                        // Load up function.
1679                        loadExpressionAsObject(function); //TODO, e.g. booleans can be used as functions
1680                        method.loadUndefined(Type.OBJECT); // ScriptFunction will figure out the correct this when it sees CALLSITE_SCOPE
1681                        argsCount = loadArgs(args);
1682                        }
1683                        @Override
1684                        void consumeStack() {
1685                            final int flags = getCallSiteFlags() | CALLSITE_SCOPE;
1686                            dynamicCall(2 + argsCount, flags, node.toString(false));
1687                        }
1688                }.emit();
1689                return false;
1690            }
1691        });
1692
1693        return false;
1694    }
1695
1696    /**
1697     * Returns the flags with optimistic flag and program point removed.
1698     * @param flags the flags that need optimism stripped from them.
1699     * @return flags without optimism
1700     */
1701    static int nonOptimisticFlags(final int flags) {
1702        return flags & ~(CALLSITE_OPTIMISTIC | -1 << CALLSITE_PROGRAM_POINT_SHIFT);
1703    }
1704
1705    @Override
1706    public boolean enterContinueNode(final ContinueNode continueNode) {
1707        return enterJumpStatement(continueNode);
1708    }
1709
1710    @Override
1711    public boolean enterEmptyNode(final EmptyNode emptyNode) {
1712        // Don't even record the line number, it's irrelevant as there's no code.
1713        return false;
1714    }
1715
1716    @Override
1717    public boolean enterExpressionStatement(final ExpressionStatement expressionStatement) {
1718        if(!method.isReachable()) {
1719            return false;
1720        }
1721        enterStatement(expressionStatement);
1722
1723        loadAndDiscard(expressionStatement.getExpression());
1724        assert method.getStackSize() == 0;
1725
1726        return false;
1727    }
1728
1729    @Override
1730    public boolean enterBlockStatement(final BlockStatement blockStatement) {
1731        if(!method.isReachable()) {
1732            return false;
1733        }
1734        enterStatement(blockStatement);
1735
1736        blockStatement.getBlock().accept(this);
1737
1738        return false;
1739    }
1740
1741    @Override
1742    public boolean enterForNode(final ForNode forNode) {
1743        if(!method.isReachable()) {
1744            return false;
1745        }
1746        enterStatement(forNode);
1747        if (forNode.isForIn()) {
1748            enterForIn(forNode);
1749        } else {
1750            final Expression init = forNode.getInit();
1751            if (init != null) {
1752                loadAndDiscard(init);
1753            }
1754            enterForOrWhile(forNode, forNode.getModify());
1755        }
1756
1757        return false;
1758    }
1759
1760    private void enterForIn(final ForNode forNode) {
1761        loadExpression(forNode.getModify(), TypeBounds.OBJECT);
1762        method.invoke(forNode.isForEach() ? ScriptRuntime.TO_VALUE_ITERATOR : ScriptRuntime.TO_PROPERTY_ITERATOR);
1763        final Symbol iterSymbol = forNode.getIterator();
1764        final int iterSlot = iterSymbol.getSlot(Type.OBJECT);
1765        method.store(iterSymbol, ITERATOR_TYPE);
1766
1767        method.beforeJoinPoint(forNode);
1768
1769        final Label continueLabel = forNode.getContinueLabel();
1770        final Label breakLabel    = forNode.getBreakLabel();
1771
1772        method.label(continueLabel);
1773        method.load(ITERATOR_TYPE, iterSlot);
1774        method.invoke(interfaceCallNoLookup(ITERATOR_CLASS, "hasNext", boolean.class));
1775        final JoinPredecessorExpression test = forNode.getTest();
1776        final Block body = forNode.getBody();
1777        if(LocalVariableConversion.hasLiveConversion(test)) {
1778            final Label afterConversion = new Label("for_in_after_test_conv");
1779            method.ifne(afterConversion);
1780            method.beforeJoinPoint(test);
1781            method._goto(breakLabel);
1782            method.label(afterConversion);
1783        } else {
1784            method.ifeq(breakLabel);
1785        }
1786
1787        new Store<Expression>(forNode.getInit()) {
1788            @Override
1789            protected void storeNonDiscard() {
1790                // This expression is neither part of a discard, nor needs to be left on the stack after it was
1791                // stored, so we override storeNonDiscard to be a no-op.
1792            }
1793
1794            @Override
1795            protected void evaluate() {
1796                new OptimisticOperation((Optimistic)forNode.getInit(), TypeBounds.UNBOUNDED) {
1797                    @Override
1798                    void loadStack() {
1799                        method.load(ITERATOR_TYPE, iterSlot);
1800                    }
1801
1802                    @Override
1803                    void consumeStack() {
1804                        method.invoke(interfaceCallNoLookup(ITERATOR_CLASS, "next", Object.class));
1805                        convertOptimisticReturnValue();
1806                    }
1807                }.emit();
1808            }
1809        }.store();
1810        body.accept(this);
1811
1812        if(method.isReachable()) {
1813            method._goto(continueLabel);
1814        }
1815        method.label(breakLabel);
1816    }
1817
1818    /**
1819     * Initialize the slots in a frame to undefined.
1820     *
1821     * @param block block with local vars.
1822     */
1823    private void initLocals(final Block block) {
1824        lc.onEnterBlock(block);
1825
1826        final boolean isFunctionBody = lc.isFunctionBody();
1827        final FunctionNode function = lc.getCurrentFunction();
1828        if (isFunctionBody) {
1829            initializeMethodParameters(function);
1830            if(!function.isVarArg()) {
1831                expandParameterSlots(function);
1832            }
1833            if (method.hasScope()) {
1834                if (function.needsParentScope()) {
1835                    method.loadCompilerConstant(CALLEE);
1836                    method.invoke(ScriptFunction.GET_SCOPE);
1837                } else {
1838                    assert function.hasScopeBlock();
1839                    method.loadNull();
1840                }
1841                method.storeCompilerConstant(SCOPE);
1842            }
1843            if (function.needsArguments()) {
1844                initArguments(function);
1845            }
1846        }
1847
1848        /*
1849         * Determine if block needs scope, if not, just do initSymbols for this block.
1850         */
1851        if (block.needsScope()) {
1852            /*
1853             * Determine if function is varargs and consequently variables have to
1854             * be in the scope.
1855             */
1856            final boolean varsInScope = function.allVarsInScope();
1857
1858            // TODO for LET we can do better: if *block* does not contain any eval/with, we don't need its vars in scope.
1859
1860            final boolean hasArguments = function.needsArguments();
1861            final List<MapTuple<Symbol>> tuples = new ArrayList<>();
1862            final Iterator<IdentNode> paramIter = function.getParameters().iterator();
1863            for (final Symbol symbol : block.getSymbols()) {
1864                if (symbol.isInternal() || symbol.isThis()) {
1865                    continue;
1866                }
1867
1868                if (symbol.isVar()) {
1869                    assert !varsInScope || symbol.isScope();
1870                    if (varsInScope || symbol.isScope()) {
1871                        assert symbol.isScope()   : "scope for " + symbol + " should have been set in Lower already " + function.getName();
1872                        assert !symbol.hasSlot()  : "slot for " + symbol + " should have been removed in Lower already" + function.getName();
1873
1874                        //this tuple will not be put fielded, as it has no value, just a symbol
1875                        tuples.add(new MapTuple<Symbol>(symbol.getName(), symbol, null));
1876                    } else {
1877                        assert symbol.hasSlot() || symbol.slotCount() == 0 : symbol + " should have a slot only, no scope";
1878                    }
1879                } else if (symbol.isParam() && (varsInScope || hasArguments || symbol.isScope())) {
1880                    assert symbol.isScope()   : "scope for " + symbol + " should have been set in AssignSymbols already " + function.getName() + " varsInScope="+varsInScope+" hasArguments="+hasArguments+" symbol.isScope()=" + symbol.isScope();
1881                    assert !(hasArguments && symbol.hasSlot())  : "slot for " + symbol + " should have been removed in Lower already " + function.getName();
1882
1883                    final Type   paramType;
1884                    final Symbol paramSymbol;
1885
1886                    if (hasArguments) {
1887                        assert !symbol.hasSlot()  : "slot for " + symbol + " should have been removed in Lower already ";
1888                        paramSymbol = null;
1889                        paramType   = null;
1890                    } else {
1891                        paramSymbol = symbol;
1892                        // NOTE: We're relying on the fact here that Block.symbols is a LinkedHashMap, hence it will
1893                        // return symbols in the order they were defined, and parameters are defined in the same order
1894                        // they appear in the function. That's why we can have a single pass over the parameter list
1895                        // with an iterator, always just scanning forward for the next parameter that matches the symbol
1896                        // name.
1897                        for(;;) {
1898                            final IdentNode nextParam = paramIter.next();
1899                            if(nextParam.getName().equals(symbol.getName())) {
1900                                paramType = nextParam.getType();
1901                                break;
1902                            }
1903                        }
1904                    }
1905
1906                    tuples.add(new MapTuple<Symbol>(symbol.getName(), symbol, paramType, paramSymbol) {
1907                        //this symbol will be put fielded, we can't initialize it as undefined with a known type
1908                        @Override
1909                        public Class<?> getValueType() {
1910                            if (!useDualFields() ||  value == null || paramType == null || paramType.isBoolean()) {
1911                                return Object.class;
1912                            }
1913                            return paramType.getTypeClass();
1914                        }
1915                    });
1916                }
1917            }
1918
1919            /*
1920             * Create a new object based on the symbols and values, generate
1921             * bootstrap code for object
1922             */
1923            new FieldObjectCreator<Symbol>(this, tuples, true, hasArguments) {
1924                @Override
1925                protected void loadValue(final Symbol value, final Type type) {
1926                    method.load(value, type);
1927                }
1928            }.makeObject(method);
1929            // program function: merge scope into global
1930            if (isFunctionBody && function.isProgram()) {
1931                method.invoke(ScriptRuntime.MERGE_SCOPE);
1932            }
1933
1934            method.storeCompilerConstant(SCOPE);
1935            if(!isFunctionBody) {
1936                // Function body doesn't need a try/catch to restore scope, as it'd be a dead store anyway. Allowing it
1937                // actually causes issues with UnwarrantedOptimismException handlers as ASM will sort this handler to
1938                // the top of the exception handler table, so it'll be triggered instead of the UOE handlers.
1939                final Label scopeEntryLabel = new Label("scope_entry");
1940                scopeEntryLabels.push(scopeEntryLabel);
1941                method.label(scopeEntryLabel);
1942            }
1943        } else if (isFunctionBody && function.isVarArg()) {
1944            // Since we don't have a scope, parameters didn't get assigned array indices by the FieldObjectCreator, so
1945            // we need to assign them separately here.
1946            int nextParam = 0;
1947            for (final IdentNode param : function.getParameters()) {
1948                param.getSymbol().setFieldIndex(nextParam++);
1949            }
1950        }
1951
1952        // Debugging: print symbols? @see --print-symbols flag
1953        printSymbols(block, function, (isFunctionBody ? "Function " : "Block in ") + (function.getIdent() == null ? "<anonymous>" : function.getIdent().getName()));
1954    }
1955
1956    /**
1957     * Incoming method parameters are always declared on method entry; declare them in the local variable table.
1958     * @param function function for which code is being generated.
1959     */
1960    private void initializeMethodParameters(final FunctionNode function) {
1961        final Label functionStart = new Label("fn_start");
1962        method.label(functionStart);
1963        int nextSlot = 0;
1964        if(function.needsCallee()) {
1965            initializeInternalFunctionParameter(CALLEE, function, functionStart, nextSlot++);
1966        }
1967        initializeInternalFunctionParameter(THIS, function, functionStart, nextSlot++);
1968        if(function.isVarArg()) {
1969            initializeInternalFunctionParameter(VARARGS, function, functionStart, nextSlot++);
1970        } else {
1971            for(final IdentNode param: function.getParameters()) {
1972                final Symbol symbol = param.getSymbol();
1973                if(symbol.isBytecodeLocal()) {
1974                    method.initializeMethodParameter(symbol, param.getType(), functionStart);
1975                }
1976            }
1977        }
1978    }
1979
1980    private void initializeInternalFunctionParameter(final CompilerConstants cc, final FunctionNode fn, final Label functionStart, final int slot) {
1981        final Symbol symbol = initializeInternalFunctionOrSplitParameter(cc, fn, functionStart, slot);
1982        // Internal function params (:callee, this, and :varargs) are never expanded to multiple slots
1983        assert symbol.getFirstSlot() == slot;
1984    }
1985
1986    private Symbol initializeInternalFunctionOrSplitParameter(final CompilerConstants cc, final FunctionNode fn, final Label functionStart, final int slot) {
1987        final Symbol symbol = fn.getBody().getExistingSymbol(cc.symbolName());
1988        final Type type = Type.typeFor(cc.type());
1989        method.initializeMethodParameter(symbol, type, functionStart);
1990        method.onLocalStore(type, slot);
1991        return symbol;
1992    }
1993
1994    /**
1995     * Parameters come into the method packed into local variable slots next to each other. Nashorn on the other hand
1996     * can use 1-6 slots for a local variable depending on all the types it needs to store. When this method is invoked,
1997     * the symbols are already allocated such wider slots, but the values are still in tightly packed incoming slots,
1998     * and we need to spread them into their new locations.
1999     * @param function the function for which parameter-spreading code needs to be emitted
2000     */
2001    private void expandParameterSlots(final FunctionNode function) {
2002        final List<IdentNode> parameters = function.getParameters();
2003        // Calculate the total number of incoming parameter slots
2004        int currentIncomingSlot = function.needsCallee() ? 2 : 1;
2005        for(final IdentNode parameter: parameters) {
2006            currentIncomingSlot += parameter.getType().getSlots();
2007        }
2008        // Starting from last parameter going backwards, move the parameter values into their new slots.
2009        for(int i = parameters.size(); i-- > 0;) {
2010            final IdentNode parameter = parameters.get(i);
2011            final Type parameterType = parameter.getType();
2012            final int typeWidth = parameterType.getSlots();
2013            currentIncomingSlot -= typeWidth;
2014            final Symbol symbol = parameter.getSymbol();
2015            final int slotCount = symbol.slotCount();
2016            assert slotCount > 0;
2017            // Scoped parameters must not hold more than one value
2018            assert symbol.isBytecodeLocal() || slotCount == typeWidth;
2019
2020            // Mark it as having its value stored into it by the method invocation.
2021            method.onLocalStore(parameterType, currentIncomingSlot);
2022            if(currentIncomingSlot != symbol.getSlot(parameterType)) {
2023                method.load(parameterType, currentIncomingSlot);
2024                method.store(symbol, parameterType);
2025            }
2026        }
2027    }
2028
2029    private void initArguments(final FunctionNode function) {
2030        method.loadCompilerConstant(VARARGS);
2031        if (function.needsCallee()) {
2032            method.loadCompilerConstant(CALLEE);
2033        } else {
2034            // If function is strict mode, "arguments.callee" is not populated, so we don't necessarily need the
2035            // caller.
2036            assert function.isStrict();
2037            method.loadNull();
2038        }
2039        method.load(function.getParameters().size());
2040        globalAllocateArguments();
2041        method.storeCompilerConstant(ARGUMENTS);
2042    }
2043
2044    private boolean skipFunction(final FunctionNode functionNode) {
2045        final ScriptEnvironment env = compiler.getScriptEnvironment();
2046        final boolean lazy = env._lazy_compilation;
2047        final boolean onDemand = compiler.isOnDemandCompilation();
2048
2049        // If this is on-demand or lazy compilation, don't compile a nested (not topmost) function.
2050        if((onDemand || lazy) && lc.getOutermostFunction() != functionNode) {
2051            return true;
2052        }
2053
2054        // If lazy compiling with optimistic types, don't compile the program eagerly either. It will soon be
2055        // invalidated anyway. In presence of a class cache, this further means that an obsoleted program version
2056        // lingers around. Also, currently loading previously persisted optimistic types information only works if
2057        // we're on-demand compiling a function, so with this strategy the :program method can also have the warmup
2058        // benefit of using previously persisted types.
2059        //
2060        // NOTE that this means the first compiled class will effectively just have a :createProgramFunction method, and
2061        // the RecompilableScriptFunctionData (RSFD) object in its constants array. It won't even have the :program
2062        // method. This is by design. It does mean that we're wasting one compiler execution (and we could minimize this
2063        // by just running it up to scope depth calculation, which creates the RSFDs and then this limited codegen).
2064        // We could emit an initial separate compile unit with the initial version of :program in it to better utilize
2065        // the compilation pipeline, but that would need more invasive changes, as currently the assumption that
2066        // :program is emitted into the first compilation unit of the function lives in many places.
2067        return !onDemand && lazy && env._optimistic_types && functionNode.isProgram();
2068    }
2069
2070    @Override
2071    public boolean enterFunctionNode(final FunctionNode functionNode) {
2072        if (skipFunction(functionNode)) {
2073            // In case we are not generating code for the function, we must create or retrieve the function object and
2074            // load it on the stack here.
2075            newFunctionObject(functionNode, false);
2076            return false;
2077        }
2078
2079        final String fnName = functionNode.getName();
2080
2081        // NOTE: we only emit the method for a function with the given name once. We can have multiple functions with
2082        // the same name as a result of inlining finally blocks. However, in the future -- with type specialization,
2083        // notably -- we might need to check for both name *and* signature. Of course, even that might not be
2084        // sufficient; the function might have a code dependency on the type of the variables in its enclosing scopes,
2085        // and the type of such a variable can be different in catch and finally blocks. So, in the future we will have
2086        // to decide to either generate a unique method for each inlined copy of the function, maybe figure out its
2087        // exact type closure and deduplicate based on that, or just decide that functions in finally blocks aren't
2088        // worth it, and generate one method with most generic type closure.
2089        if (!emittedMethods.contains(fnName)) {
2090            log.info("=== BEGIN ", fnName);
2091
2092            assert functionNode.getCompileUnit() != null : "no compile unit for " + fnName + " " + Debug.id(functionNode);
2093            unit = lc.pushCompileUnit(functionNode.getCompileUnit());
2094            assert lc.hasCompileUnits();
2095
2096            final ClassEmitter classEmitter = unit.getClassEmitter();
2097            pushMethodEmitter(isRestOf() ? classEmitter.restOfMethod(functionNode) : classEmitter.method(functionNode));
2098            method.setPreventUndefinedLoad();
2099            if(useOptimisticTypes()) {
2100                lc.pushUnwarrantedOptimismHandlers();
2101            }
2102
2103            // new method - reset last line number
2104            lastLineNumber = -1;
2105
2106            method.begin();
2107
2108            if (isRestOf()) {
2109                assert continuationInfo == null;
2110                continuationInfo = new ContinuationInfo();
2111                method.gotoLoopStart(continuationInfo.getHandlerLabel());
2112            }
2113        }
2114
2115        return true;
2116    }
2117
2118    private void pushMethodEmitter(final MethodEmitter newMethod) {
2119        method = lc.pushMethodEmitter(newMethod);
2120        catchLabels.push(METHOD_BOUNDARY);
2121    }
2122
2123    private void popMethodEmitter() {
2124        method = lc.popMethodEmitter(method);
2125        assert catchLabels.peek() == METHOD_BOUNDARY;
2126        catchLabels.pop();
2127    }
2128
2129    @Override
2130    public Node leaveFunctionNode(final FunctionNode functionNode) {
2131        try {
2132            final boolean markOptimistic;
2133            if (emittedMethods.add(functionNode.getName())) {
2134                markOptimistic = generateUnwarrantedOptimismExceptionHandlers(functionNode);
2135                generateContinuationHandler();
2136                method.end(); // wrap up this method
2137                unit   = lc.popCompileUnit(functionNode.getCompileUnit());
2138                popMethodEmitter();
2139                log.info("=== END ", functionNode.getName());
2140            } else {
2141                markOptimistic = false;
2142            }
2143
2144            FunctionNode newFunctionNode = functionNode;
2145            if (markOptimistic) {
2146                newFunctionNode = newFunctionNode.setFlag(lc, FunctionNode.IS_DEOPTIMIZABLE);
2147            }
2148
2149            newFunctionObject(newFunctionNode, true);
2150            return newFunctionNode;
2151        } catch (final Throwable t) {
2152            Context.printStackTrace(t);
2153            final VerifyError e = new VerifyError("Code generation bug in \"" + functionNode.getName() + "\": likely stack misaligned: " + t + " " + functionNode.getSource().getName());
2154            e.initCause(t);
2155            throw e;
2156        }
2157    }
2158
2159    @Override
2160    public boolean enterIfNode(final IfNode ifNode) {
2161        if(!method.isReachable()) {
2162            return false;
2163        }
2164        enterStatement(ifNode);
2165
2166        final Expression test = ifNode.getTest();
2167        final Block pass = ifNode.getPass();
2168        final Block fail = ifNode.getFail();
2169
2170        if (Expression.isAlwaysTrue(test)) {
2171            loadAndDiscard(test);
2172            pass.accept(this);
2173            return false;
2174        } else if (Expression.isAlwaysFalse(test)) {
2175            loadAndDiscard(test);
2176            if (fail != null) {
2177                fail.accept(this);
2178            }
2179            return false;
2180        }
2181
2182        final boolean hasFailConversion = LocalVariableConversion.hasLiveConversion(ifNode);
2183
2184        final Label failLabel  = new Label("if_fail");
2185        final Label afterLabel = (fail == null && !hasFailConversion) ? null : new Label("if_done");
2186
2187        emitBranch(test, failLabel, false);
2188
2189        pass.accept(this);
2190        if(method.isReachable() && afterLabel != null) {
2191            method._goto(afterLabel); //don't fallthru to fail block
2192        }
2193        method.label(failLabel);
2194
2195        if (fail != null) {
2196            fail.accept(this);
2197        } else if(hasFailConversion) {
2198            method.beforeJoinPoint(ifNode);
2199        }
2200
2201        if(afterLabel != null && afterLabel.isReachable()) {
2202            method.label(afterLabel);
2203        }
2204
2205        return false;
2206    }
2207
2208    private void emitBranch(final Expression test, final Label label, final boolean jumpWhenTrue) {
2209        new BranchOptimizer(this, method).execute(test, label, jumpWhenTrue);
2210    }
2211
2212    private void enterStatement(final Statement statement) {
2213        lineNumber(statement);
2214    }
2215
2216    private void lineNumber(final Statement statement) {
2217        lineNumber(statement.getLineNumber());
2218    }
2219
2220    private void lineNumber(final int lineNumber) {
2221        if (lineNumber != lastLineNumber && lineNumber != Node.NO_LINE_NUMBER) {
2222            method.lineNumber(lineNumber);
2223            lastLineNumber = lineNumber;
2224        }
2225    }
2226
2227    int getLastLineNumber() {
2228        return lastLineNumber;
2229    }
2230
2231    /**
2232     * Load a list of nodes as an array of a specific type
2233     * The array will contain the visited nodes.
2234     *
2235     * @param arrayLiteralNode the array of contents
2236     * @param arrayType        the type of the array, e.g. ARRAY_NUMBER or ARRAY_OBJECT
2237     */
2238    private void loadArray(final ArrayLiteralNode arrayLiteralNode, final ArrayType arrayType) {
2239        assert arrayType == Type.INT_ARRAY || arrayType == Type.LONG_ARRAY || arrayType == Type.NUMBER_ARRAY || arrayType == Type.OBJECT_ARRAY;
2240
2241        final Expression[]     nodes    = arrayLiteralNode.getValue();
2242        final Object           presets  = arrayLiteralNode.getPresets();
2243        final int[]            postsets = arrayLiteralNode.getPostsets();
2244        final List<Splittable.SplitRange> ranges   = arrayLiteralNode.getSplitRanges();
2245
2246        loadConstant(presets);
2247
2248        final Type elementType = arrayType.getElementType();
2249
2250        if (ranges != null) {
2251
2252            loadSplitLiteral(new SplitLiteralCreator() {
2253                @Override
2254                public void populateRange(final MethodEmitter method, final Type type, final int slot, final int start, final int end) {
2255                    for (int i = start; i < end; i++) {
2256                        method.load(type, slot);
2257                        storeElement(nodes, elementType, postsets[i]);
2258                    }
2259                    method.load(type, slot);
2260                }
2261            }, ranges, arrayType);
2262
2263            return;
2264        }
2265
2266        if(postsets.length > 0) {
2267            final int arraySlot = method.getUsedSlotsWithLiveTemporaries();
2268            method.storeTemp(arrayType, arraySlot);
2269            for (final int postset : postsets) {
2270                method.load(arrayType, arraySlot);
2271                storeElement(nodes, elementType, postset);
2272            }
2273            method.load(arrayType, arraySlot);
2274        }
2275    }
2276
2277    private void storeElement(final Expression[] nodes, final Type elementType, final int index) {
2278        method.load(index);
2279
2280        final Expression element = nodes[index];
2281
2282        if (element == null) {
2283            method.loadEmpty(elementType);
2284        } else {
2285            loadExpressionAsType(element, elementType);
2286        }
2287
2288        method.arraystore();
2289    }
2290
2291    private MethodEmitter loadArgsArray(final List<Expression> args) {
2292        final Object[] array = new Object[args.size()];
2293        loadConstant(array);
2294
2295        for (int i = 0; i < args.size(); i++) {
2296            method.dup();
2297            method.load(i);
2298            loadExpression(args.get(i), TypeBounds.OBJECT); // variable arity methods always take objects
2299            method.arraystore();
2300        }
2301
2302        return method;
2303    }
2304
2305    /**
2306     * Load a constant from the constant array. This is only public to be callable from the objects
2307     * subpackage. Do not call directly.
2308     *
2309     * @param string string to load
2310     */
2311    void loadConstant(final String string) {
2312        final String       unitClassName = unit.getUnitClassName();
2313        final ClassEmitter classEmitter  = unit.getClassEmitter();
2314        final int          index         = compiler.getConstantData().add(string);
2315
2316        method.load(index);
2317        method.invokestatic(unitClassName, GET_STRING.symbolName(), methodDescriptor(String.class, int.class));
2318        classEmitter.needGetConstantMethod(String.class);
2319    }
2320
2321    /**
2322     * Load a constant from the constant array. This is only public to be callable from the objects
2323     * subpackage. Do not call directly.
2324     *
2325     * @param object object to load
2326     */
2327    void loadConstant(final Object object) {
2328        loadConstant(object, unit, method);
2329    }
2330
2331    private void loadConstant(final Object object, final CompileUnit compileUnit, final MethodEmitter methodEmitter) {
2332        final String       unitClassName = compileUnit.getUnitClassName();
2333        final ClassEmitter classEmitter  = compileUnit.getClassEmitter();
2334        final int          index         = compiler.getConstantData().add(object);
2335        final Class<?>     cls           = object.getClass();
2336
2337        if (cls == PropertyMap.class) {
2338            methodEmitter.load(index);
2339            methodEmitter.invokestatic(unitClassName, GET_MAP.symbolName(), methodDescriptor(PropertyMap.class, int.class));
2340            classEmitter.needGetConstantMethod(PropertyMap.class);
2341        } else if (cls.isArray()) {
2342            methodEmitter.load(index);
2343            final String methodName = ClassEmitter.getArrayMethodName(cls);
2344            methodEmitter.invokestatic(unitClassName, methodName, methodDescriptor(cls, int.class));
2345            classEmitter.needGetConstantMethod(cls);
2346        } else {
2347            methodEmitter.loadConstants().load(index).arrayload();
2348            if (object instanceof ArrayData) {
2349                methodEmitter.checkcast(ArrayData.class);
2350                methodEmitter.invoke(virtualCallNoLookup(ArrayData.class, "copy", ArrayData.class));
2351            } else if (cls != Object.class) {
2352                methodEmitter.checkcast(cls);
2353            }
2354        }
2355    }
2356
2357    private void loadConstantsAndIndex(final Object object, final MethodEmitter methodEmitter) {
2358        methodEmitter.loadConstants().load(compiler.getConstantData().add(object));
2359    }
2360
2361    // literal values
2362    private void loadLiteral(final LiteralNode<?> node, final TypeBounds resultBounds) {
2363        final Object value = node.getValue();
2364
2365        if (value == null) {
2366            method.loadNull();
2367        } else if (value instanceof Undefined) {
2368            method.loadUndefined(resultBounds.within(Type.OBJECT));
2369        } else if (value instanceof String) {
2370            final String string = (String)value;
2371
2372            if (string.length() > MethodEmitter.LARGE_STRING_THRESHOLD / 3) { // 3 == max bytes per encoded char
2373                loadConstant(string);
2374            } else {
2375                method.load(string);
2376            }
2377        } else if (value instanceof RegexToken) {
2378            loadRegex((RegexToken)value);
2379        } else if (value instanceof Boolean) {
2380            method.load((Boolean)value);
2381        } else if (value instanceof Integer) {
2382            if(!resultBounds.canBeNarrowerThan(Type.OBJECT)) {
2383                method.load((Integer)value);
2384                method.convert(Type.OBJECT);
2385            } else if(!resultBounds.canBeNarrowerThan(Type.NUMBER)) {
2386                method.load(((Integer)value).doubleValue());
2387            } else if(!resultBounds.canBeNarrowerThan(Type.LONG)) {
2388                method.load(((Integer)value).longValue());
2389            } else {
2390                method.load((Integer)value);
2391            }
2392        } else if (value instanceof Long) {
2393            if(!resultBounds.canBeNarrowerThan(Type.OBJECT)) {
2394                method.load((Long)value);
2395                method.convert(Type.OBJECT);
2396            } else if(!resultBounds.canBeNarrowerThan(Type.NUMBER)) {
2397                method.load(((Long)value).doubleValue());
2398            } else {
2399                method.load((Long)value);
2400            }
2401        } else if (value instanceof Double) {
2402            if(!resultBounds.canBeNarrowerThan(Type.OBJECT)) {
2403                method.load((Double)value);
2404                method.convert(Type.OBJECT);
2405            } else {
2406                method.load((Double)value);
2407            }
2408        } else if (node instanceof ArrayLiteralNode) {
2409            final ArrayLiteralNode arrayLiteral = (ArrayLiteralNode)node;
2410            final ArrayType atype = arrayLiteral.getArrayType();
2411            loadArray(arrayLiteral, atype);
2412            globalAllocateArray(atype);
2413        } else {
2414            throw new UnsupportedOperationException("Unknown literal for " + node.getClass() + " " + value.getClass() + " " + value);
2415        }
2416    }
2417
2418    private MethodEmitter loadRegexToken(final RegexToken value) {
2419        method.load(value.getExpression());
2420        method.load(value.getOptions());
2421        return globalNewRegExp();
2422    }
2423
2424    private MethodEmitter loadRegex(final RegexToken regexToken) {
2425        if (regexFieldCount > MAX_REGEX_FIELDS) {
2426            return loadRegexToken(regexToken);
2427        }
2428        // emit field
2429        final String       regexName    = lc.getCurrentFunction().uniqueName(REGEX_PREFIX.symbolName());
2430        final ClassEmitter classEmitter = unit.getClassEmitter();
2431
2432        classEmitter.field(EnumSet.of(PRIVATE, STATIC), regexName, Object.class);
2433        regexFieldCount++;
2434
2435        // get field, if null create new regex, finally clone regex object
2436        method.getStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
2437        method.dup();
2438        final Label cachedLabel = new Label("cached");
2439        method.ifnonnull(cachedLabel);
2440
2441        method.pop();
2442        loadRegexToken(regexToken);
2443        method.dup();
2444        method.putStatic(unit.getUnitClassName(), regexName, typeDescriptor(Object.class));
2445
2446        method.label(cachedLabel);
2447        globalRegExpCopy();
2448
2449        return method;
2450    }
2451
2452    /**
2453     * Check if a property value contains a particular program point
2454     * @param value value
2455     * @param pp    program point
2456     * @return true if it's there.
2457     */
2458    private static boolean propertyValueContains(final Expression value, final int pp) {
2459        return new Supplier<Boolean>() {
2460            boolean contains;
2461
2462            @Override
2463            public Boolean get() {
2464                value.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
2465                    @Override
2466                    public boolean enterFunctionNode(final FunctionNode functionNode) {
2467                        return false;
2468                    }
2469
2470                    @Override
2471                    public boolean enterObjectNode(final ObjectNode objectNode) {
2472                        return false;
2473                    }
2474
2475                    @Override
2476                    public boolean enterDefault(final Node node) {
2477                        if (contains) {
2478                            return false;
2479                        }
2480                        if (node instanceof Optimistic && ((Optimistic)node).getProgramPoint() == pp) {
2481                            contains = true;
2482                            return false;
2483                        }
2484                        return true;
2485                    }
2486                });
2487
2488                return contains;
2489            }
2490        }.get();
2491    }
2492
2493    private void loadObjectNode(final ObjectNode objectNode) {
2494        final List<PropertyNode> elements = objectNode.getElements();
2495
2496        final List<MapTuple<Expression>> tuples = new ArrayList<>();
2497        final List<PropertyNode> gettersSetters = new ArrayList<>();
2498        final int ccp = getCurrentContinuationEntryPoint();
2499        final List<Splittable.SplitRange> ranges = objectNode.getSplitRanges();
2500
2501        Expression protoNode = null;
2502        boolean restOfProperty = false;
2503
2504        for (final PropertyNode propertyNode : elements) {
2505            final Expression value = propertyNode.getValue();
2506            final String key = propertyNode.getKeyName();
2507            // Just use a pseudo-symbol. We just need something non null; use the name and zero flags.
2508            final Symbol symbol = value == null ? null : new Symbol(key, 0);
2509
2510            if (value == null) {
2511                gettersSetters.add(propertyNode);
2512            } else if (propertyNode.getKey() instanceof IdentNode &&
2513                       key.equals(ScriptObject.PROTO_PROPERTY_NAME)) {
2514                // ES6 draft compliant __proto__ inside object literal
2515                // Identifier key and name is __proto__
2516                protoNode = value;
2517                continue;
2518            }
2519
2520            restOfProperty |=
2521                value != null &&
2522                isValid(ccp) &&
2523                propertyValueContains(value, ccp);
2524
2525            //for literals, a value of null means object type, i.e. the value null or getter setter function
2526            //(I think)
2527            final Class<?> valueType = (!useDualFields() || value == null || value.getType().isBoolean()) ? Object.class : value.getType().getTypeClass();
2528            tuples.add(new MapTuple<Expression>(key, symbol, Type.typeFor(valueType), value) {
2529                @Override
2530                public Class<?> getValueType() {
2531                    return type.getTypeClass();
2532                }
2533            });
2534        }
2535
2536        final ObjectCreator<?> oc;
2537        if (elements.size() > OBJECT_SPILL_THRESHOLD) {
2538            oc = new SpillObjectCreator(this, tuples);
2539        } else {
2540            oc = new FieldObjectCreator<Expression>(this, tuples) {
2541                @Override
2542                protected void loadValue(final Expression node, final Type type) {
2543                    loadExpressionAsType(node, type);
2544                }};
2545        }
2546
2547        if (ranges != null) {
2548            oc.createObject(method);
2549            loadSplitLiteral(oc, ranges, Type.typeFor(oc.getAllocatorClass()));
2550        } else {
2551            oc.makeObject(method);
2552        }
2553
2554        //if this is a rest of method and our continuation point was found as one of the values
2555        //in the properties above, we need to reset the map to oc.getMap() in the continuation
2556        //handler
2557        if (restOfProperty) {
2558            final ContinuationInfo ci = getContinuationInfo();
2559            // Can be set at most once for a single rest-of method
2560            assert ci.getObjectLiteralMap() == null;
2561            ci.setObjectLiteralMap(oc.getMap());
2562            ci.setObjectLiteralStackDepth(method.getStackSize());
2563        }
2564
2565        method.dup();
2566        if (protoNode != null) {
2567            loadExpressionAsObject(protoNode);
2568            // take care of { __proto__: 34 } or some such!
2569            method.convert(Type.OBJECT);
2570            method.invoke(ScriptObject.SET_PROTO_FROM_LITERAL);
2571        } else {
2572            method.invoke(ScriptObject.SET_GLOBAL_OBJECT_PROTO);
2573        }
2574
2575        for (final PropertyNode propertyNode : gettersSetters) {
2576            final FunctionNode getter = propertyNode.getGetter();
2577            final FunctionNode setter = propertyNode.getSetter();
2578
2579            assert getter != null || setter != null;
2580
2581            method.dup().loadKey(propertyNode.getKey());
2582            if (getter == null) {
2583                method.loadNull();
2584            } else {
2585                getter.accept(this);
2586            }
2587
2588            if (setter == null) {
2589                method.loadNull();
2590            } else {
2591                setter.accept(this);
2592            }
2593
2594            method.invoke(ScriptObject.SET_USER_ACCESSORS);
2595        }
2596    }
2597
2598    @Override
2599    public boolean enterReturnNode(final ReturnNode returnNode) {
2600        if(!method.isReachable()) {
2601            return false;
2602        }
2603        enterStatement(returnNode);
2604
2605        final Type returnType = lc.getCurrentFunction().getReturnType();
2606
2607        final Expression expression = returnNode.getExpression();
2608        if (expression != null) {
2609            loadExpressionUnbounded(expression);
2610        } else {
2611            method.loadUndefined(returnType);
2612        }
2613
2614        method._return(returnType);
2615
2616        return false;
2617    }
2618
2619    private boolean undefinedCheck(final RuntimeNode runtimeNode, final List<Expression> args) {
2620        final Request request = runtimeNode.getRequest();
2621
2622        if (!Request.isUndefinedCheck(request)) {
2623            return false;
2624        }
2625
2626        final Expression lhs = args.get(0);
2627        final Expression rhs = args.get(1);
2628
2629        final Symbol lhsSymbol = lhs instanceof IdentNode ? ((IdentNode)lhs).getSymbol() : null;
2630        final Symbol rhsSymbol = rhs instanceof IdentNode ? ((IdentNode)rhs).getSymbol() : null;
2631        // One must be a "undefined" identifier, otherwise we can't get here
2632        assert lhsSymbol != null || rhsSymbol != null;
2633
2634        final Symbol undefinedSymbol;
2635        if (isUndefinedSymbol(lhsSymbol)) {
2636            undefinedSymbol = lhsSymbol;
2637        } else {
2638            assert isUndefinedSymbol(rhsSymbol);
2639            undefinedSymbol = rhsSymbol;
2640        }
2641
2642        assert undefinedSymbol != null; //remove warning
2643        if (!undefinedSymbol.isScope()) {
2644            return false; //disallow undefined as local var or parameter
2645        }
2646
2647        if (lhsSymbol == undefinedSymbol && lhs.getType().isPrimitive()) {
2648            //we load the undefined first. never mind, because this will deoptimize anyway
2649            return false;
2650        }
2651
2652        if(isDeoptimizedExpression(lhs)) {
2653            // This is actually related to "lhs.getType().isPrimitive()" above: any expression being deoptimized in
2654            // the current chain of rest-of compilations used to have a type narrower than Object (so it was primitive).
2655            // We must not perform undefined check specialization for them, as then we'd violate the basic rule of
2656            // "Thou shalt not alter the stack shape between a deoptimized method and any of its (transitive) rest-ofs."
2657            return false;
2658        }
2659
2660        //make sure that undefined has not been overridden or scoped as a local var
2661        //between us and global
2662        if (!compiler.isGlobalSymbol(lc.getCurrentFunction(), "undefined")) {
2663            return false;
2664        }
2665
2666        final boolean isUndefinedCheck = request == Request.IS_UNDEFINED;
2667        final Expression expr = undefinedSymbol == lhsSymbol ? rhs : lhs;
2668        if (expr.getType().isPrimitive()) {
2669            loadAndDiscard(expr); //throw away lhs, but it still needs to be evaluated for side effects, even if not in scope, as it can be optimistic
2670            method.load(!isUndefinedCheck);
2671        } else {
2672            final Label checkTrue  = new Label("ud_check_true");
2673            final Label end        = new Label("end");
2674            loadExpressionAsObject(expr);
2675            method.loadUndefined(Type.OBJECT);
2676            method.if_acmpeq(checkTrue);
2677            method.load(!isUndefinedCheck);
2678            method._goto(end);
2679            method.label(checkTrue);
2680            method.load(isUndefinedCheck);
2681            method.label(end);
2682        }
2683
2684        return true;
2685    }
2686
2687    private static boolean isUndefinedSymbol(final Symbol symbol) {
2688        return symbol != null && "undefined".equals(symbol.getName());
2689    }
2690
2691    private static boolean isNullLiteral(final Node node) {
2692        return node instanceof LiteralNode<?> && ((LiteralNode<?>) node).isNull();
2693    }
2694
2695    private boolean nullCheck(final RuntimeNode runtimeNode, final List<Expression> args) {
2696        final Request request = runtimeNode.getRequest();
2697
2698        if (!Request.isEQ(request) && !Request.isNE(request)) {
2699            return false;
2700        }
2701
2702        assert args.size() == 2 : "EQ or NE or TYPEOF need two args";
2703
2704        Expression lhs = args.get(0);
2705        Expression rhs = args.get(1);
2706
2707        if (isNullLiteral(lhs)) {
2708            final Expression tmp = lhs;
2709            lhs = rhs;
2710            rhs = tmp;
2711        }
2712
2713        if (!isNullLiteral(rhs)) {
2714            return false;
2715        }
2716
2717        if (!lhs.getType().isObject()) {
2718            return false;
2719        }
2720
2721        if(isDeoptimizedExpression(lhs)) {
2722            // This is actually related to "!lhs.getType().isObject()" above: any expression being deoptimized in
2723            // the current chain of rest-of compilations used to have a type narrower than Object. We must not
2724            // perform null check specialization for them, as then we'd no longer be loading aconst_null on stack
2725            // and thus violate the basic rule of "Thou shalt not alter the stack shape between a deoptimized
2726            // method and any of its (transitive) rest-ofs."
2727            // NOTE also that if we had a representation for well-known constants (e.g. null, 0, 1, -1, etc.) in
2728            // Label$Stack.localLoads then this wouldn't be an issue, as we would never (somewhat ridiculously)
2729            // allocate a temporary local to hold the result of aconst_null before attempting an optimistic
2730            // operation.
2731            return false;
2732        }
2733
2734        // this is a null literal check, so if there is implicit coercion
2735        // involved like {D}x=null, we will fail - this is very rare
2736        final Label trueLabel  = new Label("trueLabel");
2737        final Label falseLabel = new Label("falseLabel");
2738        final Label endLabel   = new Label("end");
2739
2740        loadExpressionUnbounded(lhs);    //lhs
2741        final Label popLabel;
2742        if (!Request.isStrict(request)) {
2743            method.dup(); //lhs lhs
2744            popLabel = new Label("pop");
2745        } else {
2746            popLabel = null;
2747        }
2748
2749        if (Request.isEQ(request)) {
2750            method.ifnull(!Request.isStrict(request) ? popLabel : trueLabel);
2751            if (!Request.isStrict(request)) {
2752                method.loadUndefined(Type.OBJECT);
2753                method.if_acmpeq(trueLabel);
2754            }
2755            method.label(falseLabel);
2756            method.load(false);
2757            method._goto(endLabel);
2758            if (!Request.isStrict(request)) {
2759                method.label(popLabel);
2760                method.pop();
2761            }
2762            method.label(trueLabel);
2763            method.load(true);
2764            method.label(endLabel);
2765        } else if (Request.isNE(request)) {
2766            method.ifnull(!Request.isStrict(request) ? popLabel : falseLabel);
2767            if (!Request.isStrict(request)) {
2768                method.loadUndefined(Type.OBJECT);
2769                method.if_acmpeq(falseLabel);
2770            }
2771            method.label(trueLabel);
2772            method.load(true);
2773            method._goto(endLabel);
2774            if (!Request.isStrict(request)) {
2775                method.label(popLabel);
2776                method.pop();
2777            }
2778            method.label(falseLabel);
2779            method.load(false);
2780            method.label(endLabel);
2781        }
2782
2783        assert runtimeNode.getType().isBoolean();
2784        method.convert(runtimeNode.getType());
2785
2786        return true;
2787    }
2788
2789    /**
2790     * Was this expression or any of its subexpressions deoptimized in the current recompilation chain of rest-of methods?
2791     * @param rootExpr the expression being tested
2792     * @return true if the expression or any of its subexpressions was deoptimized in the current recompilation chain.
2793     */
2794    private boolean isDeoptimizedExpression(final Expression rootExpr) {
2795        if(!isRestOf()) {
2796            return false;
2797        }
2798        return new Supplier<Boolean>() {
2799            boolean contains;
2800            @Override
2801            public Boolean get() {
2802                rootExpr.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
2803                    @Override
2804                    public boolean enterFunctionNode(final FunctionNode functionNode) {
2805                        return false;
2806                    }
2807                    @Override
2808                    public boolean enterDefault(final Node node) {
2809                        if(!contains && node instanceof Optimistic) {
2810                            final int pp = ((Optimistic)node).getProgramPoint();
2811                            contains = isValid(pp) && isContinuationEntryPoint(pp);
2812                        }
2813                        return !contains;
2814                    }
2815                });
2816                return contains;
2817            }
2818        }.get();
2819    }
2820
2821    private void loadRuntimeNode(final RuntimeNode runtimeNode) {
2822        final List<Expression> args = new ArrayList<>(runtimeNode.getArgs());
2823        if (nullCheck(runtimeNode, args)) {
2824           return;
2825        } else if(undefinedCheck(runtimeNode, args)) {
2826            return;
2827        }
2828        // Revert a false undefined check to a strict equality check
2829        final RuntimeNode newRuntimeNode;
2830        final Request request = runtimeNode.getRequest();
2831        if (Request.isUndefinedCheck(request)) {
2832            newRuntimeNode = runtimeNode.setRequest(request == Request.IS_UNDEFINED ? Request.EQ_STRICT : Request.NE_STRICT);
2833        } else {
2834            newRuntimeNode = runtimeNode;
2835        }
2836
2837        for (final Expression arg : args) {
2838            loadExpression(arg, TypeBounds.OBJECT);
2839        }
2840
2841        method.invokestatic(
2842                CompilerConstants.className(ScriptRuntime.class),
2843                newRuntimeNode.getRequest().toString(),
2844                new FunctionSignature(
2845                    false,
2846                    false,
2847                    newRuntimeNode.getType(),
2848                    args.size()).toString());
2849
2850        method.convert(newRuntimeNode.getType());
2851    }
2852
2853    private void defineCommonSplitMethodParameters() {
2854        defineSplitMethodParameter(0, CALLEE);
2855        defineSplitMethodParameter(1, THIS);
2856        defineSplitMethodParameter(2, SCOPE);
2857    }
2858
2859    private void defineSplitMethodParameter(final int slot, final CompilerConstants cc) {
2860        defineSplitMethodParameter(slot, Type.typeFor(cc.type()));
2861    }
2862
2863    private void defineSplitMethodParameter(final int slot, final Type type) {
2864        method.defineBlockLocalVariable(slot, slot + type.getSlots());
2865        method.onLocalStore(type, slot);
2866    }
2867
2868    private void loadSplitLiteral(final SplitLiteralCreator creator, final List<Splittable.SplitRange> ranges, final Type literalType) {
2869        assert ranges != null;
2870
2871        // final Type literalType = Type.typeFor(literalClass);
2872        final MethodEmitter savedMethod     = method;
2873        final FunctionNode  currentFunction = lc.getCurrentFunction();
2874
2875        for (final Splittable.SplitRange splitRange : ranges) {
2876            unit = lc.pushCompileUnit(splitRange.getCompileUnit());
2877
2878            assert unit != null;
2879            final String className = unit.getUnitClassName();
2880            final String name      = currentFunction.uniqueName(SPLIT_PREFIX.symbolName());
2881            final Class<?> clazz   = literalType.getTypeClass();
2882            final String signature = methodDescriptor(clazz, ScriptFunction.class, Object.class, ScriptObject.class, clazz);
2883
2884            pushMethodEmitter(unit.getClassEmitter().method(EnumSet.of(Flag.PUBLIC, Flag.STATIC), name, signature));
2885
2886            method.setFunctionNode(currentFunction);
2887            method.begin();
2888
2889            defineCommonSplitMethodParameters();
2890            defineSplitMethodParameter(CompilerConstants.SPLIT_ARRAY_ARG.slot(), literalType);
2891
2892            // NOTE: when this is no longer needed, SplitIntoFunctions will no longer have to add IS_SPLIT
2893            // to synthetic functions, and FunctionNode.needsCallee() will no longer need to test for isSplit().
2894            final int literalSlot = fixScopeSlot(currentFunction, 3);
2895
2896            lc.enterSplitNode();
2897
2898            creator.populateRange(method, literalType, literalSlot, splitRange.getLow(), splitRange.getHigh());
2899
2900            method._return();
2901            lc.exitSplitNode();
2902            method.end();
2903            lc.releaseSlots();
2904            popMethodEmitter();
2905
2906            assert method == savedMethod;
2907            method.loadCompilerConstant(CALLEE).swap();
2908            method.loadCompilerConstant(THIS).swap();
2909            method.loadCompilerConstant(SCOPE).swap();
2910            method.invokestatic(className, name, signature);
2911
2912            unit = lc.popCompileUnit(unit);
2913        }
2914    }
2915
2916    private int fixScopeSlot(final FunctionNode functionNode, final int extraSlot) {
2917        // TODO hack to move the scope to the expected slot (needed because split methods reuse the same slots as the root method)
2918        final int actualScopeSlot = functionNode.compilerConstant(SCOPE).getSlot(SCOPE_TYPE);
2919        final int defaultScopeSlot = SCOPE.slot();
2920        int newExtraSlot = extraSlot;
2921        if (actualScopeSlot != defaultScopeSlot) {
2922            if (actualScopeSlot == extraSlot) {
2923                newExtraSlot = extraSlot + 1;
2924                method.defineBlockLocalVariable(newExtraSlot, newExtraSlot + 1);
2925                method.load(Type.OBJECT, extraSlot);
2926                method.storeHidden(Type.OBJECT, newExtraSlot);
2927            } else {
2928                method.defineBlockLocalVariable(actualScopeSlot, actualScopeSlot + 1);
2929            }
2930            method.load(SCOPE_TYPE, defaultScopeSlot);
2931            method.storeCompilerConstant(SCOPE);
2932        }
2933        return newExtraSlot;
2934    }
2935
2936    @Override
2937    public boolean enterSplitReturn(final SplitReturn splitReturn) {
2938        if (method.isReachable()) {
2939            method.loadUndefined(lc.getCurrentFunction().getReturnType())._return();
2940        }
2941        return false;
2942    }
2943
2944    @Override
2945    public boolean enterSetSplitState(final SetSplitState setSplitState) {
2946        if (method.isReachable()) {
2947            method.setSplitState(setSplitState.getState());
2948        }
2949        return false;
2950    }
2951
2952    @Override
2953    public boolean enterSwitchNode(final SwitchNode switchNode) {
2954        if(!method.isReachable()) {
2955            return false;
2956        }
2957        enterStatement(switchNode);
2958
2959        final Expression     expression  = switchNode.getExpression();
2960        final List<CaseNode> cases       = switchNode.getCases();
2961
2962        if (cases.isEmpty()) {
2963            // still evaluate expression for side-effects.
2964            loadAndDiscard(expression);
2965            return false;
2966        }
2967
2968        final CaseNode defaultCase       = switchNode.getDefaultCase();
2969        final Label    breakLabel        = switchNode.getBreakLabel();
2970        final int      liveLocalsOnBreak = method.getUsedSlotsWithLiveTemporaries();
2971
2972        if (defaultCase != null && cases.size() == 1) {
2973            // default case only
2974            assert cases.get(0) == defaultCase;
2975            loadAndDiscard(expression);
2976            defaultCase.getBody().accept(this);
2977            method.breakLabel(breakLabel, liveLocalsOnBreak);
2978            return false;
2979        }
2980
2981        // NOTE: it can still change in the tableswitch/lookupswitch case if there's no default case
2982        // but we need to add a synthetic default case for local variable conversions
2983        Label defaultLabel = defaultCase != null ? defaultCase.getEntry() : breakLabel;
2984        final boolean hasSkipConversion = LocalVariableConversion.hasLiveConversion(switchNode);
2985
2986        if (switchNode.isUniqueInteger()) {
2987            // Tree for sorting values.
2988            final TreeMap<Integer, Label> tree = new TreeMap<>();
2989
2990            // Build up sorted tree.
2991            for (final CaseNode caseNode : cases) {
2992                final Node test = caseNode.getTest();
2993
2994                if (test != null) {
2995                    final Integer value = (Integer)((LiteralNode<?>)test).getValue();
2996                    final Label   entry = caseNode.getEntry();
2997
2998                    // Take first duplicate.
2999                    if (!tree.containsKey(value)) {
3000                        tree.put(value, entry);
3001                    }
3002                }
3003            }
3004
3005            // Copy values and labels to arrays.
3006            final int       size   = tree.size();
3007            final Integer[] values = tree.keySet().toArray(new Integer[size]);
3008            final Label[]   labels = tree.values().toArray(new Label[size]);
3009
3010            // Discern low, high and range.
3011            final int lo    = values[0];
3012            final int hi    = values[size - 1];
3013            final long range = (long)hi - (long)lo + 1;
3014
3015            // Find an unused value for default.
3016            int deflt = Integer.MIN_VALUE;
3017            for (final int value : values) {
3018                if (deflt == value) {
3019                    deflt++;
3020                } else if (deflt < value) {
3021                    break;
3022                }
3023            }
3024
3025            // Load switch expression.
3026            loadExpressionUnbounded(expression);
3027            final Type type = expression.getType();
3028
3029            // If expression not int see if we can convert, if not use deflt to trigger default.
3030            if (!type.isInteger()) {
3031                method.load(deflt);
3032                final Class<?> exprClass = type.getTypeClass();
3033                method.invoke(staticCallNoLookup(ScriptRuntime.class, "switchTagAsInt", int.class, exprClass.isPrimitive()? exprClass : Object.class, int.class));
3034            }
3035
3036            if(hasSkipConversion) {
3037                assert defaultLabel == breakLabel;
3038                defaultLabel = new Label("switch_skip");
3039            }
3040            // TABLESWITCH needs (range + 3) 32-bit values; LOOKUPSWITCH needs ((size * 2) + 2). Choose the one with
3041            // smaller representation, favor TABLESWITCH when they're equal size.
3042            if (range + 1 <= (size * 2) && range <= Integer.MAX_VALUE) {
3043                final Label[] table = new Label[(int)range];
3044                Arrays.fill(table, defaultLabel);
3045                for (int i = 0; i < size; i++) {
3046                    final int value = values[i];
3047                    table[value - lo] = labels[i];
3048                }
3049
3050                method.tableswitch(lo, hi, defaultLabel, table);
3051            } else {
3052                final int[] ints = new int[size];
3053                for (int i = 0; i < size; i++) {
3054                    ints[i] = values[i];
3055                }
3056
3057                method.lookupswitch(defaultLabel, ints, labels);
3058            }
3059            // This is a synthetic "default case" used in absence of actual default case, created if we need to apply
3060            // local variable conversions if neither case is taken.
3061            if(hasSkipConversion) {
3062                method.label(defaultLabel);
3063                method.beforeJoinPoint(switchNode);
3064                method._goto(breakLabel);
3065            }
3066        } else {
3067            final Symbol tagSymbol = switchNode.getTag();
3068            // TODO: we could have non-object tag
3069            final int tagSlot = tagSymbol.getSlot(Type.OBJECT);
3070            loadExpressionAsObject(expression);
3071            method.store(tagSymbol, Type.OBJECT);
3072
3073            for (final CaseNode caseNode : cases) {
3074                final Expression test = caseNode.getTest();
3075
3076                if (test != null) {
3077                    method.load(Type.OBJECT, tagSlot);
3078                    loadExpressionAsObject(test);
3079                    method.invoke(ScriptRuntime.EQ_STRICT);
3080                    method.ifne(caseNode.getEntry());
3081                }
3082            }
3083
3084            if (defaultCase != null) {
3085                method._goto(defaultLabel);
3086            } else {
3087                method.beforeJoinPoint(switchNode);
3088                method._goto(breakLabel);
3089            }
3090        }
3091
3092        // First case is only reachable through jump
3093        assert !method.isReachable();
3094
3095        for (final CaseNode caseNode : cases) {
3096            final Label fallThroughLabel;
3097            if(caseNode.getLocalVariableConversion() != null && method.isReachable()) {
3098                fallThroughLabel = new Label("fallthrough");
3099                method._goto(fallThroughLabel);
3100            } else {
3101                fallThroughLabel = null;
3102            }
3103            method.label(caseNode.getEntry());
3104            method.beforeJoinPoint(caseNode);
3105            if(fallThroughLabel != null) {
3106                method.label(fallThroughLabel);
3107            }
3108            caseNode.getBody().accept(this);
3109        }
3110
3111        method.breakLabel(breakLabel, liveLocalsOnBreak);
3112
3113        return false;
3114    }
3115
3116    @Override
3117    public boolean enterThrowNode(final ThrowNode throwNode) {
3118        if(!method.isReachable()) {
3119            return false;
3120        }
3121        enterStatement(throwNode);
3122
3123        if (throwNode.isSyntheticRethrow()) {
3124            method.beforeJoinPoint(throwNode);
3125
3126            //do not wrap whatever this is in an ecma exception, just rethrow it
3127            final IdentNode exceptionExpr = (IdentNode)throwNode.getExpression();
3128            final Symbol exceptionSymbol = exceptionExpr.getSymbol();
3129            method.load(exceptionSymbol, EXCEPTION_TYPE);
3130            method.checkcast(EXCEPTION_TYPE.getTypeClass());
3131            method.athrow();
3132            return false;
3133        }
3134
3135        final Source     source     = getCurrentSource();
3136        final Expression expression = throwNode.getExpression();
3137        final int        position   = throwNode.position();
3138        final int        line       = throwNode.getLineNumber();
3139        final int        column     = source.getColumn(position);
3140
3141        // NOTE: we first evaluate the expression, and only after it was evaluated do we create the new ECMAException
3142        // object and then somewhat cumbersomely move it beneath the evaluated expression on the stack. The reason for
3143        // this is that if expression is optimistic (or contains an optimistic subexpression), we'd potentially access
3144        // the not-yet-<init>ialized object on the stack from the UnwarrantedOptimismException handler, and bytecode
3145        // verifier forbids that.
3146        loadExpressionAsObject(expression);
3147
3148        method.load(source.getName());
3149        method.load(line);
3150        method.load(column);
3151        method.invoke(ECMAException.CREATE);
3152
3153        method.beforeJoinPoint(throwNode);
3154        method.athrow();
3155
3156        return false;
3157    }
3158
3159    private Source getCurrentSource() {
3160        return lc.getCurrentFunction().getSource();
3161    }
3162
3163    @Override
3164    public boolean enterTryNode(final TryNode tryNode) {
3165        if(!method.isReachable()) {
3166            return false;
3167        }
3168        enterStatement(tryNode);
3169
3170        final Block       body        = tryNode.getBody();
3171        final List<Block> catchBlocks = tryNode.getCatchBlocks();
3172        final Symbol      vmException = tryNode.getException();
3173        final Label       entry       = new Label("try");
3174        final Label       recovery    = new Label("catch");
3175        final Label       exit        = new Label("end_try");
3176        final Label       skip        = new Label("skip");
3177
3178        method.canThrow(recovery);
3179        // Effect any conversions that might be observed at the entry of the catch node before entering the try node.
3180        // This is because even the first instruction in the try block must be presumed to be able to transfer control
3181        // to the catch block. Note that this doesn't kill the original values; in this regard it works a lot like
3182        // conversions of assignments within the try block.
3183        method.beforeTry(tryNode, recovery);
3184        method.label(entry);
3185        catchLabels.push(recovery);
3186        try {
3187            body.accept(this);
3188        } finally {
3189            assert catchLabels.peek() == recovery;
3190            catchLabels.pop();
3191        }
3192
3193        method.label(exit);
3194        final boolean bodyCanThrow = exit.isAfter(entry);
3195        if(!bodyCanThrow) {
3196            // The body can't throw an exception; don't even bother emitting the catch handlers, they're all dead code.
3197            return false;
3198        }
3199
3200        method._try(entry, exit, recovery, Throwable.class);
3201
3202        if (method.isReachable()) {
3203            method._goto(skip);
3204        }
3205
3206        for (final Block inlinedFinally : tryNode.getInlinedFinallies()) {
3207            TryNode.getLabelledInlinedFinallyBlock(inlinedFinally).accept(this);
3208            // All inlined finallies end with a jump or a return
3209            assert !method.isReachable();
3210        }
3211
3212
3213        method._catch(recovery);
3214        method.store(vmException, EXCEPTION_TYPE);
3215
3216        final int catchBlockCount = catchBlocks.size();
3217        final Label afterCatch = new Label("after_catch");
3218        for (int i = 0; i < catchBlockCount; i++) {
3219            assert method.isReachable();
3220            final Block catchBlock = catchBlocks.get(i);
3221
3222            // Because of the peculiarities of the flow control, we need to use an explicit push/enterBlock/leaveBlock
3223            // here.
3224            lc.push(catchBlock);
3225            enterBlock(catchBlock);
3226
3227            final CatchNode  catchNode          = (CatchNode)catchBlocks.get(i).getStatements().get(0);
3228            final IdentNode  exception          = catchNode.getException();
3229            final Expression exceptionCondition = catchNode.getExceptionCondition();
3230            final Block      catchBody          = catchNode.getBody();
3231
3232            new Store<IdentNode>(exception) {
3233                @Override
3234                protected void storeNonDiscard() {
3235                    // This expression is neither part of a discard, nor needs to be left on the stack after it was
3236                    // stored, so we override storeNonDiscard to be a no-op.
3237                }
3238
3239                @Override
3240                protected void evaluate() {
3241                    if (catchNode.isSyntheticRethrow()) {
3242                        method.load(vmException, EXCEPTION_TYPE);
3243                        return;
3244                    }
3245                    /*
3246                     * If caught object is an instance of ECMAException, then
3247                     * bind obj.thrown to the script catch var. Or else bind the
3248                     * caught object itself to the script catch var.
3249                     */
3250                    final Label notEcmaException = new Label("no_ecma_exception");
3251                    method.load(vmException, EXCEPTION_TYPE).dup()._instanceof(ECMAException.class).ifeq(notEcmaException);
3252                    method.checkcast(ECMAException.class); //TODO is this necessary?
3253                    method.getField(ECMAException.THROWN);
3254                    method.label(notEcmaException);
3255                }
3256            }.store();
3257
3258            final boolean isConditionalCatch = exceptionCondition != null;
3259            final Label nextCatch;
3260            if (isConditionalCatch) {
3261                loadExpressionAsBoolean(exceptionCondition);
3262                nextCatch = new Label("next_catch");
3263                nextCatch.markAsBreakTarget();
3264                method.ifeq(nextCatch);
3265            } else {
3266                nextCatch = null;
3267            }
3268
3269            catchBody.accept(this);
3270            leaveBlock(catchBlock);
3271            lc.pop(catchBlock);
3272            if(nextCatch != null) {
3273                if(method.isReachable()) {
3274                    method._goto(afterCatch);
3275                }
3276                method.breakLabel(nextCatch, lc.getUsedSlotCount());
3277            }
3278        }
3279
3280        // afterCatch could be the same as skip, except that we need to establish that the vmException is dead.
3281        method.label(afterCatch);
3282        if(method.isReachable()) {
3283            method.markDeadLocalVariable(vmException);
3284        }
3285        method.label(skip);
3286
3287        // Finally body is always inlined elsewhere so it doesn't need to be emitted
3288        assert tryNode.getFinallyBody() == null;
3289
3290        return false;
3291    }
3292
3293    @Override
3294    public boolean enterVarNode(final VarNode varNode) {
3295        if(!method.isReachable()) {
3296            return false;
3297        }
3298        final Expression init = varNode.getInit();
3299        final IdentNode identNode = varNode.getName();
3300        final Symbol identSymbol = identNode.getSymbol();
3301        assert identSymbol != null : "variable node " + varNode + " requires a name with a symbol";
3302        final boolean needsScope = identSymbol.isScope();
3303
3304        if (init == null) {
3305            if (needsScope && varNode.isBlockScoped()) {
3306                // block scoped variables need a DECLARE flag to signal end of temporal dead zone (TDZ)
3307                method.loadCompilerConstant(SCOPE);
3308                method.loadUndefined(Type.OBJECT);
3309                final int flags = getScopeCallSiteFlags(identSymbol) | (varNode.isBlockScoped() ? CALLSITE_DECLARE : 0);
3310                assert isFastScope(identSymbol);
3311                storeFastScopeVar(identSymbol, flags);
3312            }
3313            return false;
3314        }
3315
3316        enterStatement(varNode);
3317        assert method != null;
3318
3319        if (needsScope) {
3320            method.loadCompilerConstant(SCOPE);
3321        }
3322
3323        if (needsScope) {
3324            loadExpressionUnbounded(init);
3325            // block scoped variables need a DECLARE flag to signal end of temporal dead zone (TDZ)
3326            final int flags = getScopeCallSiteFlags(identSymbol) | (varNode.isBlockScoped() ? CALLSITE_DECLARE : 0);
3327            if (isFastScope(identSymbol)) {
3328                storeFastScopeVar(identSymbol, flags);
3329            } else {
3330                method.dynamicSet(identNode.getName(), flags, false);
3331            }
3332        } else {
3333            final Type identType = identNode.getType();
3334            if(identType == Type.UNDEFINED) {
3335                // The initializer is either itself undefined (explicit assignment of undefined to undefined),
3336                // or the left hand side is a dead variable.
3337                assert init.getType() == Type.UNDEFINED || identNode.getSymbol().slotCount() == 0;
3338                loadAndDiscard(init);
3339                return false;
3340            }
3341            loadExpressionAsType(init, identType);
3342            storeIdentWithCatchConversion(identNode, identType);
3343        }
3344
3345        return false;
3346    }
3347
3348    private void storeIdentWithCatchConversion(final IdentNode identNode, final Type type) {
3349        // Assignments happening in try/catch blocks need to ensure that they also store a possibly wider typed value
3350        // that will be live at the exit from the try block
3351        final LocalVariableConversion conversion = identNode.getLocalVariableConversion();
3352        final Symbol symbol = identNode.getSymbol();
3353        if(conversion != null && conversion.isLive()) {
3354            assert symbol == conversion.getSymbol();
3355            assert symbol.isBytecodeLocal();
3356            // Only a single conversion from the target type to the join type is expected.
3357            assert conversion.getNext() == null;
3358            assert conversion.getFrom() == type;
3359            // We must propagate potential type change to the catch block
3360            final Label catchLabel = catchLabels.peek();
3361            assert catchLabel != METHOD_BOUNDARY; // ident conversion only exists in try blocks
3362            assert catchLabel.isReachable();
3363            final Type joinType = conversion.getTo();
3364            final Label.Stack catchStack = catchLabel.getStack();
3365            final int joinSlot = symbol.getSlot(joinType);
3366            // With nested try/catch blocks (incl. synthetic ones for finally), we can have a supposed conversion for
3367            // the exception symbol in the nested catch, but it isn't live in the outer catch block, so prevent doing
3368            // conversions for it. E.g. in "try { try { ... } catch(e) { e = 1; } } catch(e2) { ... }", we must not
3369            // introduce an I->O conversion on "e = 1" assignment as "e" is not live in "catch(e2)".
3370            if(catchStack.getUsedSlotsWithLiveTemporaries() > joinSlot) {
3371                method.dup();
3372                method.convert(joinType);
3373                method.store(symbol, joinType);
3374                catchLabel.getStack().onLocalStore(joinType, joinSlot, true);
3375                method.canThrow(catchLabel);
3376                // Store but keep the previous store live too.
3377                method.store(symbol, type, false);
3378                return;
3379            }
3380        }
3381
3382        method.store(symbol, type, true);
3383    }
3384
3385    @Override
3386    public boolean enterWhileNode(final WhileNode whileNode) {
3387        if(!method.isReachable()) {
3388            return false;
3389        }
3390        if(whileNode.isDoWhile()) {
3391            enterDoWhile(whileNode);
3392        } else {
3393            enterStatement(whileNode);
3394            enterForOrWhile(whileNode, null);
3395        }
3396        return false;
3397    }
3398
3399    private void enterForOrWhile(final LoopNode loopNode, final JoinPredecessorExpression modify) {
3400        // NOTE: the usual pattern for compiling test-first loops is "GOTO test; body; test; IFNE body". We use the less
3401        // conventional "test; IFEQ break; body; GOTO test; break;". It has one extra unconditional GOTO in each repeat
3402        // of the loop, but it's not a problem for modern JIT compilers. We do this because our local variable type
3403        // tracking is unfortunately not really prepared for out-of-order execution, e.g. compiling the following
3404        // contrived but legal JavaScript code snippet would fail because the test changes the type of "i" from object
3405        // to double: var i = {valueOf: function() { return 1} }; while(--i >= 0) { ... }
3406        // Instead of adding more complexity to the local variable type tracking, we instead choose to emit this
3407        // different code shape.
3408        final int liveLocalsOnBreak = method.getUsedSlotsWithLiveTemporaries();
3409        final JoinPredecessorExpression test = loopNode.getTest();
3410        if(Expression.isAlwaysFalse(test)) {
3411            loadAndDiscard(test);
3412            return;
3413        }
3414
3415        method.beforeJoinPoint(loopNode);
3416
3417        final Label continueLabel = loopNode.getContinueLabel();
3418        final Label repeatLabel = modify != null ? new Label("for_repeat") : continueLabel;
3419        method.label(repeatLabel);
3420        final int liveLocalsOnContinue = method.getUsedSlotsWithLiveTemporaries();
3421
3422        final Block   body                  = loopNode.getBody();
3423        final Label   breakLabel            = loopNode.getBreakLabel();
3424        final boolean testHasLiveConversion = test != null && LocalVariableConversion.hasLiveConversion(test);
3425
3426        if(Expression.isAlwaysTrue(test)) {
3427            if(test != null) {
3428                loadAndDiscard(test);
3429                if(testHasLiveConversion) {
3430                    method.beforeJoinPoint(test);
3431                }
3432            }
3433        } else if (test != null) {
3434            if (testHasLiveConversion) {
3435                emitBranch(test.getExpression(), body.getEntryLabel(), true);
3436                method.beforeJoinPoint(test);
3437                method._goto(breakLabel);
3438            } else {
3439                emitBranch(test.getExpression(), breakLabel, false);
3440            }
3441        }
3442
3443        body.accept(this);
3444        if(repeatLabel != continueLabel) {
3445            emitContinueLabel(continueLabel, liveLocalsOnContinue);
3446        }
3447
3448        if (loopNode.hasPerIterationScope() && lc.getCurrentBlock().needsScope()) {
3449            // ES6 for loops with LET init need a new scope for each iteration. We just create a shallow copy here.
3450            method.loadCompilerConstant(SCOPE);
3451            method.invoke(virtualCallNoLookup(ScriptObject.class, "copy", ScriptObject.class));
3452            method.storeCompilerConstant(SCOPE);
3453        }
3454
3455        if(method.isReachable()) {
3456            if(modify != null) {
3457                lineNumber(loopNode);
3458                loadAndDiscard(modify);
3459                method.beforeJoinPoint(modify);
3460            }
3461            method._goto(repeatLabel);
3462        }
3463
3464        method.breakLabel(breakLabel, liveLocalsOnBreak);
3465    }
3466
3467    private void emitContinueLabel(final Label continueLabel, final int liveLocals) {
3468        final boolean reachable = method.isReachable();
3469        method.breakLabel(continueLabel, liveLocals);
3470        // If we reach here only through a continue statement (e.g. body does not exit normally) then the
3471        // continueLabel can have extra non-temp symbols (e.g. exception from a try/catch contained in the body). We
3472        // must make sure those are thrown away.
3473        if(!reachable) {
3474            method.undefineLocalVariables(lc.getUsedSlotCount(), false);
3475        }
3476    }
3477
3478    private void enterDoWhile(final WhileNode whileNode) {
3479        final int liveLocalsOnContinueOrBreak = method.getUsedSlotsWithLiveTemporaries();
3480        method.beforeJoinPoint(whileNode);
3481
3482        final Block body = whileNode.getBody();
3483        body.accept(this);
3484
3485        emitContinueLabel(whileNode.getContinueLabel(), liveLocalsOnContinueOrBreak);
3486        if(method.isReachable()) {
3487            lineNumber(whileNode);
3488            final JoinPredecessorExpression test = whileNode.getTest();
3489            final Label bodyEntryLabel = body.getEntryLabel();
3490            final boolean testHasLiveConversion = LocalVariableConversion.hasLiveConversion(test);
3491            if(Expression.isAlwaysFalse(test)) {
3492                loadAndDiscard(test);
3493                if(testHasLiveConversion) {
3494                    method.beforeJoinPoint(test);
3495                }
3496            } else if(testHasLiveConversion) {
3497                // If we have conversions after the test in do-while, they need to be effected on both branches.
3498                final Label beforeExit = new Label("do_while_preexit");
3499                emitBranch(test.getExpression(), beforeExit, false);
3500                method.beforeJoinPoint(test);
3501                method._goto(bodyEntryLabel);
3502                method.label(beforeExit);
3503                method.beforeJoinPoint(test);
3504            } else {
3505                emitBranch(test.getExpression(), bodyEntryLabel, true);
3506            }
3507        }
3508        method.breakLabel(whileNode.getBreakLabel(), liveLocalsOnContinueOrBreak);
3509    }
3510
3511
3512    @Override
3513    public boolean enterWithNode(final WithNode withNode) {
3514        if(!method.isReachable()) {
3515            return false;
3516        }
3517        enterStatement(withNode);
3518        final Expression expression = withNode.getExpression();
3519        final Block      body       = withNode.getBody();
3520
3521        // It is possible to have a "pathological" case where the with block does not reference *any* identifiers. It's
3522        // pointless, but legal. In that case, if nothing else in the method forced the assignment of a slot to the
3523        // scope object, its' possible that it won't have a slot assigned. In this case we'll only evaluate expression
3524        // for its side effect and visit the body, and not bother opening and closing a WithObject.
3525        final boolean hasScope = method.hasScope();
3526
3527        if (hasScope) {
3528            method.loadCompilerConstant(SCOPE);
3529        }
3530
3531        loadExpressionAsObject(expression);
3532
3533        final Label tryLabel;
3534        if (hasScope) {
3535            // Construct a WithObject if we have a scope
3536            method.invoke(ScriptRuntime.OPEN_WITH);
3537            method.storeCompilerConstant(SCOPE);
3538            tryLabel = new Label("with_try");
3539            method.label(tryLabel);
3540        } else {
3541            // We just loaded the expression for its side effect and to check
3542            // for null or undefined value.
3543            globalCheckObjectCoercible();
3544            tryLabel = null;
3545        }
3546
3547        // Always process body
3548        body.accept(this);
3549
3550        if (hasScope) {
3551            // Ensure we always close the WithObject
3552            final Label endLabel   = new Label("with_end");
3553            final Label catchLabel = new Label("with_catch");
3554            final Label exitLabel  = new Label("with_exit");
3555
3556            method.label(endLabel);
3557            // Somewhat conservatively presume that if the body is not empty, it can throw an exception. In any case,
3558            // we must prevent trying to emit a try-catch for empty range, as it causes a verification error.
3559            final boolean bodyCanThrow = endLabel.isAfter(tryLabel);
3560            if(bodyCanThrow) {
3561                method._try(tryLabel, endLabel, catchLabel);
3562            }
3563
3564            final boolean reachable = method.isReachable();
3565            if(reachable) {
3566                popScope();
3567                if(bodyCanThrow) {
3568                    method._goto(exitLabel);
3569                }
3570            }
3571
3572            if(bodyCanThrow) {
3573                method._catch(catchLabel);
3574                popScopeException();
3575                method.athrow();
3576                if(reachable) {
3577                    method.label(exitLabel);
3578                }
3579            }
3580        }
3581        return false;
3582    }
3583
3584    private void loadADD(final UnaryNode unaryNode, final TypeBounds resultBounds) {
3585        loadExpression(unaryNode.getExpression(), resultBounds.booleanToInt().notWiderThan(Type.NUMBER));
3586        if(method.peekType() == Type.BOOLEAN) {
3587            // It's a no-op in bytecode, but we must make sure it is treated as an int for purposes of type signatures
3588            method.convert(Type.INT);
3589        }
3590    }
3591
3592    private void loadBIT_NOT(final UnaryNode unaryNode) {
3593        loadExpression(unaryNode.getExpression(), TypeBounds.INT).load(-1).xor();
3594    }
3595
3596    private void loadDECINC(final UnaryNode unaryNode) {
3597        final Expression operand     = unaryNode.getExpression();
3598        final Type       type        = unaryNode.getType();
3599        final TypeBounds typeBounds  = new TypeBounds(type, Type.NUMBER);
3600        final TokenType  tokenType   = unaryNode.tokenType();
3601        final boolean    isPostfix   = tokenType == TokenType.DECPOSTFIX || tokenType == TokenType.INCPOSTFIX;
3602        final boolean    isIncrement = tokenType == TokenType.INCPREFIX || tokenType == TokenType.INCPOSTFIX;
3603
3604        assert !type.isObject();
3605
3606        new SelfModifyingStore<UnaryNode>(unaryNode, operand) {
3607
3608            private void loadRhs() {
3609                loadExpression(operand, typeBounds, true);
3610            }
3611
3612            @Override
3613            protected void evaluate() {
3614                if(isPostfix) {
3615                    loadRhs();
3616                } else {
3617                    new OptimisticOperation(unaryNode, typeBounds) {
3618                        @Override
3619                        void loadStack() {
3620                            loadRhs();
3621                            loadMinusOne();
3622                        }
3623                        @Override
3624                        void consumeStack() {
3625                            doDecInc(getProgramPoint());
3626                        }
3627                    }.emit(getOptimisticIgnoreCountForSelfModifyingExpression(operand));
3628                }
3629            }
3630
3631            @Override
3632            protected void storeNonDiscard() {
3633                super.storeNonDiscard();
3634                if (isPostfix) {
3635                    new OptimisticOperation(unaryNode, typeBounds) {
3636                        @Override
3637                        void loadStack() {
3638                            loadMinusOne();
3639                        }
3640                        @Override
3641                        void consumeStack() {
3642                            doDecInc(getProgramPoint());
3643                        }
3644                    }.emit(1); // 1 for non-incremented result on the top of the stack pushed in evaluate()
3645                }
3646            }
3647
3648            private void loadMinusOne() {
3649                if (type.isInteger()) {
3650                    method.load(isIncrement ? 1 : -1);
3651                } else if (type.isLong()) {
3652                    method.load(isIncrement ? 1L : -1L);
3653                } else {
3654                    method.load(isIncrement ? 1.0 : -1.0);
3655                }
3656            }
3657
3658            private void doDecInc(final int programPoint) {
3659                method.add(programPoint);
3660            }
3661        }.store();
3662    }
3663
3664    private static int getOptimisticIgnoreCountForSelfModifyingExpression(final Expression target) {
3665        return target instanceof AccessNode ? 1 : target instanceof IndexNode ? 2 : 0;
3666    }
3667
3668    private void loadAndDiscard(final Expression expr) {
3669        // TODO: move checks for discarding to actual expression load code (e.g. as we do with void). That way we might
3670        // be able to eliminate even more checks.
3671        if(expr instanceof PrimitiveLiteralNode | isLocalVariable(expr)) {
3672            assert !lc.isCurrentDiscard(expr);
3673            // Don't bother evaluating expressions without side effects. Typical usage is "void 0" for reliably generating
3674            // undefined.
3675            return;
3676        }
3677
3678        lc.pushDiscard(expr);
3679        loadExpression(expr, TypeBounds.UNBOUNDED);
3680        if (lc.popDiscardIfCurrent(expr)) {
3681            assert !expr.isAssignment();
3682            // NOTE: if we had a way to load with type void, we could avoid popping
3683            method.pop();
3684        }
3685    }
3686
3687    /**
3688     * Loads the expression with the specified type bounds, but if the parent expression is the current discard,
3689     * then instead loads and discards the expression.
3690     * @param parent the parent expression that's tested for being the current discard
3691     * @param expr the expression that's either normally loaded or discard-loaded
3692     * @param resultBounds result bounds for when loading the expression normally
3693     */
3694    private void loadMaybeDiscard(final Expression parent, final Expression expr, final TypeBounds resultBounds) {
3695        loadMaybeDiscard(lc.popDiscardIfCurrent(parent), expr, resultBounds);
3696    }
3697
3698    /**
3699     * Loads the expression with the specified type bounds, or loads and discards the expression, depending on the
3700     * value of the discard flag. Useful as a helper for expressions with control flow where you often can't combine
3701     * testing for being the current discard and loading the subexpressions.
3702     * @param discard if true, the expression is loaded and discarded
3703     * @param expr the expression that's either normally loaded or discard-loaded
3704     * @param resultBounds result bounds for when loading the expression normally
3705     */
3706    private void loadMaybeDiscard(final boolean discard, final Expression expr, final TypeBounds resultBounds) {
3707        if (discard) {
3708            loadAndDiscard(expr);
3709        } else {
3710            loadExpression(expr, resultBounds);
3711        }
3712    }
3713
3714    private void loadNEW(final UnaryNode unaryNode) {
3715        final CallNode callNode = (CallNode)unaryNode.getExpression();
3716        final List<Expression> args   = callNode.getArgs();
3717
3718        final Expression func = callNode.getFunction();
3719        // Load function reference.
3720        loadExpressionAsObject(func); // must detect type error
3721
3722        method.dynamicNew(1 + loadArgs(args), getCallSiteFlags(), func.toString(false));
3723    }
3724
3725    private void loadNOT(final UnaryNode unaryNode) {
3726        final Expression expr = unaryNode.getExpression();
3727        if(expr instanceof UnaryNode && expr.isTokenType(TokenType.NOT)) {
3728            // !!x is idiomatic boolean cast in JavaScript
3729            loadExpressionAsBoolean(((UnaryNode)expr).getExpression());
3730        } else {
3731            final Label trueLabel  = new Label("true");
3732            final Label afterLabel = new Label("after");
3733
3734            emitBranch(expr, trueLabel, true);
3735            method.load(true);
3736            method._goto(afterLabel);
3737            method.label(trueLabel);
3738            method.load(false);
3739            method.label(afterLabel);
3740        }
3741    }
3742
3743    private void loadSUB(final UnaryNode unaryNode, final TypeBounds resultBounds) {
3744        final Type type = unaryNode.getType();
3745        assert type.isNumeric();
3746        final TypeBounds numericBounds = resultBounds.booleanToInt();
3747        new OptimisticOperation(unaryNode, numericBounds) {
3748            @Override
3749            void loadStack() {
3750                final Expression expr = unaryNode.getExpression();
3751                loadExpression(expr, numericBounds.notWiderThan(Type.NUMBER));
3752            }
3753            @Override
3754            void consumeStack() {
3755                // Must do an explicit conversion to the operation's type when it's double so that we correctly handle
3756                // negation of an int 0 to a double -0. With this, we get the correct negation of a local variable after
3757                // it deoptimized, e.g. "iload_2; i2d; dneg". Without this, we get "iload_2; ineg; i2d".
3758                if(type.isNumber()) {
3759                    method.convert(type);
3760                }
3761                method.neg(getProgramPoint());
3762            }
3763        }.emit();
3764    }
3765
3766    public void loadVOID(final UnaryNode unaryNode, final TypeBounds resultBounds) {
3767        loadAndDiscard(unaryNode.getExpression());
3768        if (!lc.popDiscardIfCurrent(unaryNode)) {
3769            method.loadUndefined(resultBounds.widest);
3770        }
3771    }
3772
3773    public void loadADD(final BinaryNode binaryNode, final TypeBounds resultBounds) {
3774        new OptimisticOperation(binaryNode, resultBounds) {
3775            @Override
3776            void loadStack() {
3777                final TypeBounds operandBounds;
3778                final boolean isOptimistic = isValid(getProgramPoint());
3779                boolean forceConversionSeparation = false;
3780                if(isOptimistic) {
3781                    operandBounds = new TypeBounds(binaryNode.getType(), Type.OBJECT);
3782                } else {
3783                    // Non-optimistic, non-FP +. Allow it to overflow.
3784                    final Type widestOperationType = binaryNode.getWidestOperationType();
3785                    operandBounds = new TypeBounds(Type.narrowest(binaryNode.getWidestOperandType(), resultBounds.widest), widestOperationType);
3786                    forceConversionSeparation = widestOperationType.narrowerThan(resultBounds.widest);
3787                }
3788                loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), operandBounds, false, forceConversionSeparation);
3789            }
3790
3791            @Override
3792            void consumeStack() {
3793                method.add(getProgramPoint());
3794            }
3795        }.emit();
3796    }
3797
3798    private void loadAND_OR(final BinaryNode binaryNode, final TypeBounds resultBounds, final boolean isAnd) {
3799        final Type narrowestOperandType = Type.widestReturnType(binaryNode.lhs().getType(), binaryNode.rhs().getType());
3800
3801        final boolean isCurrentDiscard = lc.popDiscardIfCurrent(binaryNode);
3802
3803        final Label skip = new Label("skip");
3804        if(narrowestOperandType == Type.BOOLEAN) {
3805            // optimize all-boolean logical expressions
3806            final Label onTrue = new Label("andor_true");
3807            emitBranch(binaryNode, onTrue, true);
3808            if (isCurrentDiscard) {
3809                method.label(onTrue);
3810            } else {
3811                method.load(false);
3812                method._goto(skip);
3813                method.label(onTrue);
3814                method.load(true);
3815                method.label(skip);
3816            }
3817            return;
3818        }
3819
3820        final TypeBounds outBounds = resultBounds.notNarrowerThan(narrowestOperandType);
3821        final JoinPredecessorExpression lhs = (JoinPredecessorExpression)binaryNode.lhs();
3822        final boolean lhsConvert = LocalVariableConversion.hasLiveConversion(lhs);
3823        final Label evalRhs = lhsConvert ? new Label("eval_rhs") : null;
3824
3825        loadExpression(lhs, outBounds);
3826        if (!isCurrentDiscard) {
3827            method.dup();
3828        }
3829        method.convert(Type.BOOLEAN);
3830        if (isAnd) {
3831            if(lhsConvert) {
3832                method.ifne(evalRhs);
3833            } else {
3834                method.ifeq(skip);
3835            }
3836        } else if(lhsConvert) {
3837            method.ifeq(evalRhs);
3838        } else {
3839            method.ifne(skip);
3840        }
3841
3842        if(lhsConvert) {
3843            method.beforeJoinPoint(lhs);
3844            method._goto(skip);
3845            method.label(evalRhs);
3846        }
3847
3848        if (!isCurrentDiscard) {
3849            method.pop();
3850        }
3851        final JoinPredecessorExpression rhs = (JoinPredecessorExpression)binaryNode.rhs();
3852        loadMaybeDiscard(isCurrentDiscard, rhs, outBounds);
3853        method.beforeJoinPoint(rhs);
3854        method.label(skip);
3855    }
3856
3857    private static boolean isLocalVariable(final Expression lhs) {
3858        return lhs instanceof IdentNode && isLocalVariable((IdentNode)lhs);
3859    }
3860
3861    private static boolean isLocalVariable(final IdentNode lhs) {
3862        return lhs.getSymbol().isBytecodeLocal();
3863    }
3864
3865    // NOTE: does not use resultBounds as the assignment is driven by the type of the RHS
3866    private void loadASSIGN(final BinaryNode binaryNode) {
3867        final Expression lhs = binaryNode.lhs();
3868        final Expression rhs = binaryNode.rhs();
3869
3870        final Type rhsType = rhs.getType();
3871        // Detect dead assignments
3872        if(lhs instanceof IdentNode) {
3873            final Symbol symbol = ((IdentNode)lhs).getSymbol();
3874            if(!symbol.isScope() && !symbol.hasSlotFor(rhsType) && lc.popDiscardIfCurrent(binaryNode)) {
3875                loadAndDiscard(rhs);
3876                method.markDeadLocalVariable(symbol);
3877                return;
3878            }
3879        }
3880
3881        new Store<BinaryNode>(binaryNode, lhs) {
3882            @Override
3883            protected void evaluate() {
3884                // NOTE: we're loading with "at least as wide as" so optimistic operations on the right hand side
3885                // remain optimistic, and then explicitly convert to the required type if needed.
3886                loadExpressionAsType(rhs, rhsType);
3887            }
3888        }.store();
3889    }
3890
3891    /**
3892     * Binary self-assignment that can be optimistic: +=, -=, *=, and /=.
3893     */
3894    private abstract class BinaryOptimisticSelfAssignment extends SelfModifyingStore<BinaryNode> {
3895
3896        /**
3897         * Constructor
3898         *
3899         * @param node the assign op node
3900         */
3901        BinaryOptimisticSelfAssignment(final BinaryNode node) {
3902            super(node, node.lhs());
3903        }
3904
3905        protected abstract void op(OptimisticOperation oo);
3906
3907        @Override
3908        protected void evaluate() {
3909            final Expression lhs = assignNode.lhs();
3910            final Expression rhs = assignNode.rhs();
3911            final Type widestOperationType = assignNode.getWidestOperationType();
3912            final TypeBounds bounds = new TypeBounds(assignNode.getType(), widestOperationType);
3913            new OptimisticOperation(assignNode, bounds) {
3914                @Override
3915                void loadStack() {
3916                    final boolean forceConversionSeparation;
3917                    if (isValid(getProgramPoint()) || widestOperationType == Type.NUMBER) {
3918                        forceConversionSeparation = false;
3919                    } else {
3920                        final Type operandType = Type.widest(booleanToInt(objectToNumber(lhs.getType())), booleanToInt(objectToNumber(rhs.getType())));
3921                        forceConversionSeparation = operandType.narrowerThan(widestOperationType);
3922                    }
3923                    loadBinaryOperands(lhs, rhs, bounds, true, forceConversionSeparation);
3924                }
3925                @Override
3926                void consumeStack() {
3927                    op(this);
3928                }
3929            }.emit(getOptimisticIgnoreCountForSelfModifyingExpression(lhs));
3930            method.convert(assignNode.getType());
3931        }
3932    }
3933
3934    /**
3935     * Non-optimistic binary self-assignment operation. Basically, everything except +=, -=, *=, and /=.
3936     */
3937    private abstract class BinarySelfAssignment extends SelfModifyingStore<BinaryNode> {
3938        BinarySelfAssignment(final BinaryNode node) {
3939            super(node, node.lhs());
3940        }
3941
3942        protected abstract void op();
3943
3944        @Override
3945        protected void evaluate() {
3946            loadBinaryOperands(assignNode.lhs(), assignNode.rhs(), TypeBounds.UNBOUNDED.notWiderThan(assignNode.getWidestOperandType()), true, false);
3947            op();
3948        }
3949    }
3950
3951    private void loadASSIGN_ADD(final BinaryNode binaryNode) {
3952        new BinaryOptimisticSelfAssignment(binaryNode) {
3953            @Override
3954            protected void op(final OptimisticOperation oo) {
3955                assert !(binaryNode.getType().isObject() && oo.isOptimistic);
3956                method.add(oo.getProgramPoint());
3957            }
3958        }.store();
3959    }
3960
3961    private void loadASSIGN_BIT_AND(final BinaryNode binaryNode) {
3962        new BinarySelfAssignment(binaryNode) {
3963            @Override
3964            protected void op() {
3965                method.and();
3966            }
3967        }.store();
3968    }
3969
3970    private void loadASSIGN_BIT_OR(final BinaryNode binaryNode) {
3971        new BinarySelfAssignment(binaryNode) {
3972            @Override
3973            protected void op() {
3974                method.or();
3975            }
3976        }.store();
3977    }
3978
3979    private void loadASSIGN_BIT_XOR(final BinaryNode binaryNode) {
3980        new BinarySelfAssignment(binaryNode) {
3981            @Override
3982            protected void op() {
3983                method.xor();
3984            }
3985        }.store();
3986    }
3987
3988    private void loadASSIGN_DIV(final BinaryNode binaryNode) {
3989        new BinaryOptimisticSelfAssignment(binaryNode) {
3990            @Override
3991            protected void op(final OptimisticOperation oo) {
3992                method.div(oo.getProgramPoint());
3993            }
3994        }.store();
3995    }
3996
3997    private void loadASSIGN_MOD(final BinaryNode binaryNode) {
3998        new BinaryOptimisticSelfAssignment(binaryNode) {
3999            @Override
4000            protected void op(final OptimisticOperation oo) {
4001                method.rem(oo.getProgramPoint());
4002            }
4003        }.store();
4004    }
4005
4006    private void loadASSIGN_MUL(final BinaryNode binaryNode) {
4007        new BinaryOptimisticSelfAssignment(binaryNode) {
4008            @Override
4009            protected void op(final OptimisticOperation oo) {
4010                method.mul(oo.getProgramPoint());
4011            }
4012        }.store();
4013    }
4014
4015    private void loadASSIGN_SAR(final BinaryNode binaryNode) {
4016        new BinarySelfAssignment(binaryNode) {
4017            @Override
4018            protected void op() {
4019                method.sar();
4020            }
4021        }.store();
4022    }
4023
4024    private void loadASSIGN_SHL(final BinaryNode binaryNode) {
4025        new BinarySelfAssignment(binaryNode) {
4026            @Override
4027            protected void op() {
4028                method.shl();
4029            }
4030        }.store();
4031    }
4032
4033    private void loadASSIGN_SHR(final BinaryNode binaryNode) {
4034        new BinarySelfAssignment(binaryNode) {
4035            @Override
4036            protected void op() {
4037                doSHR();
4038            }
4039
4040        }.store();
4041    }
4042
4043    private void doSHR() {
4044        // TODO: make SHR optimistic
4045        method.shr();
4046        toUint();
4047    }
4048
4049    private void toUint() {
4050        JSType.TO_UINT32_I.invoke(method);
4051    }
4052
4053    private void loadASSIGN_SUB(final BinaryNode binaryNode) {
4054        new BinaryOptimisticSelfAssignment(binaryNode) {
4055            @Override
4056            protected void op(final OptimisticOperation oo) {
4057                method.sub(oo.getProgramPoint());
4058            }
4059        }.store();
4060    }
4061
4062    /**
4063     * Helper class for binary arithmetic ops
4064     */
4065    private abstract class BinaryArith {
4066        protected abstract void op(int programPoint);
4067
4068        protected void evaluate(final BinaryNode node, final TypeBounds resultBounds) {
4069            final TypeBounds numericBounds = resultBounds.booleanToInt().objectToNumber();
4070            new OptimisticOperation(node, numericBounds) {
4071                @Override
4072                void loadStack() {
4073                    final TypeBounds operandBounds;
4074                    boolean forceConversionSeparation = false;
4075                    if(numericBounds.narrowest == Type.NUMBER) {
4076                        // Result should be double always. Propagate it into the operands so we don't have lots of I2D
4077                        // and L2D after operand evaluation.
4078                        assert numericBounds.widest == Type.NUMBER;
4079                        operandBounds = numericBounds;
4080                    } else {
4081                        final boolean isOptimistic = isValid(getProgramPoint());
4082                        if(isOptimistic || node.isTokenType(TokenType.DIV) || node.isTokenType(TokenType.MOD)) {
4083                            operandBounds = new TypeBounds(node.getType(), Type.NUMBER);
4084                        } else {
4085                            // Non-optimistic, non-FP subtraction or multiplication. Allow them to overflow.
4086                            operandBounds = new TypeBounds(Type.narrowest(node.getWidestOperandType(),
4087                                    numericBounds.widest), Type.NUMBER);
4088                            forceConversionSeparation = node.getWidestOperationType().narrowerThan(numericBounds.widest);
4089                        }
4090                    }
4091                    loadBinaryOperands(node.lhs(), node.rhs(), operandBounds, false, forceConversionSeparation);
4092                }
4093
4094                @Override
4095                void consumeStack() {
4096                    op(getProgramPoint());
4097                }
4098            }.emit();
4099        }
4100    }
4101
4102    private void loadBIT_AND(final BinaryNode binaryNode) {
4103        loadBinaryOperands(binaryNode);
4104        method.and();
4105    }
4106
4107    private void loadBIT_OR(final BinaryNode binaryNode) {
4108        // Optimize x|0 to (int)x
4109        if (isRhsZero(binaryNode)) {
4110            loadExpressionAsType(binaryNode.lhs(), Type.INT);
4111        } else {
4112            loadBinaryOperands(binaryNode);
4113            method.or();
4114        }
4115    }
4116
4117    private static boolean isRhsZero(final BinaryNode binaryNode) {
4118        final Expression rhs = binaryNode.rhs();
4119        return rhs instanceof LiteralNode && INT_ZERO.equals(((LiteralNode<?>)rhs).getValue());
4120    }
4121
4122    private void loadBIT_XOR(final BinaryNode binaryNode) {
4123        loadBinaryOperands(binaryNode);
4124        method.xor();
4125    }
4126
4127    private void loadCOMMARIGHT(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4128        loadAndDiscard(binaryNode.lhs());
4129        loadMaybeDiscard(binaryNode, binaryNode.rhs(), resultBounds);
4130    }
4131
4132    private void loadCOMMALEFT(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4133        loadMaybeDiscard(binaryNode, binaryNode.lhs(), resultBounds);
4134        loadAndDiscard(binaryNode.rhs());
4135    }
4136
4137    private void loadDIV(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4138        new BinaryArith() {
4139            @Override
4140            protected void op(final int programPoint) {
4141                method.div(programPoint);
4142            }
4143        }.evaluate(binaryNode, resultBounds);
4144    }
4145
4146    private void loadCmp(final BinaryNode binaryNode, final Condition cond) {
4147        loadComparisonOperands(binaryNode);
4148
4149        final Label trueLabel  = new Label("trueLabel");
4150        final Label afterLabel = new Label("skip");
4151
4152        method.conditionalJump(cond, trueLabel);
4153
4154        method.load(Boolean.FALSE);
4155        method._goto(afterLabel);
4156        method.label(trueLabel);
4157        method.load(Boolean.TRUE);
4158        method.label(afterLabel);
4159    }
4160
4161    private void loadMOD(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4162        new BinaryArith() {
4163            @Override
4164            protected void op(final int programPoint) {
4165                method.rem(programPoint);
4166            }
4167        }.evaluate(binaryNode, resultBounds);
4168    }
4169
4170    private void loadMUL(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4171        new BinaryArith() {
4172            @Override
4173            protected void op(final int programPoint) {
4174                method.mul(programPoint);
4175            }
4176        }.evaluate(binaryNode, resultBounds);
4177    }
4178
4179    private void loadSAR(final BinaryNode binaryNode) {
4180        loadBinaryOperands(binaryNode);
4181        method.sar();
4182    }
4183
4184    private void loadSHL(final BinaryNode binaryNode) {
4185        loadBinaryOperands(binaryNode);
4186        method.shl();
4187    }
4188
4189    private void loadSHR(final BinaryNode binaryNode) {
4190        // Optimize x >>> 0 to (uint)x
4191        if (isRhsZero(binaryNode)) {
4192            loadExpressionAsType(binaryNode.lhs(), Type.INT);
4193            toUint();
4194        } else {
4195            loadBinaryOperands(binaryNode);
4196            doSHR();
4197        }
4198    }
4199
4200    private void loadSUB(final BinaryNode binaryNode, final TypeBounds resultBounds) {
4201        new BinaryArith() {
4202            @Override
4203            protected void op(final int programPoint) {
4204                method.sub(programPoint);
4205            }
4206        }.evaluate(binaryNode, resultBounds);
4207    }
4208
4209    @Override
4210    public boolean enterLabelNode(final LabelNode labelNode) {
4211        labeledBlockBreakLiveLocals.push(lc.getUsedSlotCount());
4212        return true;
4213    }
4214
4215    @Override
4216    protected boolean enterDefault(final Node node) {
4217        throw new AssertionError("Code generator entered node of type " + node.getClass().getName());
4218    }
4219
4220    private void loadTernaryNode(final TernaryNode ternaryNode, final TypeBounds resultBounds) {
4221        final Expression test = ternaryNode.getTest();
4222        final JoinPredecessorExpression trueExpr  = ternaryNode.getTrueExpression();
4223        final JoinPredecessorExpression falseExpr = ternaryNode.getFalseExpression();
4224
4225        final Label falseLabel = new Label("ternary_false");
4226        final Label exitLabel  = new Label("ternary_exit");
4227
4228        final Type outNarrowest = Type.narrowest(resultBounds.widest, Type.generic(Type.widestReturnType(trueExpr.getType(), falseExpr.getType())));
4229        final TypeBounds outBounds = resultBounds.notNarrowerThan(outNarrowest);
4230
4231        emitBranch(test, falseLabel, false);
4232
4233        final boolean isCurrentDiscard = lc.popDiscardIfCurrent(ternaryNode);
4234        loadMaybeDiscard(isCurrentDiscard, trueExpr.getExpression(), outBounds);
4235        assert isCurrentDiscard || Type.generic(method.peekType()) == outBounds.narrowest;
4236        method.beforeJoinPoint(trueExpr);
4237        method._goto(exitLabel);
4238        method.label(falseLabel);
4239        loadMaybeDiscard(isCurrentDiscard, falseExpr.getExpression(), outBounds);
4240        assert isCurrentDiscard || Type.generic(method.peekType()) == outBounds.narrowest;
4241        method.beforeJoinPoint(falseExpr);
4242        method.label(exitLabel);
4243    }
4244
4245    /**
4246     * Generate all shared scope calls generated during codegen.
4247     */
4248    void generateScopeCalls() {
4249        for (final SharedScopeCall scopeAccess : lc.getScopeCalls()) {
4250            scopeAccess.generateScopeCall();
4251        }
4252    }
4253
4254    /**
4255     * Debug code used to print symbols
4256     *
4257     * @param block the block we are in
4258     * @param function the function we are in
4259     * @param ident identifier for block or function where applicable
4260     */
4261    private void printSymbols(final Block block, final FunctionNode function, final String ident) {
4262        if (compiler.getScriptEnvironment()._print_symbols || function.getFlag(FunctionNode.IS_PRINT_SYMBOLS)) {
4263            final PrintWriter out = compiler.getScriptEnvironment().getErr();
4264            out.println("[BLOCK in '" + ident + "']");
4265            if (!block.printSymbols(out)) {
4266                out.println("<no symbols>");
4267            }
4268            out.println();
4269        }
4270    }
4271
4272
4273    /**
4274     * The difference between a store and a self modifying store is that
4275     * the latter may load part of the target on the stack, e.g. the base
4276     * of an AccessNode or the base and index of an IndexNode. These are used
4277     * both as target and as an extra source. Previously it was problematic
4278     * for self modifying stores if the target/lhs didn't belong to one
4279     * of three trivial categories: IdentNode, AcessNodes, IndexNodes. In that
4280     * case it was evaluated and tagged as "resolved", which meant at the second
4281     * time the lhs of this store was read (e.g. in a = a (second) + b for a += b,
4282     * it would be evaluated to a nop in the scope and cause stack underflow
4283     *
4284     * see NASHORN-703
4285     *
4286     * @param <T>
4287     */
4288    private abstract class SelfModifyingStore<T extends Expression> extends Store<T> {
4289        protected SelfModifyingStore(final T assignNode, final Expression target) {
4290            super(assignNode, target);
4291        }
4292
4293        @Override
4294        protected boolean isSelfModifying() {
4295            return true;
4296        }
4297    }
4298
4299    /**
4300     * Helper class to generate stores
4301     */
4302    private abstract class Store<T extends Expression> {
4303
4304        /** An assignment node, e.g. x += y */
4305        protected final T assignNode;
4306
4307        /** The target node to store to, e.g. x */
4308        private final Expression target;
4309
4310        /** How deep on the stack do the arguments go if this generates an indy call */
4311        private int depth;
4312
4313        /** If we have too many arguments, we need temporary storage, this is stored in 'quick' */
4314        private IdentNode quick;
4315
4316        /**
4317         * Constructor
4318         *
4319         * @param assignNode the node representing the whole assignment
4320         * @param target     the target node of the assignment (destination)
4321         */
4322        protected Store(final T assignNode, final Expression target) {
4323            this.assignNode = assignNode;
4324            this.target = target;
4325        }
4326
4327        /**
4328         * Constructor
4329         *
4330         * @param assignNode the node representing the whole assignment
4331         */
4332        protected Store(final T assignNode) {
4333            this(assignNode, assignNode);
4334        }
4335
4336        /**
4337         * Is this a self modifying store operation, e.g. *= or ++
4338         * @return true if self modifying store
4339         */
4340        protected boolean isSelfModifying() {
4341            return false;
4342        }
4343
4344        private void prologue() {
4345            /*
4346             * This loads the parts of the target, e.g base and index. they are kept
4347             * on the stack throughout the store and used at the end to execute it
4348             */
4349
4350            target.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
4351                @Override
4352                public boolean enterIdentNode(final IdentNode node) {
4353                    if (node.getSymbol().isScope()) {
4354                        method.loadCompilerConstant(SCOPE);
4355                        depth += Type.SCOPE.getSlots();
4356                        assert depth == 1;
4357                    }
4358                    return false;
4359                }
4360
4361                private void enterBaseNode() {
4362                    assert target instanceof BaseNode : "error - base node " + target + " must be instanceof BaseNode";
4363                    final BaseNode   baseNode = (BaseNode)target;
4364                    final Expression base     = baseNode.getBase();
4365
4366                    loadExpressionAsObject(base);
4367                    depth += Type.OBJECT.getSlots();
4368                    assert depth == 1;
4369
4370                    if (isSelfModifying()) {
4371                        method.dup();
4372                    }
4373                }
4374
4375                @Override
4376                public boolean enterAccessNode(final AccessNode node) {
4377                    enterBaseNode();
4378                    return false;
4379                }
4380
4381                @Override
4382                public boolean enterIndexNode(final IndexNode node) {
4383                    enterBaseNode();
4384
4385                    final Expression index = node.getIndex();
4386                    if (!index.getType().isNumeric()) {
4387                        // could be boolean here as well
4388                        loadExpressionAsObject(index);
4389                    } else {
4390                        loadExpressionUnbounded(index);
4391                    }
4392                    depth += index.getType().getSlots();
4393
4394                    if (isSelfModifying()) {
4395                        //convert "base base index" to "base index base index"
4396                        method.dup(1);
4397                    }
4398
4399                    return false;
4400                }
4401
4402            });
4403        }
4404
4405        /**
4406         * Generates an extra local variable, always using the same slot, one that is available after the end of the
4407         * frame.
4408         *
4409         * @param type the type of the variable
4410         *
4411         * @return the quick variable
4412         */
4413        private IdentNode quickLocalVariable(final Type type) {
4414            final String name = lc.getCurrentFunction().uniqueName(QUICK_PREFIX.symbolName());
4415            final Symbol symbol = new Symbol(name, IS_INTERNAL | HAS_SLOT);
4416            symbol.setHasSlotFor(type);
4417            symbol.setFirstSlot(lc.quickSlot(type));
4418
4419            final IdentNode quickIdent = IdentNode.createInternalIdentifier(symbol).setType(type);
4420
4421            return quickIdent;
4422        }
4423
4424        // store the result that "lives on" after the op, e.g. "i" in i++ postfix.
4425        protected void storeNonDiscard() {
4426            if (lc.popDiscardIfCurrent(assignNode)) {
4427                assert assignNode.isAssignment();
4428                return;
4429            }
4430
4431            if (method.dup(depth) == null) {
4432                method.dup();
4433                final Type quickType = method.peekType();
4434                this.quick = quickLocalVariable(quickType);
4435                final Symbol quickSymbol = quick.getSymbol();
4436                method.storeTemp(quickType, quickSymbol.getFirstSlot());
4437            }
4438        }
4439
4440        private void epilogue() {
4441            /**
4442             * Take the original target args from the stack and use them
4443             * together with the value to be stored to emit the store code
4444             *
4445             * The case that targetSymbol is in scope (!hasSlot) and we actually
4446             * need to do a conversion on non-equivalent types exists, but is
4447             * very rare. See for example test/script/basic/access-specializer.js
4448             */
4449            target.accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
4450                @Override
4451                protected boolean enterDefault(final Node node) {
4452                    throw new AssertionError("Unexpected node " + node + " in store epilogue");
4453                }
4454
4455                @Override
4456                public boolean enterIdentNode(final IdentNode node) {
4457                    final Symbol symbol = node.getSymbol();
4458                    assert symbol != null;
4459                    if (symbol.isScope()) {
4460                        final int flags = getScopeCallSiteFlags(symbol);
4461                        if (isFastScope(symbol)) {
4462                            storeFastScopeVar(symbol, flags);
4463                        } else {
4464                            method.dynamicSet(node.getName(), flags, false);
4465                        }
4466                    } else {
4467                        final Type storeType = assignNode.getType();
4468                        if (symbol.hasSlotFor(storeType)) {
4469                            // Only emit a convert for a store known to be live; converts for dead stores can
4470                            // give us an unnecessary ClassCastException.
4471                            method.convert(storeType);
4472                        }
4473                        storeIdentWithCatchConversion(node, storeType);
4474                    }
4475                    return false;
4476
4477                }
4478
4479                @Override
4480                public boolean enterAccessNode(final AccessNode node) {
4481                    method.dynamicSet(node.getProperty(), getCallSiteFlags(), node.isIndex());
4482                    return false;
4483                }
4484
4485                @Override
4486                public boolean enterIndexNode(final IndexNode node) {
4487                    method.dynamicSetIndex(getCallSiteFlags());
4488                    return false;
4489                }
4490            });
4491
4492
4493            // whatever is on the stack now is the final answer
4494        }
4495
4496        protected abstract void evaluate();
4497
4498        void store() {
4499            if (target instanceof IdentNode) {
4500                checkTemporalDeadZone((IdentNode)target);
4501            }
4502            prologue();
4503            evaluate(); // leaves an operation of whatever the operationType was on the stack
4504            storeNonDiscard();
4505            epilogue();
4506            if (quick != null) {
4507                method.load(quick);
4508            }
4509        }
4510    }
4511
4512    private void newFunctionObject(final FunctionNode functionNode, final boolean addInitializer) {
4513        assert lc.peek() == functionNode;
4514
4515        final RecompilableScriptFunctionData data = compiler.getScriptFunctionData(functionNode.getId());
4516
4517        if (functionNode.isProgram() && !compiler.isOnDemandCompilation()) {
4518            final MethodEmitter createFunction = functionNode.getCompileUnit().getClassEmitter().method(
4519                    EnumSet.of(Flag.PUBLIC, Flag.STATIC), CREATE_PROGRAM_FUNCTION.symbolName(),
4520                    ScriptFunction.class, ScriptObject.class);
4521            createFunction.begin();
4522            loadConstantsAndIndex(data, createFunction);
4523            createFunction.load(SCOPE_TYPE, 0);
4524            createFunction.invoke(CREATE_FUNCTION_OBJECT);
4525            createFunction._return();
4526            createFunction.end();
4527        }
4528
4529        if (addInitializer && !compiler.isOnDemandCompilation()) {
4530            functionNode.getCompileUnit().addFunctionInitializer(data, functionNode);
4531        }
4532
4533        // We don't emit a ScriptFunction on stack for the outermost compiled function (as there's no code being
4534        // generated in its outer context that'd need it as a callee).
4535        if (lc.getOutermostFunction() == functionNode) {
4536            return;
4537        }
4538
4539        loadConstantsAndIndex(data, method);
4540
4541        if (functionNode.needsParentScope()) {
4542            method.loadCompilerConstant(SCOPE);
4543            method.invoke(CREATE_FUNCTION_OBJECT);
4544        } else {
4545            method.invoke(CREATE_FUNCTION_OBJECT_NO_SCOPE);
4546        }
4547    }
4548
4549    // calls on Global class.
4550    private MethodEmitter globalInstance() {
4551        return method.invokestatic(GLOBAL_OBJECT, "instance", "()L" + GLOBAL_OBJECT + ';');
4552    }
4553
4554    private MethodEmitter globalAllocateArguments() {
4555        return method.invokestatic(GLOBAL_OBJECT, "allocateArguments", methodDescriptor(ScriptObject.class, Object[].class, Object.class, int.class));
4556    }
4557
4558    private MethodEmitter globalNewRegExp() {
4559        return method.invokestatic(GLOBAL_OBJECT, "newRegExp", methodDescriptor(Object.class, String.class, String.class));
4560    }
4561
4562    private MethodEmitter globalRegExpCopy() {
4563        return method.invokestatic(GLOBAL_OBJECT, "regExpCopy", methodDescriptor(Object.class, Object.class));
4564    }
4565
4566    private MethodEmitter globalAllocateArray(final ArrayType type) {
4567        //make sure the native array is treated as an array type
4568        return method.invokestatic(GLOBAL_OBJECT, "allocate", "(" + type.getDescriptor() + ")Ljdk/nashorn/internal/objects/NativeArray;");
4569    }
4570
4571    private MethodEmitter globalIsEval() {
4572        return method.invokestatic(GLOBAL_OBJECT, "isEval", methodDescriptor(boolean.class, Object.class));
4573    }
4574
4575    private MethodEmitter globalReplaceLocationPropertyPlaceholder() {
4576        return method.invokestatic(GLOBAL_OBJECT, "replaceLocationPropertyPlaceholder", methodDescriptor(Object.class, Object.class, Object.class));
4577    }
4578
4579    private MethodEmitter globalCheckObjectCoercible() {
4580        return method.invokestatic(GLOBAL_OBJECT, "checkObjectCoercible", methodDescriptor(void.class, Object.class));
4581    }
4582
4583    private MethodEmitter globalDirectEval() {
4584        return method.invokestatic(GLOBAL_OBJECT, "directEval",
4585                methodDescriptor(Object.class, Object.class, Object.class, Object.class, Object.class, boolean.class));
4586    }
4587
4588    private abstract class OptimisticOperation {
4589        private final boolean isOptimistic;
4590        // expression and optimistic are the same reference
4591        private final Expression expression;
4592        private final Optimistic optimistic;
4593        private final TypeBounds resultBounds;
4594
4595        OptimisticOperation(final Optimistic optimistic, final TypeBounds resultBounds) {
4596            this.optimistic = optimistic;
4597            this.expression = (Expression)optimistic;
4598            this.resultBounds = resultBounds;
4599            this.isOptimistic = isOptimistic(optimistic) && useOptimisticTypes() &&
4600                    // Operation is only effectively optimistic if its type, after being coerced into the result bounds
4601                    // is narrower than the upper bound.
4602                    resultBounds.within(Type.generic(((Expression)optimistic).getType())).narrowerThan(resultBounds.widest);
4603        }
4604
4605        MethodEmitter emit() {
4606            return emit(0);
4607        }
4608
4609        MethodEmitter emit(final int ignoredArgCount) {
4610            final int     programPoint                  = optimistic.getProgramPoint();
4611            final boolean optimisticOrContinuation      = isOptimistic || isContinuationEntryPoint(programPoint);
4612            final boolean currentContinuationEntryPoint = isCurrentContinuationEntryPoint(programPoint);
4613            final int     stackSizeOnEntry              = method.getStackSize() - ignoredArgCount;
4614
4615            // First store the values on the stack opportunistically into local variables. Doing it before loadStack()
4616            // allows us to not have to pop/load any arguments that are pushed onto it by loadStack() in the second
4617            // storeStack().
4618            storeStack(ignoredArgCount, optimisticOrContinuation);
4619
4620            // Now, load the stack
4621            loadStack();
4622
4623            // Now store the values on the stack ultimately into local variables. In vast majority of cases, this is
4624            // (aside from creating the local types map) a no-op, as the first opportunistic stack store will already
4625            // store all variables. However, there can be operations in the loadStack() that invalidate some of the
4626            // stack stores, e.g. in "x[i] = x[++i]", "++i" will invalidate the already stored value for "i". In such
4627            // unfortunate cases this second storeStack() will restore the invariant that everything on the stack is
4628            // stored into a local variable, although at the cost of doing a store/load on the loaded arguments as well.
4629            final int liveLocalsCount = storeStack(method.getStackSize() - stackSizeOnEntry, optimisticOrContinuation);
4630            assert optimisticOrContinuation == (liveLocalsCount != -1);
4631
4632            final Label beginTry;
4633            final Label catchLabel;
4634            final Label afterConsumeStack = isOptimistic || currentContinuationEntryPoint ? new Label("after_consume_stack") : null;
4635            if(isOptimistic) {
4636                beginTry = new Label("try_optimistic");
4637                final String catchLabelName = (afterConsumeStack == null ? "" : afterConsumeStack.toString()) + "_handler";
4638                catchLabel = new Label(catchLabelName);
4639                method.label(beginTry);
4640            } else {
4641                beginTry = catchLabel = null;
4642            }
4643
4644            consumeStack();
4645
4646            if(isOptimistic) {
4647                method._try(beginTry, afterConsumeStack, catchLabel, UnwarrantedOptimismException.class);
4648            }
4649
4650            if(isOptimistic || currentContinuationEntryPoint) {
4651                method.label(afterConsumeStack);
4652
4653                final int[] localLoads = method.getLocalLoadsOnStack(0, stackSizeOnEntry);
4654                assert everyStackValueIsLocalLoad(localLoads) : Arrays.toString(localLoads) + ", " + stackSizeOnEntry + ", " + ignoredArgCount;
4655                final List<Type> localTypesList = method.getLocalVariableTypes();
4656                final int usedLocals = method.getUsedSlotsWithLiveTemporaries();
4657                final List<Type> localTypes = method.getWidestLiveLocals(localTypesList.subList(0, usedLocals));
4658                assert everyLocalLoadIsValid(localLoads, usedLocals) : Arrays.toString(localLoads) + " ~ " + localTypes;
4659
4660                if(isOptimistic) {
4661                    addUnwarrantedOptimismHandlerLabel(localTypes, catchLabel);
4662                }
4663                if(currentContinuationEntryPoint) {
4664                    final ContinuationInfo ci = getContinuationInfo();
4665                    assert ci != null : "no continuation info found for " + lc.getCurrentFunction();
4666                    assert !ci.hasTargetLabel(); // No duplicate program points
4667                    ci.setTargetLabel(afterConsumeStack);
4668                    ci.getHandlerLabel().markAsOptimisticContinuationHandlerFor(afterConsumeStack);
4669                    // Can't rely on targetLabel.stack.localVariableTypes.length, as it can be higher due to effectively
4670                    // dead local variables.
4671                    ci.lvarCount = localTypes.size();
4672                    ci.setStackStoreSpec(localLoads);
4673                    ci.setStackTypes(Arrays.copyOf(method.getTypesFromStack(method.getStackSize()), stackSizeOnEntry));
4674                    assert ci.getStackStoreSpec().length == ci.getStackTypes().length;
4675                    ci.setReturnValueType(method.peekType());
4676                    ci.lineNumber = getLastLineNumber();
4677                    ci.catchLabel = catchLabels.peek();
4678                }
4679            }
4680            return method;
4681        }
4682
4683        /**
4684         * Stores the current contents of the stack into local variables so they are not lost before invoking something that
4685         * can result in an {@code UnwarantedOptimizationException}.
4686         * @param ignoreArgCount the number of topmost arguments on stack to ignore when deciding on the shape of the catch
4687         * block. Those are used in the situations when we could not place the call to {@code storeStack} early enough
4688         * (before emitting code for pushing the arguments that the optimistic call will pop). This is admittedly a
4689         * deficiency in the design of the code generator when it deals with self-assignments and we should probably look
4690         * into fixing it.
4691         * @return types of the significant local variables after the stack was stored (types for local variables used
4692         * for temporary storage of ignored arguments are not returned).
4693         * @param optimisticOrContinuation if false, this method should not execute
4694         * a label for a catch block for the {@code UnwarantedOptimizationException}, suitable for capturing the
4695         * currently live local variables, tailored to their types.
4696         */
4697        private int storeStack(final int ignoreArgCount, final boolean optimisticOrContinuation) {
4698            if(!optimisticOrContinuation) {
4699                return -1; // NOTE: correct value to return is lc.getUsedSlotCount(), but it wouldn't be used anyway
4700            }
4701
4702            final int stackSize = method.getStackSize();
4703            final Type[] stackTypes = method.getTypesFromStack(stackSize);
4704            final int[] localLoadsOnStack = method.getLocalLoadsOnStack(0, stackSize);
4705            final int usedSlots = method.getUsedSlotsWithLiveTemporaries();
4706
4707            final int firstIgnored = stackSize - ignoreArgCount;
4708            // Find the first value on the stack (from the bottom) that is not a load from a local variable.
4709            int firstNonLoad = 0;
4710            while(firstNonLoad < firstIgnored && localLoadsOnStack[firstNonLoad] != Label.Stack.NON_LOAD) {
4711                firstNonLoad++;
4712            }
4713
4714            // Only do the store/load if first non-load is not an ignored argument. Otherwise, do nothing and return
4715            // the number of used slots as the number of live local variables.
4716            if(firstNonLoad >= firstIgnored) {
4717                return usedSlots;
4718            }
4719
4720            // Find the number of new temporary local variables that we need; it's the number of values on the stack that
4721            // are not direct loads of existing local variables.
4722            int tempSlotsNeeded = 0;
4723            for(int i = firstNonLoad; i < stackSize; ++i) {
4724                if(localLoadsOnStack[i] == Label.Stack.NON_LOAD) {
4725                    tempSlotsNeeded += stackTypes[i].getSlots();
4726                }
4727            }
4728
4729            // Ensure all values on the stack that weren't directly loaded from a local variable are stored in a local
4730            // variable. We're starting from highest local variable index, so that in case ignoreArgCount > 0 the ignored
4731            // ones end up at the end of the local variable table.
4732            int lastTempSlot = usedSlots + tempSlotsNeeded;
4733            int ignoreSlotCount = 0;
4734            for(int i = stackSize; i -- > firstNonLoad;) {
4735                final int loadSlot = localLoadsOnStack[i];
4736                if(loadSlot == Label.Stack.NON_LOAD) {
4737                    final Type type = stackTypes[i];
4738                    final int slots = type.getSlots();
4739                    lastTempSlot -= slots;
4740                    if(i >= firstIgnored) {
4741                        ignoreSlotCount += slots;
4742                    }
4743                    method.storeTemp(type, lastTempSlot);
4744                } else {
4745                    method.pop();
4746                }
4747            }
4748            assert lastTempSlot == usedSlots; // used all temporary locals
4749
4750            final List<Type> localTypesList = method.getLocalVariableTypes();
4751
4752            // Load values back on stack.
4753            for(int i = firstNonLoad; i < stackSize; ++i) {
4754                final int loadSlot = localLoadsOnStack[i];
4755                final Type stackType = stackTypes[i];
4756                final boolean isLoad = loadSlot != Label.Stack.NON_LOAD;
4757                final int lvarSlot = isLoad ? loadSlot : lastTempSlot;
4758                final Type lvarType = localTypesList.get(lvarSlot);
4759                method.load(lvarType, lvarSlot);
4760                if(isLoad) {
4761                    // Conversion operators (I2L etc.) preserve "load"-ness of the value despite the fact that, in the
4762                    // strict sense they are creating a derived value from the loaded value. This special behavior of
4763                    // on-stack conversion operators is necessary to accommodate for differences in local variable types
4764                    // after deoptimization; having a conversion operator throw away "load"-ness would create different
4765                    // local variable table shapes between optimism-failed code and its deoptimized rest-of method).
4766                    // After we load the value back, we need to redo the conversion to the stack type if stack type is
4767                    // different.
4768                    // NOTE: this would only strictly be necessary for widening conversions (I2L, L2D, I2D), and not for
4769                    // narrowing ones (L2I, D2L, D2I) as only widening conversions are the ones that can get eliminated
4770                    // in a deoptimized method, as their original input argument got widened. Maybe experiment with
4771                    // throwing away "load"-ness for narrowing conversions in MethodEmitter.convert()?
4772                    method.convert(stackType);
4773                } else {
4774                    // temporary stores never needs a convert, as their type is always the same as the stack type.
4775                    assert lvarType == stackType;
4776                    lastTempSlot += lvarType.getSlots();
4777                }
4778            }
4779            // used all temporaries
4780            assert lastTempSlot == usedSlots + tempSlotsNeeded;
4781
4782            return lastTempSlot - ignoreSlotCount;
4783        }
4784
4785        private void addUnwarrantedOptimismHandlerLabel(final List<Type> localTypes, final Label label) {
4786            final String lvarTypesDescriptor = getLvarTypesDescriptor(localTypes);
4787            final Map<String, Collection<Label>> unwarrantedOptimismHandlers = lc.getUnwarrantedOptimismHandlers();
4788            Collection<Label> labels = unwarrantedOptimismHandlers.get(lvarTypesDescriptor);
4789            if(labels == null) {
4790                labels = new LinkedList<>();
4791                unwarrantedOptimismHandlers.put(lvarTypesDescriptor, labels);
4792            }
4793            method.markLabelAsOptimisticCatchHandler(label, localTypes.size());
4794            labels.add(label);
4795        }
4796
4797        abstract void loadStack();
4798
4799        // Make sure that whatever indy call site you emit from this method uses {@code getCallSiteFlagsOptimistic(node)}
4800        // or otherwise ensure optimistic flag is correctly set in the call site, otherwise it doesn't make much sense
4801        // to use OptimisticExpression for emitting it.
4802        abstract void consumeStack();
4803
4804        /**
4805         * Emits the correct dynamic getter code. Normally just delegates to method emitter, except when the target
4806         * expression is optimistic, and the desired type is narrower than the optimistic type. In that case, it'll emit a
4807         * dynamic getter with its original optimistic type, and explicitly insert a narrowing conversion. This way we can
4808         * preserve the optimism of the values even if they're subsequently immediately coerced into a narrower type. This
4809         * is beneficial because in this case we can still presume that since the original getter was optimistic, the
4810         * conversion has no side effects.
4811         * @param name the name of the property being get
4812         * @param flags call site flags
4813         * @param isMethod whether we're preferably retrieving a function
4814         * @return the current method emitter
4815         */
4816        MethodEmitter dynamicGet(final String name, final int flags, final boolean isMethod, final boolean isIndex) {
4817            if(isOptimistic) {
4818                return method.dynamicGet(getOptimisticCoercedType(), name, getOptimisticFlags(flags), isMethod, isIndex);
4819            }
4820            return method.dynamicGet(resultBounds.within(expression.getType()), name, nonOptimisticFlags(flags), isMethod, isIndex);
4821        }
4822
4823        MethodEmitter dynamicGetIndex(final int flags, final boolean isMethod) {
4824            if(isOptimistic) {
4825                return method.dynamicGetIndex(getOptimisticCoercedType(), getOptimisticFlags(flags), isMethod);
4826            }
4827            return method.dynamicGetIndex(resultBounds.within(expression.getType()), nonOptimisticFlags(flags), isMethod);
4828        }
4829
4830        MethodEmitter dynamicCall(final int argCount, final int flags, final String msg) {
4831            if (isOptimistic) {
4832                return method.dynamicCall(getOptimisticCoercedType(), argCount, getOptimisticFlags(flags), msg);
4833            }
4834            return method.dynamicCall(resultBounds.within(expression.getType()), argCount, nonOptimisticFlags(flags), msg);
4835        }
4836
4837        int getOptimisticFlags(final int flags) {
4838            return flags | CALLSITE_OPTIMISTIC | (optimistic.getProgramPoint() << CALLSITE_PROGRAM_POINT_SHIFT); //encode program point in high bits
4839        }
4840
4841        int getProgramPoint() {
4842            return isOptimistic ? optimistic.getProgramPoint() : INVALID_PROGRAM_POINT;
4843        }
4844
4845        void convertOptimisticReturnValue() {
4846            if (isOptimistic) {
4847                final Type optimisticType = getOptimisticCoercedType();
4848                if(!optimisticType.isObject()) {
4849                    method.load(optimistic.getProgramPoint());
4850                    if(optimisticType.isInteger()) {
4851                        method.invoke(ENSURE_INT);
4852                    } else if(optimisticType.isLong()) {
4853                        method.invoke(ENSURE_LONG);
4854                    } else if(optimisticType.isNumber()) {
4855                        method.invoke(ENSURE_NUMBER);
4856                    } else {
4857                        throw new AssertionError(optimisticType);
4858                    }
4859                }
4860            }
4861        }
4862
4863        void replaceCompileTimeProperty() {
4864            final IdentNode identNode = (IdentNode)expression;
4865            final String name = identNode.getSymbol().getName();
4866            if (CompilerConstants.__FILE__.name().equals(name)) {
4867                replaceCompileTimeProperty(getCurrentSource().getName());
4868            } else if (CompilerConstants.__DIR__.name().equals(name)) {
4869                replaceCompileTimeProperty(getCurrentSource().getBase());
4870            } else if (CompilerConstants.__LINE__.name().equals(name)) {
4871                replaceCompileTimeProperty(getCurrentSource().getLine(identNode.position()));
4872            }
4873        }
4874
4875        /**
4876         * When an ident with name __FILE__, __DIR__, or __LINE__ is loaded, we'll try to look it up as any other
4877         * identifier. However, if it gets all the way up to the Global object, it will send back a special value that
4878         * represents a placeholder for these compile-time location properties. This method will generate code that loads
4879         * the value of the compile-time location property and then invokes a method in Global that will replace the
4880         * placeholder with the value. Effectively, if the symbol for these properties is defined anywhere in the lexical
4881         * scope, they take precedence, but if they aren't, then they resolve to the compile-time location property.
4882         * @param propertyValue the actual value of the property
4883         */
4884        private void replaceCompileTimeProperty(final Object propertyValue) {
4885            assert method.peekType().isObject();
4886            if(propertyValue instanceof String || propertyValue == null) {
4887                method.load((String)propertyValue);
4888            } else if(propertyValue instanceof Integer) {
4889                method.load(((Integer)propertyValue));
4890                method.convert(Type.OBJECT);
4891            } else {
4892                throw new AssertionError();
4893            }
4894            globalReplaceLocationPropertyPlaceholder();
4895            convertOptimisticReturnValue();
4896        }
4897
4898        /**
4899         * Returns the type that should be used as the return type of the dynamic invocation that is emitted as the code
4900         * for the current optimistic operation. If the type bounds is exact boolean or narrower than the expression's
4901         * optimistic type, then the optimistic type is returned, otherwise the coercing type. Effectively, this method
4902         * allows for moving the coercion into the optimistic type when it won't adversely affect the optimistic
4903         * evaluation semantics, and for preserving the optimistic type and doing a separate coercion when it would
4904         * affect it.
4905         * @return
4906         */
4907        private Type getOptimisticCoercedType() {
4908            final Type optimisticType = expression.getType();
4909            assert resultBounds.widest.widerThan(optimisticType);
4910            final Type narrowest = resultBounds.narrowest;
4911
4912            if(narrowest.isBoolean() || narrowest.narrowerThan(optimisticType)) {
4913                assert !optimisticType.isObject();
4914                return optimisticType;
4915            }
4916            assert !narrowest.isObject();
4917            return narrowest;
4918        }
4919    }
4920
4921    private static boolean isOptimistic(final Optimistic optimistic) {
4922        if(!optimistic.canBeOptimistic()) {
4923            return false;
4924        }
4925        final Expression expr = (Expression)optimistic;
4926        return expr.getType().narrowerThan(expr.getWidestOperationType());
4927    }
4928
4929    private static boolean everyLocalLoadIsValid(final int[] loads, final int localCount) {
4930        for (final int load : loads) {
4931            if(load < 0 || load >= localCount) {
4932                return false;
4933            }
4934        }
4935        return true;
4936    }
4937
4938    private static boolean everyStackValueIsLocalLoad(final int[] loads) {
4939        for (final int load : loads) {
4940            if(load == Label.Stack.NON_LOAD) {
4941                return false;
4942            }
4943        }
4944        return true;
4945    }
4946
4947    private String getLvarTypesDescriptor(final List<Type> localVarTypes) {
4948        final int count = localVarTypes.size();
4949        final StringBuilder desc = new StringBuilder(count);
4950        for(int i = 0; i < count;) {
4951            i += appendType(desc, localVarTypes.get(i));
4952        }
4953        return method.markSymbolBoundariesInLvarTypesDescriptor(desc.toString());
4954    }
4955
4956    private static int appendType(final StringBuilder b, final Type t) {
4957        b.append(t.getBytecodeStackType());
4958        return t.getSlots();
4959    }
4960
4961    private static int countSymbolsInLvarTypeDescriptor(final String lvarTypeDescriptor) {
4962        int count = 0;
4963        for(int i = 0; i < lvarTypeDescriptor.length(); ++i) {
4964            if(Character.isUpperCase(lvarTypeDescriptor.charAt(i))) {
4965                ++count;
4966            }
4967        }
4968        return count;
4969
4970    }
4971    /**
4972     * Generates all the required {@code UnwarrantedOptimismException} handlers for the current function. The employed
4973     * strategy strives to maximize code reuse. Every handler constructs an array to hold the local variables, then
4974     * fills in some trailing part of the local variables (those for which it has a unique suffix in the descriptor),
4975     * then jumps to a handler for a prefix that's shared with other handlers. A handler that fills up locals up to
4976     * position 0 will not jump to a prefix handler (as it has no prefix), but instead end with constructing and
4977     * throwing a {@code RewriteException}. Since we lexicographically sort the entries, we only need to check every
4978     * entry to its immediately preceding one for longest matching prefix.
4979     * @return true if there is at least one exception handler
4980     */
4981    private boolean generateUnwarrantedOptimismExceptionHandlers(final FunctionNode fn) {
4982        if(!useOptimisticTypes()) {
4983            return false;
4984        }
4985
4986        // Take the mapping of lvarSpecs -> labels, and turn them into a descending lexicographically sorted list of
4987        // handler specifications.
4988        final Map<String, Collection<Label>> unwarrantedOptimismHandlers = lc.popUnwarrantedOptimismHandlers();
4989        if(unwarrantedOptimismHandlers.isEmpty()) {
4990            return false;
4991        }
4992
4993        method.lineNumber(0);
4994
4995        final List<OptimismExceptionHandlerSpec> handlerSpecs = new ArrayList<>(unwarrantedOptimismHandlers.size() * 4/3);
4996        for(final String spec: unwarrantedOptimismHandlers.keySet()) {
4997            handlerSpecs.add(new OptimismExceptionHandlerSpec(spec, true));
4998        }
4999        Collections.sort(handlerSpecs, Collections.reverseOrder());
5000
5001        // Map of local variable specifications to labels for populating the array for that local variable spec.
5002        final Map<String, Label> delegationLabels = new HashMap<>();
5003
5004        // Do everything in a single pass over the handlerSpecs list. Note that the list can actually grow as we're
5005        // passing through it as we might add new prefix handlers into it, so can't hoist size() outside of the loop.
5006        for(int handlerIndex = 0; handlerIndex < handlerSpecs.size(); ++handlerIndex) {
5007            final OptimismExceptionHandlerSpec spec = handlerSpecs.get(handlerIndex);
5008            final String lvarSpec = spec.lvarSpec;
5009            if(spec.catchTarget) {
5010                assert !method.isReachable();
5011                // Start a catch block and assign the labels for this lvarSpec with it.
5012                method._catch(unwarrantedOptimismHandlers.get(lvarSpec));
5013                // This spec is a catch target, so emit array creation code. The length of the array is the number of
5014                // symbols - the number of uppercase characters.
5015                method.load(countSymbolsInLvarTypeDescriptor(lvarSpec));
5016                method.newarray(Type.OBJECT_ARRAY);
5017            }
5018            if(spec.delegationTarget) {
5019                // If another handler can delegate to this handler as its prefix, then put a jump target here for the
5020                // shared code (after the array creation code, which is never shared).
5021                method.label(delegationLabels.get(lvarSpec)); // label must exist
5022            }
5023
5024            final boolean lastHandler = handlerIndex == handlerSpecs.size() - 1;
5025
5026            int lvarIndex;
5027            final int firstArrayIndex;
5028            final int firstLvarIndex;
5029            Label delegationLabel;
5030            final String commonLvarSpec;
5031            if(lastHandler) {
5032                // Last handler block, doesn't delegate to anything.
5033                lvarIndex = 0;
5034                firstLvarIndex = 0;
5035                firstArrayIndex = 0;
5036                delegationLabel = null;
5037                commonLvarSpec = null;
5038            } else {
5039                // Not yet the last handler block, will definitely delegate to another handler; let's figure out which
5040                // one. It can be an already declared handler further down the list, or it might need to declare a new
5041                // prefix handler.
5042
5043                // Since we're lexicographically ordered, the common prefix handler is defined by the common prefix of
5044                // this handler and the next handler on the list.
5045                final int nextHandlerIndex = handlerIndex + 1;
5046                final String nextLvarSpec = handlerSpecs.get(nextHandlerIndex).lvarSpec;
5047                commonLvarSpec = commonPrefix(lvarSpec, nextLvarSpec);
5048                // We don't chop symbols in half
5049                assert Character.isUpperCase(commonLvarSpec.charAt(commonLvarSpec.length() - 1));
5050
5051                // Let's find if we already have a declaration for such handler, or we need to insert it.
5052                {
5053                    boolean addNewHandler = true;
5054                    int commonHandlerIndex = nextHandlerIndex;
5055                    for(; commonHandlerIndex < handlerSpecs.size(); ++commonHandlerIndex) {
5056                        final OptimismExceptionHandlerSpec forwardHandlerSpec = handlerSpecs.get(commonHandlerIndex);
5057                        final String forwardLvarSpec = forwardHandlerSpec.lvarSpec;
5058                        if(forwardLvarSpec.equals(commonLvarSpec)) {
5059                            // We already have a handler for the common prefix.
5060                            addNewHandler = false;
5061                            // Make sure we mark it as a delegation target.
5062                            forwardHandlerSpec.delegationTarget = true;
5063                            break;
5064                        } else if(!forwardLvarSpec.startsWith(commonLvarSpec)) {
5065                            break;
5066                        }
5067                    }
5068                    if(addNewHandler) {
5069                        // We need to insert a common prefix handler. Note handlers created with catchTarget == false
5070                        // will automatically have delegationTarget == true (because that's the only reason for their
5071                        // existence).
5072                        handlerSpecs.add(commonHandlerIndex, new OptimismExceptionHandlerSpec(commonLvarSpec, false));
5073                    }
5074                }
5075
5076                firstArrayIndex = countSymbolsInLvarTypeDescriptor(commonLvarSpec);
5077                lvarIndex = 0;
5078                for(int j = 0; j < commonLvarSpec.length(); ++j) {
5079                    lvarIndex += CodeGeneratorLexicalContext.getTypeForSlotDescriptor(commonLvarSpec.charAt(j)).getSlots();
5080                }
5081                firstLvarIndex = lvarIndex;
5082
5083                // Create a delegation label if not already present
5084                delegationLabel = delegationLabels.get(commonLvarSpec);
5085                if(delegationLabel == null) {
5086                    // uo_pa == "unwarranted optimism, populate array"
5087                    delegationLabel = new Label("uo_pa_" + commonLvarSpec);
5088                    delegationLabels.put(commonLvarSpec, delegationLabel);
5089                }
5090            }
5091
5092            // Load local variables handled by this handler on stack
5093            int args = 0;
5094            boolean symbolHadValue = false;
5095            for(int typeIndex = commonLvarSpec == null ? 0 : commonLvarSpec.length(); typeIndex < lvarSpec.length(); ++typeIndex) {
5096                final char typeDesc = lvarSpec.charAt(typeIndex);
5097                final Type lvarType = CodeGeneratorLexicalContext.getTypeForSlotDescriptor(typeDesc);
5098                if (!lvarType.isUnknown()) {
5099                    method.load(lvarType, lvarIndex);
5100                    symbolHadValue = true;
5101                    args++;
5102                } else if(typeDesc == 'U' && !symbolHadValue) {
5103                    // Symbol boundary with undefined last value. Check if all previous values for this symbol were also
5104                    // undefined; if so, emit one explicit Undefined. This serves to ensure that we're emiting exactly
5105                    // one value for every symbol that uses local slots. While we could in theory ignore symbols that
5106                    // are undefined (in other words, dead) at the point where this exception was thrown, unfortunately
5107                    // we can't do it in practice. The reason for this is that currently our liveness analysis is
5108                    // coarse (it can determine whether a symbol has not been read with a particular type anywhere in
5109                    // the function being compiled, but that's it), and a symbol being promoted to Object due to a
5110                    // deoptimization will suddenly show up as "live for Object type", and previously dead U->O
5111                    // conversions on loop entries will suddenly become alive in the deoptimized method which will then
5112                    // expect a value for that slot in its continuation handler. If we had precise liveness analysis, we
5113                    // could go back to excluding known dead symbols from the payload of the RewriteException.
5114                    if(method.peekType() == Type.UNDEFINED) {
5115                        method.dup();
5116                    } else {
5117                        method.loadUndefined(Type.OBJECT);
5118                    }
5119                    args++;
5120                }
5121                if(Character.isUpperCase(typeDesc)) {
5122                    // Reached symbol boundary; reset flag for the next symbol.
5123                    symbolHadValue = false;
5124                }
5125                lvarIndex += lvarType.getSlots();
5126            }
5127            assert args > 0;
5128            // Delegate actual storing into array to an array populator utility method.
5129            //on the stack:
5130            // object array to be populated
5131            // start index
5132            // a lot of types
5133            method.dynamicArrayPopulatorCall(args + 1, firstArrayIndex);
5134            if(delegationLabel != null) {
5135                // We cascade to a prefix handler to fill out the rest of the local variables and throw the
5136                // RewriteException.
5137                assert !lastHandler;
5138                assert commonLvarSpec != null;
5139                // Must undefine the local variables that we have already processed for the sake of correct join on the
5140                // delegate label
5141                method.undefineLocalVariables(firstLvarIndex, true);
5142                final OptimismExceptionHandlerSpec nextSpec = handlerSpecs.get(handlerIndex + 1);
5143                // If the delegate immediately follows, and it's not a catch target (so it doesn't have array setup
5144                // code) don't bother emitting a jump, as we'd just jump to the next instruction.
5145                if(!nextSpec.lvarSpec.equals(commonLvarSpec) || nextSpec.catchTarget) {
5146                    method._goto(delegationLabel);
5147                }
5148            } else {
5149                assert lastHandler;
5150                // Nothing to delegate to, so this handler must create and throw the RewriteException.
5151                // At this point we have the UnwarrantedOptimismException and the Object[] with local variables on
5152                // stack. We need to create a RewriteException, push two references to it below the constructor
5153                // arguments, invoke the constructor, and throw the exception.
5154                loadConstant(getByteCodeSymbolNames(fn));
5155                if (isRestOf()) {
5156                    loadConstant(getContinuationEntryPoints());
5157                    method.invoke(CREATE_REWRITE_EXCEPTION_REST_OF);
5158                } else {
5159                    method.invoke(CREATE_REWRITE_EXCEPTION);
5160                }
5161                method.athrow();
5162            }
5163        }
5164        return true;
5165    }
5166
5167    private static String[] getByteCodeSymbolNames(final FunctionNode fn) {
5168        // Only names of local variables on the function level are captured. This information is used to reduce
5169        // deoptimizations, so as much as we can capture will help. We rely on the fact that function wide variables are
5170        // all live all the time, so the array passed to rewrite exception contains one element for every slotted symbol
5171        // here.
5172        final List<String> names = new ArrayList<>();
5173        for (final Symbol symbol: fn.getBody().getSymbols()) {
5174            if (symbol.hasSlot()) {
5175                if (symbol.isScope()) {
5176                    // slot + scope can only be true for parameters
5177                    assert symbol.isParam();
5178                    names.add(null);
5179                } else {
5180                    names.add(symbol.getName());
5181                }
5182            }
5183        }
5184        return names.toArray(new String[names.size()]);
5185    }
5186
5187    private static String commonPrefix(final String s1, final String s2) {
5188        final int l1 = s1.length();
5189        final int l = Math.min(l1, s2.length());
5190        int lms = -1; // last matching symbol
5191        for(int i = 0; i < l; ++i) {
5192            final char c1 = s1.charAt(i);
5193            if(c1 != s2.charAt(i)) {
5194                return s1.substring(0, lms + 1);
5195            } else if(Character.isUpperCase(c1)) {
5196                lms = i;
5197            }
5198        }
5199        return l == l1 ? s1 : s2;
5200    }
5201
5202    private static class OptimismExceptionHandlerSpec implements Comparable<OptimismExceptionHandlerSpec> {
5203        private final String lvarSpec;
5204        private final boolean catchTarget;
5205        private boolean delegationTarget;
5206
5207        OptimismExceptionHandlerSpec(final String lvarSpec, final boolean catchTarget) {
5208            this.lvarSpec = lvarSpec;
5209            this.catchTarget = catchTarget;
5210            if(!catchTarget) {
5211                delegationTarget = true;
5212            }
5213        }
5214
5215        @Override
5216        public int compareTo(final OptimismExceptionHandlerSpec o) {
5217            return lvarSpec.compareTo(o.lvarSpec);
5218        }
5219
5220        @Override
5221        public String toString() {
5222            final StringBuilder b = new StringBuilder(64).append("[HandlerSpec ").append(lvarSpec);
5223            if(catchTarget) {
5224                b.append(", catchTarget");
5225            }
5226            if(delegationTarget) {
5227                b.append(", delegationTarget");
5228            }
5229            return b.append("]").toString();
5230        }
5231    }
5232
5233    private static class ContinuationInfo {
5234        private final Label handlerLabel;
5235        private Label targetLabel; // Label for the target instruction.
5236        int lvarCount;
5237        // Indices of local variables that need to be loaded on the stack when this node completes
5238        private int[] stackStoreSpec;
5239        // Types of values loaded on the stack
5240        private Type[] stackTypes;
5241        // If non-null, this node should perform the requisite type conversion
5242        private Type returnValueType;
5243        // If we are in the middle of an object literal initialization, we need to update the map
5244        private PropertyMap objectLiteralMap;
5245        // Object literal stack depth for object literal - not necessarily top if property is a tree
5246        private int objectLiteralStackDepth = -1;
5247        // The line number at the continuation point
5248        private int lineNumber;
5249        // The active catch label, in case the continuation point is in a try/catch block
5250        private Label catchLabel;
5251        // The number of scopes that need to be popped before control is transferred to the catch label.
5252        private int exceptionScopePops;
5253
5254        ContinuationInfo() {
5255            this.handlerLabel = new Label("continuation_handler");
5256        }
5257
5258        Label getHandlerLabel() {
5259            return handlerLabel;
5260        }
5261
5262        boolean hasTargetLabel() {
5263            return targetLabel != null;
5264        }
5265
5266        Label getTargetLabel() {
5267            return targetLabel;
5268        }
5269
5270        void setTargetLabel(final Label targetLabel) {
5271            this.targetLabel = targetLabel;
5272        }
5273
5274        int[] getStackStoreSpec() {
5275            return stackStoreSpec.clone();
5276        }
5277
5278        void setStackStoreSpec(final int[] stackStoreSpec) {
5279            this.stackStoreSpec = stackStoreSpec;
5280        }
5281
5282        Type[] getStackTypes() {
5283            return stackTypes.clone();
5284        }
5285
5286        void setStackTypes(final Type[] stackTypes) {
5287            this.stackTypes = stackTypes;
5288        }
5289
5290        Type getReturnValueType() {
5291            return returnValueType;
5292        }
5293
5294        void setReturnValueType(final Type returnValueType) {
5295            this.returnValueType = returnValueType;
5296        }
5297
5298        int getObjectLiteralStackDepth() {
5299            return objectLiteralStackDepth;
5300        }
5301
5302        void setObjectLiteralStackDepth(final int objectLiteralStackDepth) {
5303            this.objectLiteralStackDepth = objectLiteralStackDepth;
5304        }
5305
5306        PropertyMap getObjectLiteralMap() {
5307            return objectLiteralMap;
5308        }
5309
5310        void setObjectLiteralMap(final PropertyMap objectLiteralMap) {
5311            this.objectLiteralMap = objectLiteralMap;
5312        }
5313
5314        @Override
5315        public String toString() {
5316             return "[localVariableTypes=" + targetLabel.getStack().getLocalVariableTypesCopy() + ", stackStoreSpec=" +
5317                     Arrays.toString(stackStoreSpec) + ", returnValueType=" + returnValueType + "]";
5318        }
5319    }
5320
5321    private ContinuationInfo getContinuationInfo() {
5322        return continuationInfo;
5323    }
5324
5325    private void generateContinuationHandler() {
5326        if (!isRestOf()) {
5327            return;
5328        }
5329
5330        final ContinuationInfo ci = getContinuationInfo();
5331        method.label(ci.getHandlerLabel());
5332
5333        // There should never be an exception thrown from the continuation handler, but in case there is (meaning,
5334        // Nashorn has a bug), then line number 0 will be an indication of where it came from (line numbers are Uint16).
5335        method.lineNumber(0);
5336
5337        final Label.Stack stack = ci.getTargetLabel().getStack();
5338        final List<Type> lvarTypes = stack.getLocalVariableTypesCopy();
5339        final BitSet symbolBoundary = stack.getSymbolBoundaryCopy();
5340        final int lvarCount = ci.lvarCount;
5341
5342        final Type rewriteExceptionType = Type.typeFor(RewriteException.class);
5343        // Store the RewriteException into an unused local variable slot.
5344        method.load(rewriteExceptionType, 0);
5345        method.storeTemp(rewriteExceptionType, lvarCount);
5346        // Get local variable array
5347        method.load(rewriteExceptionType, 0);
5348        method.invoke(RewriteException.GET_BYTECODE_SLOTS);
5349        // Store local variables. Note that deoptimization might introduce new value types for existing local variables,
5350        // so we must use both liveLocals and symbolBoundary, as in some cases (when the continuation is inside of a try
5351        // block) we need to store the incoming value into multiple slots. The optimism exception handlers will have
5352        // exactly one array element for every symbol that uses bytecode storage. If in the originating method the value
5353        // was undefined, there will be an explicit Undefined value in the array.
5354        int arrayIndex = 0;
5355        for(int lvarIndex = 0; lvarIndex < lvarCount;) {
5356            final Type lvarType = lvarTypes.get(lvarIndex);
5357            if(!lvarType.isUnknown()) {
5358                method.dup();
5359                method.load(arrayIndex).arrayload();
5360                final Class<?> typeClass = lvarType.getTypeClass();
5361                // Deoptimization in array initializers can cause arrays to undergo component type widening
5362                if(typeClass == long[].class) {
5363                    method.load(rewriteExceptionType, lvarCount);
5364                    method.invoke(RewriteException.TO_LONG_ARRAY);
5365                } else if(typeClass == double[].class) {
5366                    method.load(rewriteExceptionType, lvarCount);
5367                    method.invoke(RewriteException.TO_DOUBLE_ARRAY);
5368                } else if(typeClass == Object[].class) {
5369                    method.load(rewriteExceptionType, lvarCount);
5370                    method.invoke(RewriteException.TO_OBJECT_ARRAY);
5371                } else {
5372                    if(!(typeClass.isPrimitive() || typeClass == Object.class)) {
5373                        // NOTE: this can only happen with dead stores. E.g. for the program "1; []; f();" in which the
5374                        // call to f() will deoptimize the call site, but it'll expect :return to have the type
5375                        // NativeArray. However, in the more optimal version, :return's only live type is int, therefore
5376                        // "{O}:return = []" is a dead store, and the variable will be sent into the continuation as
5377                        // Undefined, however NativeArray can't hold Undefined instance.
5378                        method.loadType(Type.getInternalName(typeClass));
5379                        method.invoke(RewriteException.INSTANCE_OR_NULL);
5380                    }
5381                    method.convert(lvarType);
5382                }
5383                method.storeHidden(lvarType, lvarIndex, false);
5384            }
5385            final int nextLvarIndex = lvarIndex + lvarType.getSlots();
5386            if(symbolBoundary.get(nextLvarIndex - 1)) {
5387                ++arrayIndex;
5388            }
5389            lvarIndex = nextLvarIndex;
5390        }
5391        if (AssertsEnabled.assertsEnabled()) {
5392            method.load(arrayIndex);
5393            method.invoke(RewriteException.ASSERT_ARRAY_LENGTH);
5394        } else {
5395            method.pop();
5396        }
5397
5398        final int[]   stackStoreSpec = ci.getStackStoreSpec();
5399        final Type[]  stackTypes     = ci.getStackTypes();
5400        final boolean isStackEmpty   = stackStoreSpec.length == 0;
5401        boolean replacedObjectLiteralMap = false;
5402        if(!isStackEmpty) {
5403            // Load arguments on the stack
5404            final int objectLiteralStackDepth = ci.getObjectLiteralStackDepth();
5405            for(int i = 0; i < stackStoreSpec.length; ++i) {
5406                final int slot = stackStoreSpec[i];
5407                method.load(lvarTypes.get(slot), slot);
5408                method.convert(stackTypes[i]);
5409                // stack: s0=object literal being initialized
5410                // change map of s0 so that the property we are initializing when we failed
5411                // is now ci.returnValueType
5412                if (i == objectLiteralStackDepth) {
5413                    method.dup();
5414                    assert ci.getObjectLiteralMap() != null;
5415                    assert ScriptObject.class.isAssignableFrom(method.peekType().getTypeClass()) : method.peekType().getTypeClass() + " is not a script object";
5416                    loadConstant(ci.getObjectLiteralMap());
5417                    method.invoke(ScriptObject.SET_MAP);
5418                    replacedObjectLiteralMap = true;
5419                }
5420            }
5421        }
5422        // Must have emitted the code for replacing the map of an object literal if we have a set object literal stack depth
5423        assert ci.getObjectLiteralStackDepth() == -1 || replacedObjectLiteralMap;
5424        // Load RewriteException back.
5425        method.load(rewriteExceptionType, lvarCount);
5426        // Get rid of the stored reference
5427        method.loadNull();
5428        method.storeHidden(Type.OBJECT, lvarCount);
5429        // Mark it dead
5430        method.markDeadSlots(lvarCount, Type.OBJECT.getSlots());
5431
5432        // Load return value on the stack
5433        method.invoke(RewriteException.GET_RETURN_VALUE);
5434
5435        final Type returnValueType = ci.getReturnValueType();
5436
5437        // Set up an exception handler for primitive type conversion of return value if needed
5438        boolean needsCatch = false;
5439        final Label targetCatchLabel = ci.catchLabel;
5440        Label _try = null;
5441        if(returnValueType.isPrimitive()) {
5442            // If the conversion throws an exception, we want to report the line number of the continuation point.
5443            method.lineNumber(ci.lineNumber);
5444
5445            if(targetCatchLabel != METHOD_BOUNDARY) {
5446                _try = new Label("");
5447                method.label(_try);
5448                needsCatch = true;
5449            }
5450        }
5451
5452        // Convert return value
5453        method.convert(returnValueType);
5454
5455        final int scopePopCount = needsCatch ? ci.exceptionScopePops : 0;
5456
5457        // Declare a try/catch for the conversion. If no scopes need to be popped until the target catch block, just
5458        // jump into it. Otherwise, we'll need to create a scope-popping catch block below.
5459        final Label catchLabel = scopePopCount > 0 ? new Label("") : targetCatchLabel;
5460        if(needsCatch) {
5461            final Label _end_try = new Label("");
5462            method.label(_end_try);
5463            method._try(_try, _end_try, catchLabel);
5464        }
5465
5466        // Jump to continuation point
5467        method._goto(ci.getTargetLabel());
5468
5469        // Make a scope-popping exception delegate if needed
5470        if(catchLabel != targetCatchLabel) {
5471            method.lineNumber(0);
5472            assert scopePopCount > 0;
5473            method._catch(catchLabel);
5474            popScopes(scopePopCount);
5475            method.uncheckedGoto(targetCatchLabel);
5476        }
5477    }
5478
5479    /**
5480     * Interface implemented by object creators that support splitting over multiple methods.
5481     */
5482    interface SplitLiteralCreator {
5483        /**
5484         * Generate code to populate a range of the literal object. A reference to the object
5485         * should be left on the stack when the method terminates.
5486         *
5487         * @param method the method emitter
5488         * @param type the type of the literal object
5489         * @param slot the local slot containing the literal object
5490         * @param start the start index (inclusive)
5491         * @param end the end index (exclusive)
5492         */
5493        void populateRange(MethodEmitter method, Type type, int slot, int start, int end);
5494    }
5495}
5496