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