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