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