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