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