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