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