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