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