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