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