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