1 /* 2 * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.invoke; 27 28 import jdk.internal.perf.PerfCounter; 29 import jdk.internal.vm.annotation.DontInline; 30 import jdk.internal.vm.annotation.Hidden; 31 import jdk.internal.vm.annotation.Stable; 32 import sun.invoke.util.Wrapper; 33 34 import java.lang.annotation.ElementType; 35 import java.lang.annotation.Retention; 36 import java.lang.annotation.RetentionPolicy; 37 import java.lang.annotation.Target; 38 import java.lang.reflect.Method; 39 import java.util.Arrays; 40 import java.util.HashMap; 41 42 import static java.lang.invoke.LambdaForm.BasicType.*; 43 import static java.lang.invoke.MethodHandleNatives.Constants.*; 44 import static java.lang.invoke.MethodHandleStatics.*; 45 46 /** 47 * The symbolic, non-executable form of a method handle's invocation semantics. 48 * It consists of a series of names. 49 * The first N (N=arity) names are parameters, 50 * while any remaining names are temporary values. 51 * Each temporary specifies the application of a function to some arguments. 52 * The functions are method handles, while the arguments are mixes of 53 * constant values and local names. 54 * The result of the lambda is defined as one of the names, often the last one. 55 * <p> 56 * Here is an approximate grammar: 57 * <blockquote><pre>{@code 58 * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}" 59 * ArgName = "a" N ":" T 60 * TempName = "t" N ":" T "=" Function "(" Argument* ");" 61 * Function = ConstantValue 62 * Argument = NameRef | ConstantValue 63 * Result = NameRef | "void" 64 * NameRef = "a" N | "t" N 65 * N = (any whole number) 66 * T = "L" | "I" | "J" | "F" | "D" | "V" 67 * }</pre></blockquote> 68 * Names are numbered consecutively from left to right starting at zero. 69 * (The letters are merely a taste of syntax sugar.) 70 * Thus, the first temporary (if any) is always numbered N (where N=arity). 71 * Every occurrence of a name reference in an argument list must refer to 72 * a name previously defined within the same lambda. 73 * A lambda has a void result if and only if its result index is -1. 74 * If a temporary has the type "V", it cannot be the subject of a NameRef, 75 * even though possesses a number. 76 * Note that all reference types are erased to "L", which stands for {@code Object}. 77 * All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}. 78 * The other types stand for the usual primitive types. 79 * <p> 80 * Function invocation closely follows the static rules of the Java verifier. 81 * Arguments and return values must exactly match when their "Name" types are 82 * considered. 83 * Conversions are allowed only if they do not change the erased type. 84 * <ul> 85 * <li>L = Object: casts are used freely to convert into and out of reference types 86 * <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments}) 87 * <li>J = long: no implicit conversions 88 * <li>F = float: no implicit conversions 89 * <li>D = double: no implicit conversions 90 * <li>V = void: a function result may be void if and only if its Name is of type "V" 91 * </ul> 92 * Although implicit conversions are not allowed, explicit ones can easily be 93 * encoded by using temporary expressions which call type-transformed identity functions. 94 * <p> 95 * Examples: 96 * <blockquote><pre>{@code 97 * (a0:J)=>{ a0 } 98 * == identity(long) 99 * (a0:I)=>{ t1:V = System.out#println(a0); void } 100 * == System.out#println(int) 101 * (a0:L)=>{ t1:V = System.out#println(a0); a0 } 102 * == identity, with printing side-effect 103 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 104 * t3:L = BoundMethodHandle#target(a0); 105 * t4:L = MethodHandle#invoke(t3, t2, a1); t4 } 106 * == general invoker for unary insertArgument combination 107 * (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0); 108 * t3:L = MethodHandle#invoke(t2, a1); 109 * t4:L = FilterMethodHandle#target(a0); 110 * t5:L = MethodHandle#invoke(t4, t3); t5 } 111 * == general invoker for unary filterArgument combination 112 * (a0:L, a1:L)=>{ ...(same as previous example)... 113 * t5:L = MethodHandle#invoke(t4, t3, a1); t5 } 114 * == general invoker for unary/unary foldArgument combination 115 * (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 } 116 * == invoker for identity method handle which performs i2l 117 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0); 118 * t3:L = Class#cast(t2,a1); t3 } 119 * == invoker for identity method handle which performs cast 120 * }</pre></blockquote> 121 * <p> 122 * @author John Rose, JSR 292 EG 123 */ 124 class LambdaForm { 125 final int arity; 126 final int result; 127 final boolean forceInline; 128 final MethodHandle customized; 129 @Stable final Name[] names; 130 final Kind kind; 131 MemberName vmentry; // low-level behavior, or null if not yet prepared 132 private boolean isCompiled; 133 134 // Either a LambdaForm cache (managed by LambdaFormEditor) or a link to uncustomized version (for customized LF) 135 volatile Object transformCache; 136 137 public static final int VOID_RESULT = -1, LAST_RESULT = -2; 138 139 enum BasicType { 140 L_TYPE('L', Object.class, Wrapper.OBJECT), // all reference types 141 I_TYPE('I', int.class, Wrapper.INT), 142 J_TYPE('J', long.class, Wrapper.LONG), 143 F_TYPE('F', float.class, Wrapper.FLOAT), 144 D_TYPE('D', double.class, Wrapper.DOUBLE), // all primitive types 145 V_TYPE('V', void.class, Wrapper.VOID); // not valid in all contexts 146 147 static final @Stable BasicType[] ALL_TYPES = BasicType.values(); 148 static final @Stable BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1); 149 150 static final int ARG_TYPE_LIMIT = ARG_TYPES.length; 151 static final int TYPE_LIMIT = ALL_TYPES.length; 152 153 // Derived int constants, which (unlike the enums) can be constant folded. 154 // We can remove them when JDK-8161245 is fixed. 155 static final byte 156 L_TYPE_NUM = (byte) L_TYPE.ordinal(), 157 I_TYPE_NUM = (byte) I_TYPE.ordinal(), 158 J_TYPE_NUM = (byte) J_TYPE.ordinal(), 159 F_TYPE_NUM = (byte) F_TYPE.ordinal(), 160 D_TYPE_NUM = (byte) D_TYPE.ordinal(), 161 V_TYPE_NUM = (byte) V_TYPE.ordinal(); 162 163 final char btChar; 164 final Class<?> btClass; 165 final Wrapper btWrapper; 166 167 private BasicType(char btChar, Class<?> btClass, Wrapper wrapper) { 168 this.btChar = btChar; 169 this.btClass = btClass; 170 this.btWrapper = wrapper; 171 } 172 173 char basicTypeChar() { 174 return btChar; 175 } 176 Class<?> basicTypeClass() { 177 return btClass; 178 } 179 Wrapper basicTypeWrapper() { 180 return btWrapper; 181 } 182 int basicTypeSlots() { 183 return btWrapper.stackSlots(); 184 } 185 186 static BasicType basicType(byte type) { 187 return ALL_TYPES[type]; 188 } 189 static BasicType basicType(char type) { 190 return switch (type) { 191 case 'L' -> L_TYPE; 192 case 'I' -> I_TYPE; 193 case 'J' -> J_TYPE; 194 case 'F' -> F_TYPE; 195 case 'D' -> D_TYPE; 196 case 'V' -> V_TYPE; 197 // all subword types are represented as ints 198 case 'Z', 'B', 'S', 'C' -> I_TYPE; 199 default -> throw newInternalError("Unknown type char: '" + type + "'"); 200 }; 201 } 202 static BasicType basicType(Wrapper type) { 203 char c = type.basicTypeChar(); 204 return basicType(c); 205 } 206 static BasicType basicType(Class<?> type) { 207 if (!type.isPrimitive()) return L_TYPE; 208 return basicType(Wrapper.forPrimitiveType(type)); 209 } 210 static int[] basicTypeOrds(BasicType[] types) { 211 if (types == null) { 212 return null; 213 } 214 int[] a = new int[types.length]; 215 for(int i = 0; i < types.length; ++i) { 216 a[i] = types[i].ordinal(); 217 } 218 return a; 219 } 220 221 static char basicTypeChar(Class<?> type) { 222 return basicType(type).btChar; 223 } 224 225 static byte[] basicTypesOrd(Class<?>[] types) { 226 byte[] ords = new byte[types.length]; 227 for (int i = 0; i < ords.length; i++) { 228 ords[i] = (byte)basicType(types[i]).ordinal(); 229 } 230 return ords; 231 } 232 233 static boolean isBasicTypeChar(char c) { 234 return "LIJFDV".indexOf(c) >= 0; 235 } 236 static boolean isArgBasicTypeChar(char c) { 237 return "LIJFD".indexOf(c) >= 0; 238 } 239 240 static { assert(checkBasicType()); } 241 private static boolean checkBasicType() { 242 for (int i = 0; i < ARG_TYPE_LIMIT; i++) { 243 assert ARG_TYPES[i].ordinal() == i; 244 assert ARG_TYPES[i] == ALL_TYPES[i]; 245 } 246 for (int i = 0; i < TYPE_LIMIT; i++) { 247 assert ALL_TYPES[i].ordinal() == i; 248 } 249 assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE; 250 assert !Arrays.asList(ARG_TYPES).contains(V_TYPE); 251 return true; 252 } 253 } 254 255 enum Kind { 256 GENERIC("invoke"), 257 ZERO("zero"), 258 IDENTITY("identity"), 259 BOUND_REINVOKER("BMH.reinvoke", "reinvoke"), 260 REINVOKER("MH.reinvoke", "reinvoke"), 261 DELEGATE("MH.delegate", "delegate"), 262 EXACT_LINKER("MH.invokeExact_MT", "invokeExact_MT"), 263 EXACT_INVOKER("MH.exactInvoker", "exactInvoker"), 264 GENERIC_LINKER("MH.invoke_MT", "invoke_MT"), 265 GENERIC_INVOKER("MH.invoker", "invoker"), 266 LINK_TO_TARGET_METHOD("linkToTargetMethod"), 267 LINK_TO_CALL_SITE("linkToCallSite"), 268 DIRECT_INVOKE_VIRTUAL("DMH.invokeVirtual", "invokeVirtual"), 269 DIRECT_INVOKE_SPECIAL("DMH.invokeSpecial", "invokeSpecial"), 270 DIRECT_INVOKE_SPECIAL_IFC("DMH.invokeSpecialIFC", "invokeSpecialIFC"), 271 DIRECT_INVOKE_STATIC("DMH.invokeStatic", "invokeStatic"), 272 DIRECT_NEW_INVOKE_SPECIAL("DMH.newInvokeSpecial", "newInvokeSpecial"), 273 DIRECT_INVOKE_INTERFACE("DMH.invokeInterface", "invokeInterface"), 274 DIRECT_INVOKE_STATIC_INIT("DMH.invokeStaticInit", "invokeStaticInit"), 275 GET_REFERENCE("getReference"), 276 PUT_REFERENCE("putReference"), 277 GET_REFERENCE_VOLATILE("getReferenceVolatile"), 278 PUT_REFERENCE_VOLATILE("putReferenceVolatile"), 279 GET_VALUE("getValue"), 280 PUT_VALUE("putValue"), 281 GET_VALUE_VOLATILE("getValueVolatile"), 282 PUT_VALUE_VOLATILE("putValueVolatile"), 283 GET_INT("getInt"), 284 PUT_INT("putInt"), 285 GET_INT_VOLATILE("getIntVolatile"), 286 PUT_INT_VOLATILE("putIntVolatile"), 287 GET_BOOLEAN("getBoolean"), 288 PUT_BOOLEAN("putBoolean"), 289 GET_BOOLEAN_VOLATILE("getBooleanVolatile"), 290 PUT_BOOLEAN_VOLATILE("putBooleanVolatile"), 291 GET_BYTE("getByte"), 292 PUT_BYTE("putByte"), 293 GET_BYTE_VOLATILE("getByteVolatile"), 294 PUT_BYTE_VOLATILE("putByteVolatile"), 295 GET_CHAR("getChar"), 296 PUT_CHAR("putChar"), 297 GET_CHAR_VOLATILE("getCharVolatile"), 298 PUT_CHAR_VOLATILE("putCharVolatile"), 299 GET_SHORT("getShort"), 300 PUT_SHORT("putShort"), 301 GET_SHORT_VOLATILE("getShortVolatile"), 302 PUT_SHORT_VOLATILE("putShortVolatile"), 303 GET_LONG("getLong"), 304 PUT_LONG("putLong"), 305 GET_LONG_VOLATILE("getLongVolatile"), 306 PUT_LONG_VOLATILE("putLongVolatile"), 307 GET_FLOAT("getFloat"), 308 PUT_FLOAT("putFloat"), 309 GET_FLOAT_VOLATILE("getFloatVolatile"), 310 PUT_FLOAT_VOLATILE("putFloatVolatile"), 311 GET_DOUBLE("getDouble"), 312 PUT_DOUBLE("putDouble"), 313 GET_DOUBLE_VOLATILE("getDoubleVolatile"), 314 PUT_DOUBLE_VOLATILE("putDoubleVolatile"), 315 TRY_FINALLY("tryFinally"), 316 TABLE_SWITCH("tableSwitch"), 317 COLLECT("collect"), 318 COLLECTOR("collector"), 319 CONVERT("convert"), 320 SPREAD("spread"), 321 LOOP("loop"), 322 FIELD("field"), 323 GUARD("guard"), 324 GUARD_WITH_CATCH("guardWithCatch"), 325 VARHANDLE_EXACT_INVOKER("VH.exactInvoker"), 326 VARHANDLE_INVOKER("VH.invoker", "invoker"), 327 VARHANDLE_LINKER("VH.invoke_MT", "invoke_MT"); 328 329 final String defaultLambdaName; 330 final String methodName; 331 332 private Kind(String defaultLambdaName) { 333 this(defaultLambdaName, defaultLambdaName); 334 } 335 336 private Kind(String defaultLambdaName, String methodName) { 337 this.defaultLambdaName = defaultLambdaName; 338 this.methodName = methodName; 339 } 340 } 341 342 LambdaForm(int arity, Name[] names, int result) { 343 this(arity, names, result, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC); 344 } 345 LambdaForm(int arity, Name[] names, int result, Kind kind) { 346 this(arity, names, result, /*forceInline=*/true, /*customized=*/null, kind); 347 } 348 LambdaForm(int arity, Name[] names, int result, boolean forceInline, MethodHandle customized) { 349 this(arity, names, result, forceInline, customized, Kind.GENERIC); 350 } 351 LambdaForm(int arity, Name[] names, int result, boolean forceInline, MethodHandle customized, Kind kind) { 352 assert(namesOK(arity, names)); 353 this.arity = arity; 354 this.result = fixResult(result, names); 355 this.names = names.clone(); 356 this.forceInline = forceInline; 357 this.customized = customized; 358 this.kind = kind; 359 int maxOutArity = normalize(); 360 if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) { 361 // Cannot use LF interpreter on very high arity expressions. 362 assert(maxOutArity <= MethodType.MAX_JVM_ARITY); 363 compileToBytecode(); 364 } 365 } 366 LambdaForm(int arity, Name[] names) { 367 this(arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC); 368 } 369 LambdaForm(int arity, Name[] names, Kind kind) { 370 this(arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, kind); 371 } 372 LambdaForm(int arity, Name[] names, boolean forceInline, Kind kind) { 373 this(arity, names, LAST_RESULT, forceInline, /*customized=*/null, kind); 374 } 375 376 private static Name[] buildNames(Name[] formals, Name[] temps, Name result) { 377 int arity = formals.length; 378 int length = arity + temps.length + (result == null ? 0 : 1); 379 Name[] names = Arrays.copyOf(formals, length); 380 System.arraycopy(temps, 0, names, arity, temps.length); 381 if (result != null) 382 names[length - 1] = result; 383 return names; 384 } 385 386 private LambdaForm(MethodType mt) { 387 // Make a blank lambda form, which returns a constant zero or null. 388 // It is used as a template for managing the invocation of similar forms that are non-empty. 389 // Called only from getPreparedForm. 390 this.arity = mt.parameterCount(); 391 this.result = (mt.returnType() == void.class || mt.returnType() == Void.class) ? -1 : arity; 392 this.names = buildEmptyNames(arity, mt, result == -1); 393 this.forceInline = true; 394 this.customized = null; 395 this.kind = Kind.ZERO; 396 assert(nameRefsAreLegal()); 397 assert(isEmpty()); 398 String sig = null; 399 assert(isValidSignature(sig = basicTypeSignature())); 400 assert(sig.equals(basicTypeSignature())) : sig + " != " + basicTypeSignature(); 401 } 402 403 private static Name[] buildEmptyNames(int arity, MethodType mt, boolean isVoid) { 404 Name[] names = arguments(isVoid ? 0 : 1, mt); 405 if (!isVoid) { 406 Name zero = new Name(constantZero(basicType(mt.returnType()))); 407 names[arity] = zero.newIndex(arity); 408 } 409 return names; 410 } 411 412 private static int fixResult(int result, Name[] names) { 413 if (result == LAST_RESULT) 414 result = names.length - 1; // might still be void 415 if (result >= 0 && names[result].type == V_TYPE) 416 result = VOID_RESULT; 417 return result; 418 } 419 420 static boolean debugNames() { 421 return DEBUG_NAME_COUNTERS != null; 422 } 423 424 static void associateWithDebugName(LambdaForm form, String name) { 425 assert (debugNames()); 426 synchronized (DEBUG_NAMES) { 427 DEBUG_NAMES.put(form, name); 428 } 429 } 430 431 String lambdaName() { 432 if (DEBUG_NAMES != null) { 433 synchronized (DEBUG_NAMES) { 434 String name = DEBUG_NAMES.get(this); 435 if (name == null) { 436 name = generateDebugName(); 437 } 438 return name; 439 } 440 } 441 return kind.defaultLambdaName; 442 } 443 444 private String generateDebugName() { 445 assert (debugNames()); 446 String debugNameStem = kind.defaultLambdaName; 447 Integer ctr = DEBUG_NAME_COUNTERS.getOrDefault(debugNameStem, 0); 448 DEBUG_NAME_COUNTERS.put(debugNameStem, ctr + 1); 449 StringBuilder buf = new StringBuilder(debugNameStem); 450 int leadingZero = buf.length(); 451 buf.append((int) ctr); 452 for (int i = buf.length() - leadingZero; i < 3; i++) { 453 buf.insert(leadingZero, '0'); 454 } 455 buf.append('_'); 456 buf.append(basicTypeSignature()); 457 String name = buf.toString(); 458 associateWithDebugName(this, name); 459 return name; 460 } 461 462 private static boolean namesOK(int arity, Name[] names) { 463 for (int i = 0; i < names.length; i++) { 464 Name n = names[i]; 465 assert(n != null) : "n is null"; 466 if (i < arity) 467 assert( n.isParam()) : n + " is not param at " + i; 468 else 469 assert(!n.isParam()) : n + " is param at " + i; 470 } 471 return true; 472 } 473 474 /** Customize LambdaForm for a particular MethodHandle */ 475 LambdaForm customize(MethodHandle mh) { 476 if (customized == mh) { 477 return this; 478 } 479 LambdaForm customForm = new LambdaForm(arity, names, result, forceInline, mh, kind); 480 if (COMPILE_THRESHOLD >= 0 && isCompiled) { 481 // If shared LambdaForm has been compiled, compile customized version as well. 482 customForm.compileToBytecode(); 483 } 484 customForm.transformCache = this; // LambdaFormEditor should always use uncustomized form. 485 return customForm; 486 } 487 488 /** Get uncustomized flavor of the LambdaForm */ 489 LambdaForm uncustomize() { 490 if (customized == null) { 491 return this; 492 } 493 assert(transformCache != null); // Customized LambdaForm should always has a link to uncustomized version. 494 LambdaForm uncustomizedForm = (LambdaForm)transformCache; 495 if (COMPILE_THRESHOLD >= 0 && isCompiled) { 496 // If customized LambdaForm has been compiled, compile uncustomized version as well. 497 uncustomizedForm.compileToBytecode(); 498 } 499 return uncustomizedForm; 500 } 501 502 /** Renumber and/or replace params so that they are interned and canonically numbered. 503 * @return maximum argument list length among the names (since we have to pass over them anyway) 504 */ 505 private int normalize() { 506 Name[] oldNames = null; 507 int maxOutArity = 0; 508 int changesStart = 0; 509 for (int i = 0; i < names.length; i++) { 510 Name n = names[i]; 511 if (!n.initIndex(i)) { 512 if (oldNames == null) { 513 oldNames = names.clone(); 514 changesStart = i; 515 } 516 names[i] = n.cloneWithIndex(i); 517 } 518 if (n.arguments != null && maxOutArity < n.arguments.length) 519 maxOutArity = n.arguments.length; 520 } 521 if (oldNames != null) { 522 int startFixing = arity; 523 if (startFixing <= changesStart) 524 startFixing = changesStart+1; 525 for (int i = startFixing; i < names.length; i++) { 526 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i); 527 names[i] = fixed.newIndex(i); 528 } 529 } 530 assert(nameRefsAreLegal()); 531 int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT); 532 boolean needIntern = false; 533 for (int i = 0; i < maxInterned; i++) { 534 Name n = names[i], n2 = internArgument(n); 535 if (n != n2) { 536 names[i] = n2; 537 needIntern = true; 538 } 539 } 540 if (needIntern) { 541 for (int i = arity; i < names.length; i++) { 542 names[i].internArguments(); 543 } 544 } 545 assert(nameRefsAreLegal()); 546 return maxOutArity; 547 } 548 549 /** 550 * Check that all embedded Name references are localizable to this lambda, 551 * and are properly ordered after their corresponding definitions. 552 * <p> 553 * Note that a Name can be local to multiple lambdas, as long as 554 * it possesses the same index in each use site. 555 * This allows Name references to be freely reused to construct 556 * fresh lambdas, without confusion. 557 */ 558 boolean nameRefsAreLegal() { 559 assert(arity >= 0 && arity <= names.length); 560 assert(result >= -1 && result < names.length); 561 // Do all names possess an index consistent with their local definition order? 562 for (int i = 0; i < arity; i++) { 563 Name n = names[i]; 564 assert(n.index() == i) : Arrays.asList(n.index(), i); 565 assert(n.isParam()); 566 } 567 // Also, do all local name references 568 for (int i = arity; i < names.length; i++) { 569 Name n = names[i]; 570 assert(n.index() == i); 571 for (Object arg : n.arguments) { 572 if (arg instanceof Name n2) { 573 int i2 = n2.index; 574 assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length; 575 assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this); 576 assert(i2 < i); // ref must come after def! 577 } 578 } 579 } 580 return true; 581 } 582 583 /** Invoke this form on the given arguments. */ 584 // final Object invoke(Object... args) throws Throwable { 585 // // NYI: fit this into the fast path? 586 // return interpretWithArguments(args); 587 // } 588 589 /** Report the return type. */ 590 BasicType returnType() { 591 if (result < 0) return V_TYPE; 592 Name n = names[result]; 593 return n.type; 594 } 595 596 /** Report the N-th argument type. */ 597 BasicType parameterType(int n) { 598 return parameter(n).type; 599 } 600 601 /** Report the N-th argument name. */ 602 Name parameter(int n) { 603 Name param = names[n]; 604 assert(n < arity && param.isParam()); 605 return param; 606 } 607 608 /** Report the N-th argument type constraint. */ 609 Object parameterConstraint(int n) { 610 return parameter(n).constraint; 611 } 612 613 /** Report the arity. */ 614 int arity() { 615 return arity; 616 } 617 618 /** Report the number of expressions (non-parameter names). */ 619 int expressionCount() { 620 return names.length - arity; 621 } 622 623 /** Return the method type corresponding to my basic type signature. */ 624 MethodType methodType() { 625 Class<?>[] ptypes = new Class<?>[arity]; 626 for (int i = 0; i < arity; ++i) { 627 ptypes[i] = parameterType(i).btClass; 628 } 629 return MethodType.makeImpl(returnType().btClass, ptypes, true); 630 } 631 632 /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */ 633 final String basicTypeSignature() { 634 StringBuilder buf = new StringBuilder(arity() + 3); 635 for (int i = 0, a = arity(); i < a; i++) 636 buf.append(parameterType(i).basicTypeChar()); 637 return buf.append('_').append(returnType().basicTypeChar()).toString(); 638 } 639 static int signatureArity(String sig) { 640 assert(isValidSignature(sig)); 641 return sig.indexOf('_'); 642 } 643 static boolean isValidSignature(String sig) { 644 int arity = sig.indexOf('_'); 645 if (arity < 0) return false; // must be of the form *_* 646 int siglen = sig.length(); 647 if (siglen != arity + 2) return false; // *_X 648 for (int i = 0; i < siglen; i++) { 649 if (i == arity) continue; // skip '_' 650 char c = sig.charAt(i); 651 if (c == 'V') 652 return (i == siglen - 1 && arity == siglen - 2); 653 if (!isArgBasicTypeChar(c)) return false; // must be [LIJFD] 654 } 655 return true; // [LIJFD]*_[LIJFDV] 656 } 657 658 /** 659 * Check if i-th name is a call to MethodHandleImpl.selectAlternative. 660 */ 661 boolean isSelectAlternative(int pos) { 662 // selectAlternative idiom: 663 // t_{n}:L=MethodHandleImpl.selectAlternative(...) 664 // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 665 if (pos+1 >= names.length) return false; 666 Name name0 = names[pos]; 667 Name name1 = names[pos+1]; 668 return name0.refersTo(MethodHandleImpl.class, "selectAlternative") && 669 name1.isInvokeBasic() && 670 name1.lastUseIndex(name0) == 0 && // t_{n+1}:?=MethodHandle.invokeBasic(t_{n}, ...) 671 lastUseIndex(name0) == pos+1; // t_{n} is local: used only in t_{n+1} 672 } 673 674 private boolean isMatchingIdiom(int pos, String idiomName, int nArgs) { 675 if (pos+2 >= names.length) return false; 676 Name name0 = names[pos]; 677 Name name1 = names[pos+1]; 678 Name name2 = names[pos+2]; 679 return name1.refersTo(MethodHandleImpl.class, idiomName) && 680 name0.isInvokeBasic() && 681 name2.isInvokeBasic() && 682 name1.lastUseIndex(name0) == nArgs && // t_{n+1}:L=MethodHandleImpl.<invoker>(<args>, t_{n}); 683 lastUseIndex(name0) == pos+1 && // t_{n} is local: used only in t_{n+1} 684 name2.lastUseIndex(name1) == 1 && // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 685 lastUseIndex(name1) == pos+2; // t_{n+1} is local: used only in t_{n+2} 686 } 687 688 /** 689 * Check if i-th name is a start of GuardWithCatch idiom. 690 */ 691 boolean isGuardWithCatch(int pos) { 692 // GuardWithCatch idiom: 693 // t_{n}:L=MethodHandle.invokeBasic(...) 694 // t_{n+1}:L=MethodHandleImpl.guardWithCatch(*, *, *, t_{n}); 695 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 696 return isMatchingIdiom(pos, "guardWithCatch", 3); 697 } 698 699 /** 700 * Check if i-th name is a start of the tryFinally idiom. 701 */ 702 boolean isTryFinally(int pos) { 703 // tryFinally idiom: 704 // t_{n}:L=MethodHandle.invokeBasic(...) 705 // t_{n+1}:L=MethodHandleImpl.tryFinally(*, *, t_{n}) 706 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 707 return isMatchingIdiom(pos, "tryFinally", 2); 708 } 709 710 /** 711 * Check if i-th name is a start of the tableSwitch idiom. 712 */ 713 boolean isTableSwitch(int pos) { 714 // tableSwitch idiom: 715 // t_{n}:L=MethodHandle.invokeBasic(...) // args 716 // t_{n+1}:L=MethodHandleImpl.tableSwitch(*, *, *, t_{n}) 717 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 718 if (pos + 2 >= names.length) return false; 719 720 final int POS_COLLECT_ARGS = pos; 721 final int POS_TABLE_SWITCH = pos + 1; 722 final int POS_UNBOX_RESULT = pos + 2; 723 724 Name collectArgs = names[POS_COLLECT_ARGS]; 725 Name tableSwitch = names[POS_TABLE_SWITCH]; 726 Name unboxResult = names[POS_UNBOX_RESULT]; 727 return tableSwitch.refersTo(MethodHandleImpl.class, "tableSwitch") && 728 collectArgs.isInvokeBasic() && 729 unboxResult.isInvokeBasic() && 730 tableSwitch.lastUseIndex(collectArgs) == 3 && // t_{n+1}:L=MethodHandleImpl.<invoker>(*, *, *, t_{n}); 731 lastUseIndex(collectArgs) == POS_TABLE_SWITCH && // t_{n} is local: used only in t_{n+1} 732 unboxResult.lastUseIndex(tableSwitch) == 1 && // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 733 lastUseIndex(tableSwitch) == POS_UNBOX_RESULT; // t_{n+1} is local: used only in t_{n+2} 734 } 735 736 /** 737 * Check if i-th name is a start of the loop idiom. 738 */ 739 boolean isLoop(int pos) { 740 // loop idiom: 741 // t_{n}:L=MethodHandle.invokeBasic(...) 742 // t_{n+1}:L=MethodHandleImpl.loop(types, *, t_{n}) 743 // t_{n+2}:?=MethodHandle.invokeBasic(*, t_{n+1}) 744 return isMatchingIdiom(pos, "loop", 2); 745 } 746 747 /* 748 * Code generation issues: 749 * 750 * Compiled LFs should be reusable in general. 751 * The biggest issue is how to decide when to pull a name into 752 * the bytecode, versus loading a reified form from the MH data. 753 * 754 * For example, an asType wrapper may require execution of a cast 755 * after a call to a MH. The target type of the cast can be placed 756 * as a constant in the LF itself. This will force the cast type 757 * to be compiled into the bytecodes and native code for the MH. 758 * Or, the target type of the cast can be erased in the LF, and 759 * loaded from the MH data. (Later on, if the MH as a whole is 760 * inlined, the data will flow into the inlined instance of the LF, 761 * as a constant, and the end result will be an optimal cast.) 762 * 763 * This erasure of cast types can be done with any use of 764 * reference types. It can also be done with whole method 765 * handles. Erasing a method handle might leave behind 766 * LF code that executes correctly for any MH of a given 767 * type, and load the required MH from the enclosing MH's data. 768 * Or, the erasure might even erase the expected MT. 769 * 770 * Also, for direct MHs, the MemberName of the target 771 * could be erased, and loaded from the containing direct MH. 772 * As a simple case, a LF for all int-valued non-static 773 * field getters would perform a cast on its input argument 774 * (to non-constant base type derived from the MemberName) 775 * and load an integer value from the input object 776 * (at a non-constant offset also derived from the MemberName). 777 * Such MN-erased LFs would be inlinable back to optimized 778 * code, whenever a constant enclosing DMH is available 779 * to supply a constant MN from its data. 780 * 781 * The main problem here is to keep LFs reasonably generic, 782 * while ensuring that hot spots will inline good instances. 783 * "Reasonably generic" means that we don't end up with 784 * repeated versions of bytecode or machine code that do 785 * not differ in their optimized form. Repeated versions 786 * of machine would have the undesirable overheads of 787 * (a) redundant compilation work and (b) extra I$ pressure. 788 * To control repeated versions, we need to be ready to 789 * erase details from LFs and move them into MH data, 790 * whenever those details are not relevant to significant 791 * optimization. "Significant" means optimization of 792 * code that is actually hot. 793 * 794 * Achieving this may require dynamic splitting of MHs, by replacing 795 * a generic LF with a more specialized one, on the same MH, 796 * if (a) the MH is frequently executed and (b) the MH cannot 797 * be inlined into a containing caller, such as an invokedynamic. 798 * 799 * Compiled LFs that are no longer used should be GC-able. 800 * If they contain non-BCP references, they should be properly 801 * interlinked with the class loader(s) that their embedded types 802 * depend on. This probably means that reusable compiled LFs 803 * will be tabulated (indexed) on relevant class loaders, 804 * or else that the tables that cache them will have weak links. 805 */ 806 807 /** 808 * Make this LF directly executable, as part of a MethodHandle. 809 * Invariant: Every MH which is invoked must prepare its LF 810 * before invocation. 811 * (In principle, the JVM could do this very lazily, 812 * as a sort of pre-invocation linkage step.) 813 */ 814 public void prepare() { 815 if (COMPILE_THRESHOLD == 0 && !forceInterpretation() && !isCompiled) { 816 compileToBytecode(); 817 } 818 if (this.vmentry != null) { 819 // already prepared (e.g., a primitive DMH invoker form) 820 return; 821 } 822 MethodType mtype = methodType(); 823 LambdaForm prep = mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET); 824 if (prep == null) { 825 assert (isValidSignature(basicTypeSignature())); 826 prep = new LambdaForm(mtype); 827 prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(mtype); 828 prep = mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep); 829 } 830 this.vmentry = prep.vmentry; 831 // TO DO: Maybe add invokeGeneric, invokeWithArguments 832 } 833 834 private static @Stable PerfCounter LF_FAILED; 835 836 private static PerfCounter failedCompilationCounter() { 837 if (LF_FAILED == null) { 838 LF_FAILED = PerfCounter.newPerfCounter("java.lang.invoke.failedLambdaFormCompilations"); 839 } 840 return LF_FAILED; 841 } 842 843 /** Generate optimizable bytecode for this form. */ 844 void compileToBytecode() { 845 if (forceInterpretation()) { 846 return; // this should not be compiled 847 } 848 if (vmentry != null && isCompiled) { 849 return; // already compiled somehow 850 } 851 852 // Obtain the invoker MethodType outside of the following try block. 853 // This ensures that an IllegalArgumentException is directly thrown if the 854 // type would have 256 or more parameters 855 MethodType invokerType = methodType(); 856 assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType)); 857 try { 858 vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType); 859 if (TRACE_INTERPRETER) 860 traceInterpreter("compileToBytecode", this); 861 isCompiled = true; 862 } catch (InvokerBytecodeGenerator.BytecodeGenerationException bge) { 863 // bytecode generation failed - mark this LambdaForm as to be run in interpretation mode only 864 invocationCounter = -1; 865 failedCompilationCounter().increment(); 866 if (LOG_LF_COMPILATION_FAILURE) { 867 System.out.println("LambdaForm compilation failed: " + this); 868 bge.printStackTrace(System.out); 869 } 870 } catch (Error e) { 871 // Pass through any error 872 throw e; 873 } catch (Exception e) { 874 // Wrap any exception 875 throw newInternalError(this.toString(), e); 876 } 877 } 878 879 // The next few routines are called only from assert expressions 880 // They verify that the built-in invokers process the correct raw data types. 881 private static boolean argumentTypesMatch(String sig, Object[] av) { 882 int arity = signatureArity(sig); 883 assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity; 884 assert(av[0] instanceof MethodHandle) : "av[0] not instance of MethodHandle: " + av[0]; 885 MethodHandle mh = (MethodHandle) av[0]; 886 MethodType mt = mh.type(); 887 assert(mt.parameterCount() == arity-1); 888 for (int i = 0; i < av.length; i++) { 889 Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1)); 890 assert(valueMatches(basicType(sig.charAt(i)), pt, av[i])); 891 } 892 return true; 893 } 894 private static boolean valueMatches(BasicType tc, Class<?> type, Object x) { 895 // The following line is needed because (...)void method handles can use non-void invokers 896 if (type == void.class) tc = V_TYPE; // can drop any kind of value 897 assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type); 898 switch (tc) { 899 case I_TYPE: assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break; 900 case J_TYPE: assert x instanceof Long : "instanceof Long: " + x; break; 901 case F_TYPE: assert x instanceof Float : "instanceof Float: " + x; break; 902 case D_TYPE: assert x instanceof Double : "instanceof Double: " + x; break; 903 case L_TYPE: assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break; 904 case V_TYPE: break; // allow anything here; will be dropped 905 default: assert(false); 906 } 907 return true; 908 } 909 private static boolean checkInt(Class<?> type, Object x) { 910 assert(x instanceof Integer); 911 if (type == int.class) return true; 912 Wrapper w = Wrapper.forBasicType(type); 913 assert(w.isSubwordOrInt()); 914 Object x1 = Wrapper.INT.wrap(w.wrap(x)); 915 return x.equals(x1); 916 } 917 private static boolean checkRef(Class<?> type, Object x) { 918 assert(!type.isPrimitive()); 919 if (x == null) return true; 920 if (type.isInterface()) return true; 921 return type.isInstance(x); 922 } 923 924 /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */ 925 private static final int COMPILE_THRESHOLD; 926 static { 927 COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD); 928 } 929 private int invocationCounter = 0; // a value of -1 indicates LambdaForm interpretation mode forever 930 931 private boolean forceInterpretation() { 932 return invocationCounter == -1; 933 } 934 935 @Hidden 936 @DontInline 937 /** Interpretively invoke this form on the given arguments. */ 938 Object interpretWithArguments(Object... argumentValues) throws Throwable { 939 if (TRACE_INTERPRETER) 940 return interpretWithArgumentsTracing(argumentValues); 941 checkInvocationCounter(); 942 assert(arityCheck(argumentValues)); 943 Object[] values = Arrays.copyOf(argumentValues, names.length); 944 for (int i = argumentValues.length; i < values.length; i++) { 945 values[i] = interpretName(names[i], values); 946 } 947 Object rv = (result < 0) ? null : values[result]; 948 assert(resultCheck(argumentValues, rv)); 949 return rv; 950 } 951 952 @Hidden 953 @DontInline 954 /** Evaluate a single Name within this form, applying its function to its arguments. */ 955 Object interpretName(Name name, Object[] values) throws Throwable { 956 if (TRACE_INTERPRETER) 957 traceInterpreter("| interpretName", name.debugString(), (Object[]) null); 958 Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class); 959 for (int i = 0; i < arguments.length; i++) { 960 Object a = arguments[i]; 961 if (a instanceof Name) { 962 int i2 = ((Name)a).index(); 963 assert(names[i2] == a); 964 a = values[i2]; 965 arguments[i] = a; 966 } 967 } 968 return name.function.invokeWithArguments(arguments); 969 } 970 971 private void checkInvocationCounter() { 972 if (COMPILE_THRESHOLD != 0 && 973 !forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) { 974 invocationCounter++; // benign race 975 if (invocationCounter >= COMPILE_THRESHOLD) { 976 // Replace vmentry with a bytecode version of this LF. 977 compileToBytecode(); 978 } 979 } 980 } 981 Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable { 982 traceInterpreter("[ interpretWithArguments", this, argumentValues); 983 if (!forceInterpretation() && invocationCounter < COMPILE_THRESHOLD) { 984 int ctr = invocationCounter++; // benign race 985 traceInterpreter("| invocationCounter", ctr); 986 if (invocationCounter >= COMPILE_THRESHOLD) { 987 compileToBytecode(); 988 } 989 } 990 Object rval; 991 try { 992 assert(arityCheck(argumentValues)); 993 Object[] values = Arrays.copyOf(argumentValues, names.length); 994 for (int i = argumentValues.length; i < values.length; i++) { 995 values[i] = interpretName(names[i], values); 996 } 997 rval = (result < 0) ? null : values[result]; 998 } catch (Throwable ex) { 999 traceInterpreter("] throw =>", ex); 1000 throw ex; 1001 } 1002 traceInterpreter("] return =>", rval); 1003 return rval; 1004 } 1005 1006 static void traceInterpreter(String event, Object obj, Object... args) { 1007 if (TRACE_INTERPRETER) { 1008 System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : "")); 1009 } 1010 } 1011 static void traceInterpreter(String event, Object obj) { 1012 traceInterpreter(event, obj, (Object[])null); 1013 } 1014 private boolean arityCheck(Object[] argumentValues) { 1015 assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length"; 1016 // also check that the leading (receiver) argument is somehow bound to this LF: 1017 assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0]; 1018 MethodHandle mh = (MethodHandle) argumentValues[0]; 1019 assert(mh.internalForm() == this); 1020 // note: argument #0 could also be an interface wrapper, in the future 1021 argumentTypesMatch(basicTypeSignature(), argumentValues); 1022 return true; 1023 } 1024 private boolean resultCheck(Object[] argumentValues, Object result) { 1025 MethodHandle mh = (MethodHandle) argumentValues[0]; 1026 MethodType mt = mh.type(); 1027 assert(valueMatches(returnType(), mt.returnType(), result)); 1028 return true; 1029 } 1030 1031 private boolean isEmpty() { 1032 if (result < 0) 1033 return (names.length == arity); 1034 else if (result == arity && names.length == arity + 1) 1035 return names[arity].isConstantZero(); 1036 else 1037 return false; 1038 } 1039 1040 public String toString() { 1041 String lambdaName = lambdaName(); 1042 StringBuilder buf = new StringBuilder(lambdaName + "=Lambda("); 1043 for (int i = 0; i < names.length; i++) { 1044 if (i == arity) buf.append(")=>{"); 1045 Name n = names[i]; 1046 if (i >= arity) buf.append("\n "); 1047 buf.append(n.paramString()); 1048 if (i < arity) { 1049 if (i+1 < arity) buf.append(","); 1050 continue; 1051 } 1052 buf.append("=").append(n.exprString()); 1053 buf.append(";"); 1054 } 1055 if (arity == names.length) buf.append(")=>{"); 1056 buf.append(result < 0 ? "void" : names[result]).append("}"); 1057 if (TRACE_INTERPRETER) { 1058 // Extra verbosity: 1059 buf.append(":").append(basicTypeSignature()); 1060 buf.append("/").append(vmentry); 1061 } 1062 return buf.toString(); 1063 } 1064 1065 @Override 1066 public boolean equals(Object obj) { 1067 return obj instanceof LambdaForm && equals((LambdaForm)obj); 1068 } 1069 public boolean equals(LambdaForm that) { 1070 if (this.result != that.result) return false; 1071 return Arrays.equals(this.names, that.names); 1072 } 1073 public int hashCode() { 1074 return result + 31 * Arrays.hashCode(names); 1075 } 1076 LambdaFormEditor editor() { 1077 return LambdaFormEditor.lambdaFormEditor(this); 1078 } 1079 1080 boolean contains(Name name) { 1081 int pos = name.index(); 1082 if (pos >= 0) { 1083 return pos < names.length && name.equals(names[pos]); 1084 } 1085 for (int i = arity; i < names.length; i++) { 1086 if (name.equals(names[i])) 1087 return true; 1088 } 1089 return false; 1090 } 1091 1092 static class NamedFunction { 1093 final MemberName member; 1094 private @Stable MethodHandle resolvedHandle; 1095 @Stable MethodHandle invoker; 1096 1097 NamedFunction(MethodHandle resolvedHandle) { 1098 this(resolvedHandle.internalMemberName(), resolvedHandle); 1099 } 1100 NamedFunction(MemberName member, MethodHandle resolvedHandle) { 1101 this.member = member; 1102 this.resolvedHandle = resolvedHandle; 1103 // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest. 1104 //assert(!isInvokeBasic(member)); 1105 } 1106 NamedFunction(MethodType basicInvokerType) { 1107 assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType; 1108 if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) { 1109 this.resolvedHandle = basicInvokerType.invokers().basicInvoker(); 1110 this.member = resolvedHandle.internalMemberName(); 1111 } else { 1112 // necessary to pass BigArityTest 1113 this.member = Invokers.invokeBasicMethod(basicInvokerType); 1114 } 1115 assert(isInvokeBasic(member)); 1116 } 1117 1118 private static boolean isInvokeBasic(MemberName member) { 1119 return member != null && 1120 member.getDeclaringClass() == MethodHandle.class && 1121 "invokeBasic".equals(member.getName()); 1122 } 1123 1124 // The next 2 constructors are used to break circular dependencies on MH.invokeStatic, etc. 1125 // Any LambdaForm containing such a member is not interpretable. 1126 // This is OK, since all such LFs are prepared with special primitive vmentry points. 1127 // And even without the resolvedHandle, the name can still be compiled and optimized. 1128 NamedFunction(Method method) { 1129 this(new MemberName(method)); 1130 } 1131 NamedFunction(MemberName member) { 1132 this(member, null); 1133 } 1134 1135 MethodHandle resolvedHandle() { 1136 if (resolvedHandle == null) resolve(); 1137 return resolvedHandle; 1138 } 1139 1140 synchronized void resolve() { 1141 if (resolvedHandle == null) { 1142 resolvedHandle = DirectMethodHandle.make(member); 1143 } 1144 } 1145 1146 @Override 1147 public boolean equals(Object other) { 1148 if (this == other) return true; 1149 if (other == null) return false; 1150 return (other instanceof NamedFunction that) 1151 && this.member != null 1152 && this.member.equals(that.member); 1153 } 1154 1155 @Override 1156 public int hashCode() { 1157 if (member != null) 1158 return member.hashCode(); 1159 return super.hashCode(); 1160 } 1161 1162 static final MethodType INVOKER_METHOD_TYPE = 1163 MethodType.methodType(Object.class, MethodHandle.class, Object[].class); 1164 1165 private static MethodHandle computeInvoker(MethodTypeForm typeForm) { 1166 typeForm = typeForm.basicType().form(); // normalize to basic type 1167 MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV); 1168 if (mh != null) return mh; 1169 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while 1170 mh = DirectMethodHandle.make(invoker); 1171 MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV); 1172 if (mh2 != null) return mh2; // benign race 1173 if (!mh.type().equals(INVOKER_METHOD_TYPE)) 1174 throw newInternalError(mh.debugString()); 1175 return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh); 1176 } 1177 1178 @Hidden 1179 Object invokeWithArguments(Object... arguments) throws Throwable { 1180 // If we have a cached invoker, call it right away. 1181 // NOTE: The invoker always returns a reference value. 1182 if (TRACE_INTERPRETER) return invokeWithArgumentsTracing(arguments); 1183 return invoker().invokeBasic(resolvedHandle(), arguments); 1184 } 1185 1186 @Hidden 1187 Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable { 1188 Object rval; 1189 try { 1190 traceInterpreter("[ call", this, arguments); 1191 if (invoker == null) { 1192 traceInterpreter("| getInvoker", this); 1193 invoker(); 1194 } 1195 // resolvedHandle might be uninitialized, ok for tracing 1196 if (resolvedHandle == null) { 1197 traceInterpreter("| resolve", this); 1198 resolvedHandle(); 1199 } 1200 rval = invoker().invokeBasic(resolvedHandle(), arguments); 1201 } catch (Throwable ex) { 1202 traceInterpreter("] throw =>", ex); 1203 throw ex; 1204 } 1205 traceInterpreter("] return =>", rval); 1206 return rval; 1207 } 1208 1209 private MethodHandle invoker() { 1210 if (invoker != null) return invoker; 1211 // Get an invoker and cache it. 1212 return invoker = computeInvoker(methodType().form()); 1213 } 1214 1215 MethodType methodType() { 1216 if (resolvedHandle != null) 1217 return resolvedHandle.type(); 1218 else 1219 // only for certain internal LFs during bootstrapping 1220 return member.getInvocationType(); 1221 } 1222 1223 MemberName member() { 1224 assert(assertMemberIsConsistent()); 1225 return member; 1226 } 1227 1228 // Called only from assert. 1229 private boolean assertMemberIsConsistent() { 1230 if (resolvedHandle instanceof DirectMethodHandle) { 1231 MemberName m = resolvedHandle.internalMemberName(); 1232 assert(m.equals(member)); 1233 } 1234 return true; 1235 } 1236 1237 Class<?> memberDeclaringClassOrNull() { 1238 return (member == null) ? null : member.getDeclaringClass(); 1239 } 1240 1241 BasicType returnType() { 1242 return basicType(methodType().returnType()); 1243 } 1244 1245 BasicType parameterType(int n) { 1246 return basicType(methodType().parameterType(n)); 1247 } 1248 1249 int arity() { 1250 return methodType().parameterCount(); 1251 } 1252 1253 public String toString() { 1254 if (member == null) return String.valueOf(resolvedHandle); 1255 return member.getDeclaringClass().getSimpleName()+"."+member.getName(); 1256 } 1257 1258 public boolean isIdentity() { 1259 return this.equals(identity(returnType())); 1260 } 1261 1262 public boolean isConstantZero() { 1263 return this.equals(constantZero(returnType())); 1264 } 1265 1266 public MethodHandleImpl.Intrinsic intrinsicName() { 1267 return resolvedHandle != null 1268 ? resolvedHandle.intrinsicName() 1269 : MethodHandleImpl.Intrinsic.NONE; 1270 } 1271 1272 public Object intrinsicData() { 1273 return resolvedHandle != null 1274 ? resolvedHandle.intrinsicData() 1275 : null; 1276 } 1277 } 1278 1279 public static String basicTypeSignature(MethodType type) { 1280 int params = type.parameterCount(); 1281 char[] sig = new char[params + 2]; 1282 int sigp = 0; 1283 while (sigp < params) { 1284 sig[sigp] = basicTypeChar(type.parameterType(sigp++)); 1285 } 1286 sig[sigp++] = '_'; 1287 sig[sigp++] = basicTypeChar(type.returnType()); 1288 assert(sigp == sig.length); 1289 return String.valueOf(sig); 1290 } 1291 1292 /** Hack to make signatures more readable when they show up in method names. 1293 * Signature should start with a sequence of uppercase ASCII letters. 1294 * Runs of three or more are replaced by a single letter plus a decimal repeat count. 1295 * A tail of anything other than uppercase ASCII is passed through unchanged. 1296 * @param signature sequence of uppercase ASCII letters with possible repetitions 1297 * @return same sequence, with repetitions counted by decimal numerals 1298 */ 1299 public static String shortenSignature(String signature) { 1300 final int NO_CHAR = -1, MIN_RUN = 3; 1301 int c0, c1 = NO_CHAR, c1reps = 0; 1302 StringBuilder buf = null; 1303 int len = signature.length(); 1304 if (len < MIN_RUN) return signature; 1305 for (int i = 0; i <= len; i++) { 1306 if (c1 != NO_CHAR && !('A' <= c1 && c1 <= 'Z')) { 1307 // wrong kind of char; bail out here 1308 if (buf != null) { 1309 buf.append(signature, i - c1reps, len); 1310 } 1311 break; 1312 } 1313 // shift in the next char: 1314 c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i)); 1315 if (c1 == c0) { ++c1reps; continue; } 1316 // shift in the next count: 1317 int c0reps = c1reps; c1reps = 1; 1318 // end of a character run 1319 if (c0reps < MIN_RUN) { 1320 if (buf != null) { 1321 while (--c0reps >= 0) 1322 buf.append((char)c0); 1323 } 1324 continue; 1325 } 1326 // found three or more in a row 1327 if (buf == null) 1328 buf = new StringBuilder().append(signature, 0, i - c0reps); 1329 buf.append((char)c0).append(c0reps); 1330 } 1331 return (buf == null) ? signature : buf.toString(); 1332 } 1333 1334 static final class Name { 1335 final BasicType type; 1336 @Stable short index; 1337 final NamedFunction function; 1338 final Object constraint; // additional type information, if not null 1339 @Stable final Object[] arguments; 1340 1341 private Name(int index, BasicType type, NamedFunction function, Object[] arguments) { 1342 this.index = (short)index; 1343 this.type = type; 1344 this.function = function; 1345 this.arguments = arguments; 1346 this.constraint = null; 1347 assert(this.index == index); 1348 } 1349 private Name(Name that, Object constraint) { 1350 this.index = that.index; 1351 this.type = that.type; 1352 this.function = that.function; 1353 this.arguments = that.arguments; 1354 this.constraint = constraint; 1355 assert(constraint == null || isParam()); // only params have constraints 1356 assert(constraint == null || constraint instanceof ClassSpecializer.SpeciesData || constraint instanceof Class); 1357 } 1358 Name(MethodHandle function, Object... arguments) { 1359 this(new NamedFunction(function), arguments); 1360 } 1361 Name(MethodType functionType, Object... arguments) { 1362 this(new NamedFunction(functionType), arguments); 1363 assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE); 1364 } 1365 Name(MemberName function, Object... arguments) { 1366 this(new NamedFunction(function), arguments); 1367 } 1368 Name(NamedFunction function, Object... arguments) { 1369 this(-1, function.returnType(), function, arguments = Arrays.copyOf(arguments, arguments.length, Object[].class)); 1370 assert(typesMatch(function, arguments)); 1371 } 1372 /** Create a raw parameter of the given type, with an expected index. */ 1373 Name(int index, BasicType type) { 1374 this(index, type, null, null); 1375 } 1376 /** Create a raw parameter of the given type. */ 1377 Name(BasicType type) { this(-1, type); } 1378 1379 BasicType type() { return type; } 1380 int index() { return index; } 1381 boolean initIndex(int i) { 1382 if (index != i) { 1383 if (index != -1) return false; 1384 index = (short)i; 1385 } 1386 return true; 1387 } 1388 char typeChar() { 1389 return type.btChar; 1390 } 1391 1392 Name newIndex(int i) { 1393 if (initIndex(i)) return this; 1394 return cloneWithIndex(i); 1395 } 1396 Name cloneWithIndex(int i) { 1397 Object[] newArguments = (arguments == null) ? null : arguments.clone(); 1398 return new Name(i, type, function, newArguments).withConstraint(constraint); 1399 } 1400 Name withConstraint(Object constraint) { 1401 if (constraint == this.constraint) return this; 1402 return new Name(this, constraint); 1403 } 1404 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly 1405 if (oldName == newName) return this; 1406 @SuppressWarnings("LocalVariableHidesMemberVariable") 1407 Object[] arguments = this.arguments; 1408 if (arguments == null) return this; 1409 boolean replaced = false; 1410 for (int j = 0; j < arguments.length; j++) { 1411 if (arguments[j] == oldName) { 1412 if (!replaced) { 1413 replaced = true; 1414 arguments = arguments.clone(); 1415 } 1416 arguments[j] = newName; 1417 } 1418 } 1419 if (!replaced) return this; 1420 return new Name(function, arguments); 1421 } 1422 /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i]. 1423 * Limit such replacements to {@code start<=i<end}. Return possibly changed self. 1424 */ 1425 Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) { 1426 if (start >= end) return this; 1427 @SuppressWarnings("LocalVariableHidesMemberVariable") 1428 Object[] arguments = this.arguments; 1429 boolean replaced = false; 1430 eachArg: 1431 for (int j = 0; j < arguments.length; j++) { 1432 if (arguments[j] instanceof Name n) { 1433 int check = n.index; 1434 // harmless check to see if the thing is already in newNames: 1435 if (check >= 0 && check < newNames.length && n == newNames[check]) 1436 continue eachArg; 1437 // n might not have the correct index: n != oldNames[n.index]. 1438 for (int i = start; i < end; i++) { 1439 if (n == oldNames[i]) { 1440 if (n == newNames[i]) 1441 continue eachArg; 1442 if (!replaced) { 1443 replaced = true; 1444 arguments = arguments.clone(); 1445 } 1446 arguments[j] = newNames[i]; 1447 continue eachArg; 1448 } 1449 } 1450 } 1451 } 1452 if (!replaced) return this; 1453 return new Name(function, arguments); 1454 } 1455 void internArguments() { 1456 @SuppressWarnings("LocalVariableHidesMemberVariable") 1457 Object[] arguments = this.arguments; 1458 for (int j = 0; j < arguments.length; j++) { 1459 if (arguments[j] instanceof Name n) { 1460 if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT) 1461 arguments[j] = internArgument(n); 1462 } 1463 } 1464 } 1465 boolean isParam() { 1466 return function == null; 1467 } 1468 boolean isConstantZero() { 1469 return !isParam() && arguments.length == 0 && function.isConstantZero(); 1470 } 1471 1472 boolean refersTo(Class<?> declaringClass, String methodName) { 1473 return function != null && 1474 function.member() != null && function.member().refersTo(declaringClass, methodName); 1475 } 1476 1477 /** 1478 * Check if MemberName is a call to MethodHandle.invokeBasic. 1479 */ 1480 boolean isInvokeBasic() { 1481 if (function == null) 1482 return false; 1483 if (arguments.length < 1) 1484 return false; // must have MH argument 1485 MemberName member = function.member(); 1486 return member != null && member.refersTo(MethodHandle.class, "invokeBasic") && 1487 !member.isPublic() && !member.isStatic(); 1488 } 1489 1490 /** 1491 * Check if MemberName is a call to MethodHandle.linkToStatic, etc. 1492 */ 1493 boolean isLinkerMethodInvoke() { 1494 if (function == null) 1495 return false; 1496 if (arguments.length < 1) 1497 return false; // must have MH argument 1498 MemberName member = function.member(); 1499 return member != null && 1500 member.getDeclaringClass() == MethodHandle.class && 1501 !member.isPublic() && member.isStatic() && 1502 member.getName().startsWith("linkTo"); 1503 } 1504 1505 public String toString() { 1506 return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar(); 1507 } 1508 public String debugString() { 1509 String s = paramString(); 1510 return (function == null) ? s : s + "=" + exprString(); 1511 } 1512 public String paramString() { 1513 String s = toString(); 1514 Object c = constraint; 1515 if (c == null) 1516 return s; 1517 if (c instanceof Class) c = ((Class<?>)c).getSimpleName(); 1518 return s + "/" + c; 1519 } 1520 public String exprString() { 1521 if (function == null) return toString(); 1522 StringBuilder buf = new StringBuilder(function.toString()); 1523 buf.append("("); 1524 String cma = ""; 1525 for (Object a : arguments) { 1526 buf.append(cma); cma = ","; 1527 if (a instanceof Name || a instanceof Integer) 1528 buf.append(a); 1529 else 1530 buf.append("(").append(a).append(")"); 1531 } 1532 buf.append(")"); 1533 return buf.toString(); 1534 } 1535 1536 private boolean typesMatch(NamedFunction function, Object ... arguments) { 1537 assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString(); 1538 for (int i = 0; i < arguments.length; i++) { 1539 assert (typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString(); 1540 } 1541 return true; 1542 } 1543 1544 private static boolean typesMatch(BasicType parameterType, Object object) { 1545 if (object instanceof Name) { 1546 return ((Name)object).type == parameterType; 1547 } 1548 switch (parameterType) { 1549 case I_TYPE: return object instanceof Integer; 1550 case J_TYPE: return object instanceof Long; 1551 case F_TYPE: return object instanceof Float; 1552 case D_TYPE: return object instanceof Double; 1553 } 1554 assert(parameterType == L_TYPE); 1555 return true; 1556 } 1557 1558 /** Return the index of the last occurrence of n in the argument array. 1559 * Return -1 if the name is not used. 1560 */ 1561 int lastUseIndex(Name n) { 1562 if (arguments == null) return -1; 1563 for (int i = arguments.length; --i >= 0; ) { 1564 if (arguments[i] == n) return i; 1565 } 1566 return -1; 1567 } 1568 1569 /** Return the number of occurrences of n in the argument array. 1570 * Return 0 if the name is not used. 1571 */ 1572 int useCount(Name n) { 1573 int count = 0; 1574 if (arguments != null) { 1575 for (Object argument : arguments) { 1576 if (argument == n) { 1577 count++; 1578 } 1579 } 1580 } 1581 return count; 1582 } 1583 1584 public boolean equals(Name that) { 1585 if (this == that) return true; 1586 if (isParam()) 1587 // each parameter is a unique atom 1588 return false; // this != that 1589 return 1590 //this.index == that.index && 1591 this.type == that.type && 1592 this.function.equals(that.function) && 1593 Arrays.equals(this.arguments, that.arguments); 1594 } 1595 @Override 1596 public boolean equals(Object x) { 1597 return x instanceof Name && equals((Name)x); 1598 } 1599 @Override 1600 public int hashCode() { 1601 if (isParam()) 1602 return index | (type.ordinal() << 8); 1603 return function.hashCode() ^ Arrays.hashCode(arguments); 1604 } 1605 } 1606 1607 /** Return the index of the last name which contains n as an argument. 1608 * Return -1 if the name is not used. Return names.length if it is the return value. 1609 */ 1610 int lastUseIndex(Name n) { 1611 int ni = n.index, nmax = names.length; 1612 assert(names[ni] == n); 1613 if (result == ni) return nmax; // live all the way beyond the end 1614 for (int i = nmax; --i > ni; ) { 1615 if (names[i].lastUseIndex(n) >= 0) 1616 return i; 1617 } 1618 return -1; 1619 } 1620 1621 /** Return the number of times n is used as an argument or return value. */ 1622 int useCount(Name n) { 1623 int count = (result == n.index) ? 1 : 0; 1624 int i = Math.max(n.index + 1, arity); 1625 while (i < names.length) { 1626 count += names[i++].useCount(n); 1627 } 1628 return count; 1629 } 1630 1631 static Name argument(int which, BasicType type) { 1632 if (which >= INTERNED_ARGUMENT_LIMIT) 1633 return new Name(which, type); 1634 return INTERNED_ARGUMENTS[type.ordinal()][which]; 1635 } 1636 static Name internArgument(Name n) { 1637 assert(n.isParam()) : "not param: " + n; 1638 assert(n.index < INTERNED_ARGUMENT_LIMIT); 1639 if (n.constraint != null) return n; 1640 return argument(n.index, n.type); 1641 } 1642 static Name[] arguments(int extra, MethodType types) { 1643 int length = types.parameterCount(); 1644 Name[] names = new Name[length + extra]; 1645 for (int i = 0; i < length; i++) 1646 names[i] = argument(i, basicType(types.parameterType(i))); 1647 return names; 1648 } 1649 static final int INTERNED_ARGUMENT_LIMIT = 10; 1650 private static final Name[][] INTERNED_ARGUMENTS 1651 = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT]; 1652 static { 1653 for (BasicType type : BasicType.ARG_TYPES) { 1654 int ord = type.ordinal(); 1655 for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) { 1656 INTERNED_ARGUMENTS[ord][i] = new Name(i, type); 1657 } 1658 } 1659 } 1660 1661 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 1662 1663 static LambdaForm identityForm(BasicType type) { 1664 int ord = type.ordinal(); 1665 LambdaForm form = LF_identity[ord]; 1666 if (form != null) { 1667 return form; 1668 } 1669 createFormsFor(type); 1670 return LF_identity[ord]; 1671 } 1672 1673 static LambdaForm zeroForm(BasicType type) { 1674 int ord = type.ordinal(); 1675 LambdaForm form = LF_zero[ord]; 1676 if (form != null) { 1677 return form; 1678 } 1679 createFormsFor(type); 1680 return LF_zero[ord]; 1681 } 1682 1683 static NamedFunction identity(BasicType type) { 1684 int ord = type.ordinal(); 1685 NamedFunction function = NF_identity[ord]; 1686 if (function != null) { 1687 return function; 1688 } 1689 createFormsFor(type); 1690 return NF_identity[ord]; 1691 } 1692 1693 static NamedFunction constantZero(BasicType type) { 1694 int ord = type.ordinal(); 1695 NamedFunction function = NF_zero[ord]; 1696 if (function != null) { 1697 return function; 1698 } 1699 createFormsFor(type); 1700 return NF_zero[ord]; 1701 } 1702 1703 private static final @Stable LambdaForm[] LF_identity = new LambdaForm[TYPE_LIMIT]; 1704 private static final @Stable LambdaForm[] LF_zero = new LambdaForm[TYPE_LIMIT]; 1705 private static final @Stable NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT]; 1706 private static final @Stable NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT]; 1707 1708 private static final Object createFormsLock = new Object(); 1709 private static void createFormsFor(BasicType type) { 1710 // Avoid racy initialization during bootstrap 1711 UNSAFE.ensureClassInitialized(BoundMethodHandle.class); 1712 synchronized (createFormsLock) { 1713 final int ord = type.ordinal(); 1714 LambdaForm idForm = LF_identity[ord]; 1715 if (idForm != null) { 1716 return; 1717 } 1718 char btChar = type.basicTypeChar(); 1719 boolean isVoid = (type == V_TYPE); 1720 Class<?> btClass = type.btClass; 1721 MethodType zeType = MethodType.methodType(btClass); 1722 MethodType idType = (isVoid) ? zeType : MethodType.methodType(btClass, btClass); 1723 1724 // Look up symbolic names. It might not be necessary to have these, 1725 // but if we need to emit direct references to bytecodes, it helps. 1726 // Zero is built from a call to an identity function with a constant zero input. 1727 MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic); 1728 MemberName zeMem = null; 1729 try { 1730 idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, LM_TRUSTED, NoSuchMethodException.class); 1731 if (!isVoid) { 1732 zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic); 1733 zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, LM_TRUSTED, NoSuchMethodException.class); 1734 } 1735 } catch (IllegalAccessException|NoSuchMethodException ex) { 1736 throw newInternalError(ex); 1737 } 1738 1739 NamedFunction idFun; 1740 LambdaForm zeForm; 1741 NamedFunction zeFun; 1742 1743 // Create the LFs and NamedFunctions. Precompiling LFs to byte code is needed to break circular 1744 // bootstrap dependency on this method in case we're interpreting LFs 1745 if (isVoid) { 1746 Name[] idNames = new Name[] { argument(0, L_TYPE) }; 1747 idForm = new LambdaForm(1, idNames, VOID_RESULT, Kind.IDENTITY); 1748 idForm.compileToBytecode(); 1749 idFun = new NamedFunction(idMem, SimpleMethodHandle.make(idMem.getInvocationType(), idForm)); 1750 1751 zeForm = idForm; 1752 zeFun = idFun; 1753 } else { 1754 Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) }; 1755 idForm = new LambdaForm(2, idNames, 1, Kind.IDENTITY); 1756 idForm.compileToBytecode(); 1757 idFun = new NamedFunction(idMem, MethodHandleImpl.makeIntrinsic(SimpleMethodHandle.make(idMem.getInvocationType(), idForm), 1758 MethodHandleImpl.Intrinsic.IDENTITY)); 1759 1760 Object zeValue = Wrapper.forBasicType(btChar).zero(); 1761 Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) }; 1762 zeForm = new LambdaForm(1, zeNames, 1, Kind.ZERO); 1763 zeForm.compileToBytecode(); 1764 zeFun = new NamedFunction(zeMem, MethodHandleImpl.makeIntrinsic(SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm), 1765 MethodHandleImpl.Intrinsic.ZERO)); 1766 } 1767 1768 LF_zero[ord] = zeForm; 1769 NF_zero[ord] = zeFun; 1770 LF_identity[ord] = idForm; 1771 NF_identity[ord] = idFun; 1772 1773 assert(idFun.isIdentity()); 1774 assert(zeFun.isConstantZero()); 1775 assert(new Name(zeFun).isConstantZero()); 1776 } 1777 } 1778 1779 // Avoid appealing to ValueConversions at bootstrap time: 1780 private static int identity_I(int x) { return x; } 1781 private static long identity_J(long x) { return x; } 1782 private static float identity_F(float x) { return x; } 1783 private static double identity_D(double x) { return x; } 1784 private static Object identity_L(Object x) { return x; } 1785 private static void identity_V() { return; } 1786 private static int zero_I() { return 0; } 1787 private static long zero_J() { return 0; } 1788 private static float zero_F() { return 0; } 1789 private static double zero_D() { return 0; } 1790 private static Object zero_L() { return null; } 1791 1792 /** 1793 * Internal marker for byte-compiled LambdaForms. 1794 */ 1795 /*non-public*/ 1796 @Target(ElementType.METHOD) 1797 @Retention(RetentionPolicy.RUNTIME) 1798 @interface Compiled { 1799 } 1800 1801 private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS; 1802 private static final HashMap<LambdaForm,String> DEBUG_NAMES; 1803 static { 1804 if (debugEnabled()) { 1805 DEBUG_NAME_COUNTERS = new HashMap<>(); 1806 DEBUG_NAMES = new HashMap<>(); 1807 } else { 1808 DEBUG_NAME_COUNTERS = null; 1809 DEBUG_NAMES = null; 1810 } 1811 } 1812 1813 static { 1814 // The Holder class will contain pre-generated forms resolved 1815 // using MemberName.getFactory(). However, that doesn't initialize the 1816 // class, which subtly breaks inlining etc. By forcing 1817 // initialization of the Holder class we avoid these issues. 1818 UNSAFE.ensureClassInitialized(Holder.class); 1819 } 1820 1821 /* Placeholder class for zero and identity forms generated ahead of time */ 1822 final class Holder {} 1823 1824 // The following hack is necessary in order to suppress TRACE_INTERPRETER 1825 // during execution of the static initializes of this class. 1826 // Turning on TRACE_INTERPRETER too early will cause 1827 // stack overflows and other misbehavior during attempts to trace events 1828 // that occur during LambdaForm.<clinit>. 1829 // Therefore, do not move this line higher in this file, and do not remove. 1830 private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER; 1831 }