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