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