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());
 347             method.invoke(ScriptRuntime.THROW_REFERENCE_ERROR);






 348         }
 349     }
 350 
 351     private boolean isRestOf() {
 352         return continuationEntryPoints != null;
 353     }
 354 
 355     private boolean isOptimisticOrRestOf() {
 356         return useOptimisticTypes() || isRestOf();
 357     }
 358 
 359     private boolean isCurrentContinuationEntryPoint(final int programPoint) {
 360         return isRestOf() && getCurrentContinuationEntryPoint() == programPoint;
 361     }
 362 
 363     private int[] getContinuationEntryPoints() {
 364         return isRestOf() ? continuationEntryPoints : null;
 365     }
 366 
 367     private int getCurrentContinuationEntryPoint() {
 368         return isRestOf() ? continuationEntryPoints[0] : INVALID_PROGRAM_POINT;
 369     }
 370 
 371     private boolean isContinuationEntryPoint(final int programPoint) {
 372         if (isRestOf()) {
 373             assert continuationEntryPoints != null;
 374             for (final int cep : continuationEntryPoints) {
 375                 if (cep == programPoint) {
 376                     return true;
 377                 }
 378             }
 379         }
 380         return false;
 381     }
 382 
 383     /**
 384      * Check if this symbol can be accessed directly with a putfield or getfield or dynamic load
 385      *
 386      * @param symbol symbol to check for fast scope
 387      * @return true if fast scope
 388      */
 389     private boolean isFastScope(final Symbol symbol) {
 390         if (!symbol.isScope()) {
 391             return false;
 392         }
 393 
 394         if (!lc.inDynamicScope()) {
 395             // If there's no with or eval in context, and the symbol is marked as scoped, it is fast scoped. Such a
 396             // symbol must either be global, or its defining block must need scope.
 397             assert symbol.isGlobal() || lc.getDefiningBlock(symbol).needsScope() : symbol.getName();
 398             return true;
 399         }
 400 
 401         if (symbol.isGlobal()) {
 402             // Shortcut: if there's a with or eval in context, globals can't be fast scoped
 403             return false;
 404         }
 405 
 406         // Otherwise, check if there's a dynamic scope between use of the symbol and its definition
 407         final String name = symbol.getName();
 408         boolean previousWasBlock = false;
 409         for (final Iterator<LexicalContextNode> it = lc.getAllNodes(); it.hasNext();) {
 410             final LexicalContextNode node = it.next();
 411             if (node instanceof Block) {
 412                 // If this block defines the symbol, then we can fast scope the symbol.
 413                 final Block block = (Block)node;
 414                 if (block.getExistingSymbol(name) == symbol) {
 415                     assert block.needsScope();
 416                     return true;
 417                 }
 418                 previousWasBlock = true;
 419             } else {
 420                 if (node instanceof WithNode && previousWasBlock || node instanceof FunctionNode && ((FunctionNode)node).needsDynamicScope()) {
 421                     // If we hit a scope that can have symbols introduced into it at run time before finding the defining
 422                     // block, the symbol can't be fast scoped. A WithNode only counts if we've immediately seen a block
 423                     // before - its block. Otherwise, we are currently processing the WithNode's expression, and that's
 424                     // obviously not subjected to introducing new symbols.
 425                     return false;
 426                 }
 427                 previousWasBlock = false;
 428             }
 429         }
 430         // Should've found the symbol defined in a block
 431         throw new AssertionError();
 432     }
 433 
 434     private MethodEmitter loadSharedScopeVar(final Type valueType, final Symbol symbol, final int flags) {
 435         assert !isOptimisticOrRestOf();
 436         if (isFastScope(symbol)) {
 437             method.load(getScopeProtoDepth(lc.getCurrentBlock(), symbol));
 438         } else {
 439             method.load(-1);
 440         }
 441         return lc.getScopeGet(unit, symbol, valueType, flags | CALLSITE_FAST_SCOPE).generateInvoke(method);
 442     }
 443 
 444     private class LoadScopeVar extends OptimisticOperation {
 445         final IdentNode identNode;
 446         private final int flags;
 447 
 448         LoadScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
 449             super(identNode, resultBounds);
 450             this.identNode = identNode;
 451             this.flags = flags;
 452         }
 453 
 454         @Override
 455         void loadStack() {
 456             method.loadCompilerConstant(SCOPE);
 457             getProto();
 458         }
 459 
 460         void getProto() {
 461             //empty
 462         }
 463 
 464         @Override
 465         void consumeStack() {
 466             // If this is either __FILE__, __DIR__, or __LINE__ then load the property initially as Object as we'd convert
 467             // it anyway for replaceLocationPropertyPlaceholder.
 468             if(identNode.isCompileTimePropertyName()) {
 469                 method.dynamicGet(Type.OBJECT, identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
 470                 replaceCompileTimeProperty();
 471             } else {
 472                 dynamicGet(identNode.getSymbol().getName(), flags, identNode.isFunction(), false);
 473             }
 474         }
 475     }
 476 
 477     private class LoadFastScopeVar extends LoadScopeVar {
 478         LoadFastScopeVar(final IdentNode identNode, final TypeBounds resultBounds, final int flags) {
 479             super(identNode, resultBounds, flags | CALLSITE_FAST_SCOPE);
 480         }
 481 
 482         @Override
 483         void getProto() {
 484             loadFastScopeProto(identNode.getSymbol(), false);
 485         }
 486     }
 487 
 488     private MethodEmitter storeFastScopeVar(final Symbol symbol, final int flags) {
 489         loadFastScopeProto(symbol, true);
 490         method.dynamicSet(symbol.getName(), flags | CALLSITE_FAST_SCOPE, false);
 491         return method;
 492     }
 493 
 494     private int getScopeProtoDepth(final Block startingBlock, final Symbol symbol) {
 495         //walk up the chain from starting block and when we bump into the current function boundary, add the external
 496         //information.
 497         final FunctionNode fn   = lc.getCurrentFunction();
 498         final int externalDepth = compiler.getScriptFunctionData(fn.getId()).getExternalSymbolDepth(symbol.getName());
 499 
 500         //count the number of scopes from this place to the start of the function
 501 
 502         final int internalDepth = FindScopeDepths.findInternalDepth(lc, fn, startingBlock, symbol);
 503         final int scopesToStart = FindScopeDepths.findScopesToStart(lc, fn, startingBlock);
 504         int depth = 0;
 505         if (internalDepth == -1) {
 506             depth = scopesToStart + externalDepth;
 507         } else {
 508             assert internalDepth <= scopesToStart;
 509             depth = internalDepth;
 510         }
 511 
 512         return depth;
 513     }
 514 
 515     private void loadFastScopeProto(final Symbol symbol, final boolean swap) {
 516         final int depth = getScopeProtoDepth(lc.getCurrentBlock(), symbol);
 517         assert depth != -1 : "Couldn't find scope depth for symbol " + symbol.getName() + " in " + lc.getCurrentFunction();
 518         if (depth > 0) {
 519             if (swap) {
 520                 method.swap();
 521             }
 522             for (int i = 0; i < depth; i++) {
 523                 method.invoke(ScriptObject.GET_PROTO);
 524             }
 525             if (swap) {
 526                 method.swap();
 527             }
 528         }
 529     }
 530 
 531     /**
 532      * Generate code that loads this node to the stack, not constraining its type
 533      *
 534      * @param expr node to load
 535      *
 536      * @return the method emitter used
 537      */
 538     private MethodEmitter loadExpressionUnbounded(final Expression expr) {
 539         return loadExpression(expr, TypeBounds.UNBOUNDED);
 540     }
 541 
 542     private MethodEmitter loadExpressionAsObject(final Expression expr) {
 543         return loadExpression(expr, TypeBounds.OBJECT);
 544     }
 545 
 546     MethodEmitter loadExpressionAsBoolean(final Expression expr) {
 547         return loadExpression(expr, TypeBounds.BOOLEAN);
 548     }
 549 
 550     // Test whether conversion from source to target involves a call of ES 9.1 ToPrimitive
 551     // with possible side effects from calling an object's toString or valueOf methods.
 552     private static boolean noToPrimitiveConversion(final Type source, final Type target) {
 553         // Object to boolean conversion does not cause ToPrimitive call
 554         return source.isJSPrimitive() || !target.isJSPrimitive() || target.isBoolean();
 555     }
 556 
 557     MethodEmitter loadBinaryOperands(final BinaryNode binaryNode) {
 558         return loadBinaryOperands(binaryNode.lhs(), binaryNode.rhs(), TypeBounds.UNBOUNDED.notWiderThan(binaryNode.getWidestOperandType()), false, false);
 559     }
 560 
 561     private MethodEmitter loadBinaryOperands(final Expression lhs, final Expression rhs, final TypeBounds explicitOperandBounds, final boolean baseAlreadyOnStack, final boolean forceConversionSeparation) {
 562         // ECMAScript 5.1 specification (sections 11.5-11.11 and 11.13) prescribes that when evaluating a binary
 563         // expression "LEFT op RIGHT", the order of operations must be: LOAD LEFT, LOAD RIGHT, CONVERT LEFT, CONVERT
 564         // RIGHT, EXECUTE OP. Unfortunately, doing it in this order defeats potential optimizations that arise when we
 565         // can combine a LOAD with a CONVERT operation (e.g. use a dynamic getter with the conversion target type as its
 566         // return value). What we do here is reorder LOAD RIGHT and CONVERT LEFT when possible; it is possible only when
 567         // we can prove that executing CONVERT LEFT can't have a side effect that changes the value of LOAD RIGHT.
 568         // Basically, if we know that either LEFT already is a primitive value, or does not have to be converted to
 569         // a primitive value, or RIGHT is an expression that loads without side effects, then we can do the
 570         // reordering and collapse LOAD/CONVERT into a single operation; otherwise we need to do the more costly
 571         // separate operations to preserve specification semantics.
 572 
 573         // Operands' load type should not be narrower than the narrowest of the individual operand types, nor narrower
 574         // than the lower explicit bound, but it should also not be wider than
 575         final Type lhsType = undefinedToNumber(lhs.getType());
 576         final Type rhsType = undefinedToNumber(rhs.getType());
 577         final Type narrowestOperandType = Type.narrowest(Type.widest(lhsType, rhsType), explicitOperandBounds.widest);
 578         final TypeBounds operandBounds = explicitOperandBounds.notNarrowerThan(narrowestOperandType);
 579         if (noToPrimitiveConversion(lhsType, explicitOperandBounds.widest) || rhs.isLocal()) {
 580             // Can reorder. We might still need to separate conversion, but at least we can do it with reordering
 581             if (forceConversionSeparation) {
 582                 // Can reorder, but can't move conversion into the operand as the operation depends on operands
 583                 // exact types for its overflow guarantees. E.g. with {L}{%I}expr1 {L}* {L}{%I}expr2 we are not allowed
 584                 // to merge {L}{%I} into {%L}, as that can cause subsequent overflows; test for JDK-8058610 contains
 585                 // concrete cases where this could happen.
 586                 final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
 587                 loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
 588                 method.convert(operandBounds.within(method.peekType()));
 589                 loadExpression(rhs, safeConvertBounds, false);
 590                 method.convert(operandBounds.within(method.peekType()));
 591             } else {
 592                 // Can reorder and move conversion into the operand. Combine load and convert into single operations.
 593                 loadExpression(lhs, operandBounds, baseAlreadyOnStack);
 594                 loadExpression(rhs, operandBounds, false);
 595             }
 596         } else {
 597             // Can't reorder. Load and convert separately.
 598             final TypeBounds safeConvertBounds = TypeBounds.UNBOUNDED.notNarrowerThan(narrowestOperandType);
 599             loadExpression(lhs, safeConvertBounds, baseAlreadyOnStack);
 600             final Type lhsLoadedType = method.peekType();
 601             loadExpression(rhs, safeConvertBounds, false);
 602             final Type convertedLhsType = operandBounds.within(method.peekType());
 603             if (convertedLhsType != lhsLoadedType) {
 604                 // Do it conditionally, so that if conversion is a no-op we don't introduce a SWAP, SWAP.
 605                 method.swap().convert(convertedLhsType).swap();
 606             }
 607             method.convert(operandBounds.within(method.peekType()));
 608         }
 609         assert Type.generic(method.peekType()) == operandBounds.narrowest;
 610         assert Type.generic(method.peekType(1)) == operandBounds.narrowest;
 611 
 612         return method;
 613     }
 614 
 615     private static final Type undefinedToNumber(final Type type) {
 616         return type == Type.UNDEFINED ? Type.NUMBER : type;
 617     }
 618 
 619     private static final class TypeBounds {
 620         final Type narrowest;
 621         final Type widest;
 622 
 623         static final TypeBounds UNBOUNDED = new TypeBounds(Type.UNKNOWN, Type.OBJECT);
 624         static final TypeBounds INT = exact(Type.INT);
 625         static final TypeBounds OBJECT = exact(Type.OBJECT);
 626         static final TypeBounds BOOLEAN = exact(Type.BOOLEAN);
 627 
 628         static TypeBounds exact(final Type type) {
 629             return new TypeBounds(type, type);
 630         }
 631 
 632         TypeBounds(final Type narrowest, final Type widest) {
 633             assert widest    != null && widest    != Type.UNDEFINED && widest != Type.UNKNOWN : widest;
 634             assert narrowest != null && narrowest != Type.UNDEFINED : narrowest;
 635             assert !narrowest.widerThan(widest) : narrowest + " wider than " + widest;
 636             assert !widest.narrowerThan(narrowest);
 637             this.narrowest = Type.generic(narrowest);
 638             this.widest = Type.generic(widest);
 639         }
 640 
 641         TypeBounds notNarrowerThan(final Type type) {
 642             return maybeNew(Type.narrowest(Type.widest(narrowest, type), widest), widest);
 643         }
 644 
 645         TypeBounds notWiderThan(final Type type) {
 646             return maybeNew(Type.narrowest(narrowest, type), Type.narrowest(widest, type));
 647         }
 648 
 649         boolean canBeNarrowerThan(final Type type) {
 650             return narrowest.narrowerThan(type);
 651         }
 652 
 653         TypeBounds maybeNew(final Type newNarrowest, final Type newWidest) {
 654             if(newNarrowest == narrowest && newWidest == widest) {
 655                 return this;
 656             }
 657             return new TypeBounds(newNarrowest, newWidest);
 658         }
 659 
 660         TypeBounds booleanToInt() {
 661             return maybeNew(CodeGenerator.booleanToInt(narrowest), CodeGenerator.booleanToInt(widest));
 662         }
 663 
 664         TypeBounds objectToNumber() {
 665             return maybeNew(CodeGenerator.objectToNumber(narrowest), CodeGenerator.objectToNumber(widest));
 666         }
 667 
 668         Type within(final Type type) {
 669             if(type.narrowerThan(narrowest)) {
 670                 return narrowest;
 671             }
 672             if(type.widerThan(widest)) {
 673                 return widest;
 674             }
 675             return type;
 676         }
 677 
 678         @Override
 679         public String toString() {
 680             return "[" + narrowest + ", " + widest + "]";
 681         }
 682     }
 683 
 684     private static Type booleanToInt(final Type t) {
 685         return t == Type.BOOLEAN ? Type.INT : t;
 686     }
 687 
 688     private static Type objectToNumber(final Type t) {
 689         return t.isObject() ? Type.NUMBER : t;
 690     }
 691 
 692     MethodEmitter loadExpressionAsType(final Expression expr, final Type type) {
 693         if(type == Type.BOOLEAN) {
 694             return loadExpressionAsBoolean(expr);
 695         } else if(type == Type.UNDEFINED) {
 696             assert expr.getType() == Type.UNDEFINED;
 697             return loadExpressionAsObject(expr);
 698         }
 699         // having no upper bound preserves semantics of optimistic operations in the expression (by not having them
 700         // converted early) and then applies explicit conversion afterwards.
 701         return loadExpression(expr, TypeBounds.UNBOUNDED.notNarrowerThan(type)).convert(type);
 702     }
 703 
 704     private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds) {
 705         return loadExpression(expr, resultBounds, false);
 706     }
 707 
 708     /**
 709      * Emits code for evaluating an expression and leaving its value on top of the stack, narrowing or widening it if
 710      * necessary.
 711      * @param expr the expression to load
 712      * @param resultBounds the incoming type bounds. The value on the top of the stack is guaranteed to not be of narrower
 713      * type than the narrowest bound, or wider type than the widest bound after it is loaded.
 714      * @param baseAlreadyOnStack true if the base of an access or index node is already on the stack. Used to avoid
 715      * double evaluation of bases in self-assignment expressions to access and index nodes. {@code Type.OBJECT} is used
 716      * to indicate the widest possible type.
 717      * @return the method emitter
 718      */
 719     private MethodEmitter loadExpression(final Expression expr, final TypeBounds resultBounds, final boolean baseAlreadyOnStack) {
 720 
 721         /*
 722          * The load may be of type IdentNode, e.g. "x", AccessNode, e.g. "x.y"
 723          * or IndexNode e.g. "x[y]". Both AccessNodes and IndexNodes are
 724          * BaseNodes and the logic for loading the base object is reused
 725          */
 726         final CodeGenerator codegen = this;
 727 
 728         final Node currentDiscard = codegen.lc.getCurrentDiscard();
 729         expr.accept(new NodeOperatorVisitor<LexicalContext>(new LexicalContext()) {
 730             @Override
 731             public boolean enterIdentNode(final IdentNode identNode) {
 732                 loadIdent(identNode, resultBounds);
 733                 return false;
 734             }
 735 
 736             @Override
 737             public boolean enterAccessNode(final AccessNode accessNode) {
 738                 new OptimisticOperation(accessNode, resultBounds) {
 739                     @Override
 740                     void loadStack() {
 741                         if (!baseAlreadyOnStack) {
 742                             loadExpressionAsObject(accessNode.getBase());
 743                         }
 744                         assert method.peekType().isObject();
 745                     }
 746                     @Override
 747                     void consumeStack() {
 748                         final int flags = getCallSiteFlags();
 749                         dynamicGet(accessNode.getProperty(), flags, accessNode.isFunction(), accessNode.isIndex());
 750                     }
 751                 }.emit(baseAlreadyOnStack ? 1 : 0);
 752                 return false;
 753             }
 754 
 755             @Override
 756             public boolean enterIndexNode(final IndexNode indexNode) {
 757                 new OptimisticOperation(indexNode, resultBounds) {
 758                     @Override
 759                     void loadStack() {
 760                         if (!baseAlreadyOnStack) {
 761                             loadExpressionAsObject(indexNode.getBase());
 762                             loadExpressionUnbounded(indexNode.getIndex());
 763                         }
 764                     }
 765                     @Override
 766                     void consumeStack() {
 767                         final int flags = getCallSiteFlags();
 768                         dynamicGetIndex(flags, indexNode.isFunction());
 769                     }
 770                 }.emit(baseAlreadyOnStack ? 2 : 0);
 771                 return false;
 772             }
 773 
 774             @Override
 775             public boolean enterFunctionNode(final FunctionNode functionNode) {
 776                 // function nodes will always leave a constructed function object on stack, no need to load the symbol
 777                 // separately as in enterDefault()
 778                 lc.pop(functionNode);
 779                 functionNode.accept(codegen);
 780                 // NOTE: functionNode.accept() will produce a different FunctionNode that we discard. This incidentally
 781                 // doesn't cause problems as we're never touching FunctionNode again after it's visited here - codegen
 782                 // is the last element in the compilation pipeline, the AST it produces is not used externally. So, we
 783                 // re-push the original functionNode.
 784                 lc.push(functionNode);
 785                 return false;
 786             }
 787 
 788             @Override
 789             public boolean enterASSIGN(final BinaryNode binaryNode) {

 790                 loadASSIGN(binaryNode);
 791                 return false;
 792             }
 793 
 794             @Override
 795             public boolean enterASSIGN_ADD(final BinaryNode binaryNode) {

 796                 loadASSIGN_ADD(binaryNode);
 797                 return false;
 798             }
 799 
 800             @Override
 801             public boolean enterASSIGN_BIT_AND(final BinaryNode binaryNode) {

 802                 loadASSIGN_BIT_AND(binaryNode);
 803                 return false;
 804             }
 805 
 806             @Override
 807             public boolean enterASSIGN_BIT_OR(final BinaryNode binaryNode) {

 808                 loadASSIGN_BIT_OR(binaryNode);
 809                 return false;
 810             }
 811 
 812             @Override
 813             public boolean enterASSIGN_BIT_XOR(final BinaryNode binaryNode) {

 814                 loadASSIGN_BIT_XOR(binaryNode);
 815                 return false;
 816             }
 817 
 818             @Override
 819             public boolean enterASSIGN_DIV(final BinaryNode binaryNode) {

 820                 loadASSIGN_DIV(binaryNode);
 821                 return false;
 822             }
 823 
 824             @Override
 825             public boolean enterASSIGN_MOD(final BinaryNode binaryNode) {

 826                 loadASSIGN_MOD(binaryNode);
 827                 return false;
 828             }
 829 
 830             @Override
 831             public boolean enterASSIGN_MUL(final BinaryNode binaryNode) {

 832                 loadASSIGN_MUL(binaryNode);
 833                 return false;
 834             }
 835 
 836             @Override
 837             public boolean enterASSIGN_SAR(final BinaryNode binaryNode) {

 838                 loadASSIGN_SAR(binaryNode);
 839                 return false;
 840             }
 841 
 842             @Override
 843             public boolean enterASSIGN_SHL(final BinaryNode binaryNode) {

 844                 loadASSIGN_SHL(binaryNode);
 845                 return false;
 846             }
 847 
 848             @Override
 849             public boolean enterASSIGN_SHR(final BinaryNode binaryNode) {

 850                 loadASSIGN_SHR(binaryNode);
 851                 return false;
 852             }
 853 
 854             @Override
 855             public boolean enterASSIGN_SUB(final BinaryNode binaryNode) {

 856                 loadASSIGN_SUB(binaryNode);
 857                 return false;
 858             }
 859 
 860             @Override
 861             public boolean enterCallNode(final CallNode callNode) {
 862                 return loadCallNode(callNode, resultBounds);
 863             }
 864 
 865             @Override
 866             public boolean enterLiteralNode(final LiteralNode<?> literalNode) {
 867                 loadLiteral(literalNode, resultBounds);
 868                 return false;
 869             }
 870 
 871             @Override
 872             public boolean enterTernaryNode(final TernaryNode ternaryNode) {
 873                 loadTernaryNode(ternaryNode, resultBounds);
 874                 return false;
 875             }
 876 
 877             @Override
 878             public boolean enterADD(final BinaryNode binaryNode) {
 879                 loadADD(binaryNode, resultBounds);
 880                 return false;
 881             }
 882 
 883             @Override
 884             public boolean enterSUB(final UnaryNode unaryNode) {
 885                 loadSUB(unaryNode, resultBounds);
 886                 return false;
 887             }
 888 
 889             @Override
 890             public boolean enterSUB(final BinaryNode binaryNode) {
 891                 loadSUB(binaryNode, resultBounds);
 892                 return false;
 893             }
 894 
 895             @Override
 896             public boolean enterMUL(final BinaryNode binaryNode) {
 897                 loadMUL(binaryNode, resultBounds);
 898                 return false;
 899             }
 900 
 901             @Override
 902             public boolean enterDIV(final BinaryNode binaryNode) {
 903                 loadDIV(binaryNode, resultBounds);
 904                 return false;
 905             }
 906 
 907             @Override
 908             public boolean enterMOD(final BinaryNode binaryNode) {
 909                 loadMOD(binaryNode, resultBounds);
 910                 return false;
 911             }
 912 
 913             @Override
 914             public boolean enterSAR(final BinaryNode binaryNode) {
 915                 loadSAR(binaryNode);
 916                 return false;
 917             }
 918 
 919             @Override
 920             public boolean enterSHL(final BinaryNode binaryNode) {
 921                 loadSHL(binaryNode);
 922                 return false;
 923             }
 924 
 925             @Override
 926             public boolean enterSHR(final BinaryNode binaryNode) {
 927                 loadSHR(binaryNode);
 928                 return false;
 929             }
 930 
 931             @Override
 932             public boolean enterCOMMALEFT(final BinaryNode binaryNode) {
 933                 loadCOMMALEFT(binaryNode, resultBounds);
 934                 return false;
 935             }
 936 
 937             @Override
 938             public boolean enterCOMMARIGHT(final BinaryNode binaryNode) {
 939                 loadCOMMARIGHT(binaryNode, resultBounds);
 940                 return false;
 941             }
 942 
 943             @Override
 944             public boolean enterAND(final BinaryNode binaryNode) {
 945                 loadAND_OR(binaryNode, resultBounds, true);
 946                 return false;
 947             }
 948 
 949             @Override
 950             public boolean enterOR(final BinaryNode binaryNode) {
 951                 loadAND_OR(binaryNode, resultBounds, false);
 952                 return false;
 953             }
 954 
 955             @Override
 956             public boolean enterNOT(final UnaryNode unaryNode) {
 957                 loadNOT(unaryNode);
 958                 return false;
 959             }
 960 
 961             @Override
 962             public boolean enterADD(final UnaryNode unaryNode) {
 963                 loadADD(unaryNode, resultBounds);
 964                 return false;
 965             }
 966 
 967             @Override
 968             public boolean enterBIT_NOT(final UnaryNode unaryNode) {
 969                 loadBIT_NOT(unaryNode);
 970                 return false;
 971             }
 972 
 973             @Override
 974             public boolean enterBIT_AND(final BinaryNode binaryNode) {
 975                 loadBIT_AND(binaryNode);
 976                 return false;
 977             }
 978 
 979             @Override
 980             public boolean enterBIT_OR(final BinaryNode binaryNode) {
 981                 loadBIT_OR(binaryNode);
 982                 return false;
 983             }
 984 
 985             @Override
 986             public boolean enterBIT_XOR(final BinaryNode binaryNode) {
 987                 loadBIT_XOR(binaryNode);
 988                 return false;
 989             }
 990 
 991             @Override
 992             public boolean enterVOID(final UnaryNode unaryNode) {
 993                 loadVOID(unaryNode, resultBounds);
 994                 return false;
 995             }
 996 
 997             @Override
 998             public boolean enterEQ(final BinaryNode binaryNode) {
 999                 loadCmp(binaryNode, Condition.EQ);
1000                 return false;
1001             }
1002 
1003             @Override
1004             public boolean enterEQ_STRICT(final BinaryNode binaryNode) {
1005                 loadCmp(binaryNode, Condition.EQ);
1006                 return false;
1007             }
1008 
1009             @Override
1010             public boolean enterGE(final BinaryNode binaryNode) {
1011                 loadCmp(binaryNode, Condition.GE);
1012                 return false;
1013             }
1014 
1015             @Override
1016             public boolean enterGT(final BinaryNode binaryNode) {
1017                 loadCmp(binaryNode, Condition.GT);
1018                 return false;
1019             }
1020 
1021             @Override
1022             public boolean enterLE(final BinaryNode binaryNode) {
1023                 loadCmp(binaryNode, Condition.LE);
1024                 return false;
1025             }
1026 
1027             @Override
1028             public boolean enterLT(final BinaryNode binaryNode) {
1029                 loadCmp(binaryNode, Condition.LT);
1030                 return false;
1031             }
1032 
1033             @Override
1034             public boolean enterNE(final BinaryNode binaryNode) {
1035                 loadCmp(binaryNode, Condition.NE);
1036                 return false;
1037             }
1038 
1039             @Override
1040             public boolean enterNE_STRICT(final BinaryNode binaryNode) {
1041                 loadCmp(binaryNode, Condition.NE);
1042                 return false;
1043             }
1044 
1045             @Override
1046             public boolean enterObjectNode(final ObjectNode objectNode) {
1047                 loadObjectNode(objectNode);
1048                 return false;
1049             }
1050 
1051             @Override
1052             public boolean enterRuntimeNode(final RuntimeNode runtimeNode) {
1053                 loadRuntimeNode(runtimeNode);
1054                 return false;
1055             }
1056 
1057             @Override
1058             public boolean enterNEW(final UnaryNode unaryNode) {
1059                 loadNEW(unaryNode);
1060                 return false;
1061             }
1062 
1063             @Override
1064             public boolean enterDECINC(final UnaryNode unaryNode) {

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