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