1 /*
   2  * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  29 import static java.lang.invoke.LambdaForm.*;
  30 import static java.lang.invoke.MethodHandleStatics.*;
  31 
  32 import java.lang.invoke.LambdaForm.NamedFunction;
  33 import java.lang.invoke.MethodHandles.Lookup;
  34 import java.lang.reflect.Field;
  35 import java.util.Arrays;
  36 import java.util.HashMap;
  37 
  38 import sun.invoke.util.ValueConversions;
  39 import sun.invoke.util.Wrapper;
  40 
  41 import jdk.internal.org.objectweb.asm.ClassWriter;
  42 import jdk.internal.org.objectweb.asm.MethodVisitor;
  43 import jdk.internal.org.objectweb.asm.Type;
  44 
  45 /**
  46  * The flavor of method handle which emulates an invoke instruction
  47  * on a predetermined argument.  The JVM dispatches to the correct method
  48  * when the handle is created, not when it is invoked.
  49  *
  50  * All bound arguments are encapsulated in dedicated species.
  51  */
  52 /* non-public */ abstract class BoundMethodHandle extends MethodHandle {
  53 
  54     /* non-public */ BoundMethodHandle(MethodType type, LambdaForm form) {
  55         super(type, form);
  56     }
  57 
  58     //
  59     // BMH API and internals
  60     //
  61 
  62     static MethodHandle bindSingle(MethodType type, LambdaForm form, byte xtype, Object x) {
  63         // for some type signatures, there exist pre-defined concrete BMH classes
  64         try {
  65             switch (xtype) {
  66             case L_TYPE:
  67                 if (true)  return bindSingle(type, form, x);  // Use known fast path.
  68                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(L_TYPE).constructor[0].invokeBasic(type, form, x);
  69             case I_TYPE:
  70                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(I_TYPE).constructor[0].invokeBasic(type, form, ValueConversions.widenSubword(x));
  71             case J_TYPE:
  72                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(J_TYPE).constructor[0].invokeBasic(type, form, (long) x);
  73             case F_TYPE:
  74                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(F_TYPE).constructor[0].invokeBasic(type, form, (float) x);
  75             case D_TYPE:
  76                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(D_TYPE).constructor[0].invokeBasic(type, form, (double) x);
  77             default : throw new InternalError("unexpected xtype: " + xtype);
  78             }
  79         } catch (Throwable t) {
  80             throw newInternalError(t);
  81         }
  82     }
  83 
  84     static MethodHandle bindSingle(MethodType type, LambdaForm form, Object x) {
  85             return new Species_L(type, form, x);
  86     }
  87 
  88     MethodHandle cloneExtend(MethodType type, LambdaForm form, byte xtype, Object x) {
  89         try {
  90             switch (xtype) {
  91             case L_TYPE: return copyWithExtendL(type, form, x);
  92             case I_TYPE: return copyWithExtendI(type, form, ValueConversions.widenSubword(x));
  93             case J_TYPE: return copyWithExtendJ(type, form, (long) x);
  94             case F_TYPE: return copyWithExtendF(type, form, (float) x);
  95             case D_TYPE: return copyWithExtendD(type, form, (double) x);
  96             }
  97         } catch (Throwable t) {
  98             throw newInternalError(t);
  99         }
 100         throw new InternalError("unexpected type: " + xtype);
 101     }
 102 
 103     @Override
 104     MethodHandle bindArgument(int pos, byte basicType, Object value) {
 105         MethodType type = type().dropParameterTypes(pos, pos+1);
 106         LambdaForm form = internalForm().bind(1+pos, speciesData());
 107         return cloneExtend(type, form, basicType, value);
 108     }
 109 
 110     @Override
 111     MethodHandle dropArguments(MethodType srcType, int pos, int drops) {
 112         LambdaForm form = internalForm().addArguments(pos, srcType.parameterList().subList(pos, pos + drops));
 113         try {
 114              return copyWith(srcType, form);
 115          } catch (Throwable t) {
 116              throw newInternalError(t);
 117          }
 118     }
 119 
 120     @Override
 121     MethodHandle permuteArguments(MethodType newType, int[] reorder) {
 122         try {
 123              return copyWith(newType, form.permuteArguments(1, reorder, basicTypes(newType.parameterList())));
 124          } catch (Throwable t) {
 125              throw newInternalError(t);
 126          }
 127     }
 128 
 129     static final String EXTENSION_TYPES = "LIJFD";
 130     static final byte INDEX_L = 0, INDEX_I = 1, INDEX_J = 2, INDEX_F = 3, INDEX_D = 4;
 131     static byte extensionIndex(char type) {
 132         int i = EXTENSION_TYPES.indexOf(type);
 133         if (i < 0)  throw new InternalError();
 134         return (byte) i;
 135     }
 136 
 137     /**
 138      * Return the {@link SpeciesData} instance representing this BMH species. All subclasses must provide a
 139      * static field containing this value, and they must accordingly implement this method.
 140      */
 141     public abstract SpeciesData speciesData();
 142 
 143     /**
 144      * Return the number of fields in this BMH.  Equivalent to speciesData().fieldCount().
 145      */
 146     public abstract int fieldCount();
 147 
 148     @Override
 149     final Object internalProperties() {
 150         return "/BMH="+internalValues();
 151     }
 152 
 153     @Override
 154     final Object internalValues() {
 155         Object[] boundValues = new Object[speciesData().fieldCount()];
 156         for (int i = 0; i < boundValues.length; ++i) {
 157             boundValues[i] = arg(i);
 158         }
 159         return Arrays.asList(boundValues);
 160     }
 161 
 162     public final Object arg(int i) {
 163         try {
 164             switch (speciesData().fieldType(i)) {
 165             case L_TYPE: return          speciesData().getters[i].invokeBasic(this);
 166             case I_TYPE: return (int)    speciesData().getters[i].invokeBasic(this);
 167             case J_TYPE: return (long)   speciesData().getters[i].invokeBasic(this);
 168             case F_TYPE: return (float)  speciesData().getters[i].invokeBasic(this);
 169             case D_TYPE: return (double) speciesData().getters[i].invokeBasic(this);
 170             }
 171         } catch (Throwable ex) {
 172             throw newInternalError(ex);
 173         }
 174         throw new InternalError("unexpected type: " + speciesData().typeChars+"."+i);
 175     }
 176 
 177     //
 178     // cloning API
 179     //
 180 
 181     // The following is a grossly irregular hack:
 182     @Override MethodHandle reinvokerTarget() {
 183         try {
 184             return (MethodHandle) arg(0);
 185         } catch (Throwable ex) {
 186             throw newInternalError(ex);
 187         }
 188     }
 189 
 190     @Override
 191     public abstract BoundMethodHandle copyWith(MethodType mt, LambdaForm lf);
 192     public abstract BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg);
 193     public abstract BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int    narg);
 194     public abstract BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long   narg);
 195     public abstract BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float  narg);
 196     public abstract BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg);
 197 
 198     //
 199     // concrete BMH classes required to close bootstrap loops
 200     //
 201 
 202     private  // make it private to force users to access the enclosing class first
 203     static final class Species_L extends BoundMethodHandle {
 204         final Object argL0;
 205         private Species_L(MethodType mt, LambdaForm lf, Object argL0) {
 206             super(mt, lf);
 207             this.argL0 = argL0;
 208         }
 209         @Override
 210         public SpeciesData speciesData() {
 211             return SPECIES_DATA;
 212         }
 213         @Override
 214         public int fieldCount() {
 215             return 1;
 216         }
 217         public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("L", Species_L.class);
 218         public static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) {
 219             return new Species_L(mt, lf, argL0);
 220         }
 221         @Override
 222         public final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
 223             return new Species_L(mt, lf, argL0);
 224         }
 225         @Override
 226         public final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
 227             try {
 228                 return (BoundMethodHandle) SPECIES_DATA.extendWith(L_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg);
 229             } catch (Throwable ex) {
 230                 throw uncaughtException(ex);
 231             }
 232         }
 233         @Override
 234         public final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
 235             try {
 236                 return (BoundMethodHandle) SPECIES_DATA.extendWith(I_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg);
 237             } catch (Throwable ex) {
 238                 throw uncaughtException(ex);
 239             }
 240         }
 241         @Override
 242         public final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
 243             try {
 244                 return (BoundMethodHandle) SPECIES_DATA.extendWith(J_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg);
 245             } catch (Throwable ex) {
 246                 throw uncaughtException(ex);
 247             }
 248         }
 249         @Override
 250         public final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
 251             try {
 252                 return (BoundMethodHandle) SPECIES_DATA.extendWith(F_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg);
 253             } catch (Throwable ex) {
 254                 throw uncaughtException(ex);
 255             }
 256         }
 257         @Override
 258         public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
 259             try {
 260                 return (BoundMethodHandle) SPECIES_DATA.extendWith(D_TYPE).constructor[0].invokeBasic(mt, lf, argL0, narg);
 261             } catch (Throwable ex) {
 262                 throw uncaughtException(ex);
 263             }
 264         }
 265     }
 266 
 267     //
 268     // BMH species meta-data
 269     //
 270 
 271     /**
 272      * Meta-data wrapper for concrete BMH types.
 273      * Each BMH type corresponds to a given sequence of basic field types (LIJFD).
 274      * The fields are immutable; their values are fully specified at object construction.
 275      * Each BMH type supplies an array of getter functions which may be used in lambda forms.
 276      * A BMH is constructed by cloning a shorter BMH and adding one or more new field values.
 277      * As a degenerate and common case, the "shorter BMH" can be missing, and contributes zero prior fields.
 278      */
 279     static class SpeciesData {
 280         final String                             typeChars;
 281         final byte[]                             typeCodes;
 282         final Class<? extends BoundMethodHandle> clazz;
 283         // Bootstrapping requires circular relations MH -> BMH -> SpeciesData -> MH
 284         // Therefore, we need a non-final link in the chain.  Use array elements.
 285         final MethodHandle[]                     constructor;
 286         final MethodHandle[]                     getters;
 287         final NamedFunction[]                    nominalGetters;
 288         final SpeciesData[]                      extensions;
 289 
 290         public int fieldCount() {
 291             return typeCodes.length;
 292         }
 293         public byte fieldType(int i) {
 294             return typeCodes[i];
 295         }
 296         public char fieldTypeChar(int i) {
 297             return typeChars.charAt(i);
 298         }
 299 
 300         public String toString() {
 301             return "SpeciesData["+(isPlaceholder() ? "<placeholder>" : clazz.getSimpleName())+":"+typeChars+"]";
 302         }
 303 
 304         /**
 305          * Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that
 306          * represents a MH bound to a generic invoker, which in turn forwards to the corresponding
 307          * getter.
 308          */
 309         NamedFunction getterFunction(int i) {
 310             return nominalGetters[i];
 311         }
 312 
 313         static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class);
 314 
 315         private SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) {
 316             this.typeChars = types;
 317             this.typeCodes = basicTypes(types);
 318             this.clazz = clazz;
 319             if (!INIT_DONE) {
 320                 this.constructor = new MethodHandle[1];  // only one ctor
 321                 this.getters = new MethodHandle[types.length()];
 322                 this.nominalGetters = new NamedFunction[types.length()];
 323             } else {
 324                 this.constructor = Factory.makeCtors(clazz, types, null);
 325                 this.getters = Factory.makeGetters(clazz, types, null);
 326                 this.nominalGetters = Factory.makeNominalGetters(clazz, types, null, this.getters);
 327             }
 328             this.extensions = new SpeciesData[ARG_TYPE_LIMIT];
 329         }
 330 
 331         private void initForBootstrap() {
 332             assert(!INIT_DONE);
 333             if (constructor[0] == null) {
 334                 String types = typeChars;
 335                 Factory.makeCtors(clazz, types, this.constructor);
 336                 Factory.makeGetters(clazz, types, this.getters);
 337                 Factory.makeNominalGetters(clazz, types, this.nominalGetters, this.getters);
 338             }
 339         }
 340 
 341         private SpeciesData(String typeChars) {
 342             // Placeholder only.
 343             this.typeChars = typeChars;
 344             this.typeCodes = basicTypes(typeChars);
 345             this.clazz = null;
 346             this.constructor = null;
 347             this.getters = null;
 348             this.nominalGetters = null;
 349             this.extensions = null;
 350         }
 351         private boolean isPlaceholder() { return clazz == null; }
 352 
 353         private static final HashMap<String, SpeciesData> CACHE = new HashMap<>();
 354         static { CACHE.put("", EMPTY); }  // make bootstrap predictable
 355         private static final boolean INIT_DONE;  // set after <clinit> finishes...
 356 
 357         SpeciesData extendWith(byte type) {
 358             SpeciesData d = extensions[type];
 359             if (d != null)  return d;
 360             extensions[type] = d = get(typeChars+basicTypeChar(type));
 361             return d;
 362         }
 363 
 364         SpeciesData extendWith(Class<?> type) {
 365             return extendWith(basicType(type));
 366         }
 367 
 368         SpeciesData extendWithChar(char type) {
 369             return extendWith(basicType(type));
 370         }
 371 
 372         private static SpeciesData get(String types) {
 373             // Acquire cache lock for query.
 374             SpeciesData d = lookupCache(types);
 375             if (!d.isPlaceholder())
 376                 return d;
 377             synchronized (d) {
 378                 // Use synch. on the placeholder to prevent multiple instantiation of one species.
 379                 // Creating this class forces a recursive call to getForClass.
 380                 if (lookupCache(types).isPlaceholder())
 381                     Factory.generateConcreteBMHClass(types);
 382             }
 383             // Reacquire cache lock.
 384             d = lookupCache(types);
 385             // Class loading must have upgraded the cache.
 386             assert(d != null && !d.isPlaceholder());
 387             return d;
 388         }
 389         static SpeciesData getForClass(String types, Class<? extends BoundMethodHandle> clazz) {
 390             // clazz is a new class which is initializing its SPECIES_DATA field
 391             return updateCache(types, new SpeciesData(types, clazz));
 392         }
 393         private static synchronized SpeciesData lookupCache(String types) {
 394             SpeciesData d = CACHE.get(types);
 395             if (d != null)  return d;
 396             d = new SpeciesData(types);
 397             assert(d.isPlaceholder());
 398             CACHE.put(types, d);
 399             return d;
 400         }
 401         private static synchronized SpeciesData updateCache(String types, SpeciesData d) {
 402             SpeciesData d2;
 403             assert((d2 = CACHE.get(types)) == null || d2.isPlaceholder());
 404             assert(!d.isPlaceholder());
 405             CACHE.put(types, d);
 406             return d;
 407         }
 408 
 409         static void initStatics() {}
 410 
 411         static {
 412             // pre-fill the BMH speciesdata cache with BMH's inner classes
 413             final Class<BoundMethodHandle> rootCls = BoundMethodHandle.class;
 414             try {
 415                 for (Class<?> c : rootCls.getDeclaredClasses()) {
 416                     if (rootCls.isAssignableFrom(c)) {
 417                         final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class);
 418                         SpeciesData d = Factory.speciesDataFromConcreteBMHClass(cbmh);
 419                         assert(d != null) : cbmh.getName();
 420                         assert(d.clazz == cbmh);
 421                         assert(d == lookupCache(d.typeChars));
 422                     }
 423                 }
 424             } catch (Throwable e) {
 425                 throw newInternalError(e);
 426             }
 427 
 428             for (SpeciesData d : CACHE.values()) {
 429                 d.initForBootstrap();
 430             }
 431             // Note:  Do not simplify this, because INIT_DONE must not be
 432             // a compile-time constant during bootstrapping.
 433             INIT_DONE = Boolean.TRUE;
 434         }
 435     }
 436 
 437     static SpeciesData getSpeciesData(String types) {
 438         return SpeciesData.get(types);
 439     }
 440 
 441     /**
 442      * Generation of concrete BMH classes.
 443      *
 444      * A concrete BMH species is fit for binding a number of values adhering to a
 445      * given type pattern. Reference types are erased.
 446      *
 447      * BMH species are cached by type pattern.
 448      *
 449      * A BMH species has a number of fields with the concrete (possibly erased) types of
 450      * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs,
 451      * which can be included as names in lambda forms.
 452      */
 453     static class Factory {
 454 
 455         static final String JLO_SIG  = "Ljava/lang/Object;";
 456         static final String JLS_SIG  = "Ljava/lang/String;";
 457         static final String JLC_SIG  = "Ljava/lang/Class;";
 458         static final String MH       = "java/lang/invoke/MethodHandle";
 459         static final String MH_SIG   = "L"+MH+";";
 460         static final String BMH      = "java/lang/invoke/BoundMethodHandle";
 461         static final String BMH_SIG  = "L"+BMH+";";
 462         static final String SPECIES_DATA     = "java/lang/invoke/BoundMethodHandle$SpeciesData";
 463         static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";";
 464 
 465         static final String SPECIES_PREFIX_NAME = "Species_";
 466         static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME;
 467 
 468         static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG;
 469         static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG;
 470         static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG;
 471         static final String VOID_SIG   = "()V";
 472         static final String INT_SIG    = "()I";
 473 
 474         static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;";
 475 
 476         static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
 477 
 478         /**
 479          * Generate a concrete subclass of BMH for a given combination of bound types.
 480          *
 481          * A concrete BMH species adheres to the following schema:
 482          *
 483          * <pre>
 484          * class Species_[[types]] extends BoundMethodHandle {
 485          *     [[fields]]
 486          *     final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); }
 487          * }
 488          * </pre>
 489          *
 490          * The {@code [[types]]} signature is precisely the string that is passed to this
 491          * method.
 492          *
 493          * The {@code [[fields]]} section consists of one field definition per character in
 494          * the type signature, adhering to the naming schema described in the definition of
 495          * {@link #makeFieldName}.
 496          *
 497          * For example, a concrete BMH species for two reference and one integral bound values
 498          * would have the following shape:
 499          *
 500          * <pre>
 501          * class BoundMethodHandle { ... private static
 502          * final class Species_LLI extends BoundMethodHandle {
 503          *     final Object argL0;
 504          *     final Object argL1;
 505          *     final int argI2;
 506          *     private Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
 507          *         super(mt, lf);
 508          *         this.argL0 = argL0;
 509          *         this.argL1 = argL1;
 510          *         this.argI2 = argI2;
 511          *     }
 512          *     public final SpeciesData speciesData() { return SPECIES_DATA; }
 513          *     public final int fieldCount() { return 3; }
 514          *     public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("LLI", Species_LLI.class);
 515          *     public BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
 516          *         return new Species_LLI(mt, lf, argL0, argL1, argI2);
 517          *     }
 518          *     public final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
 519          *         return new Species_LLI(mt, lf, argL0, argL1, argI2);
 520          *     }
 521          *     public final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
 522          *         return SPECIES_DATA.extendWith(L_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 523          *     }
 524          *     public final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
 525          *         return SPECIES_DATA.extendWith(I_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 526          *     }
 527          *     public final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
 528          *         return SPECIES_DATA.extendWith(J_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 529          *     }
 530          *     public final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
 531          *         return SPECIES_DATA.extendWith(F_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 532          *     }
 533          *     public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
 534          *         return SPECIES_DATA.extendWith(D_TYPE).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 535          *     }
 536          * }
 537          * </pre>
 538          *
 539          * @param types the type signature, wherein reference types are erased to 'L'
 540          * @return the generated concrete BMH class
 541          */
 542         static Class<? extends BoundMethodHandle> generateConcreteBMHClass(String types) {
 543             final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 544 
 545             String shortTypes = LambdaForm.shortenSignature(types);
 546             final String className  = SPECIES_PREFIX_PATH + shortTypes;
 547             final String sourceFile = SPECIES_PREFIX_NAME + shortTypes;
 548             cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null);
 549             cw.visitSource(sourceFile, null);
 550 
 551             // emit static types and SPECIES_DATA fields
 552             cw.visitField(ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null).visitEnd();
 553 
 554             // emit bound argument fields
 555             for (int i = 0; i < types.length(); ++i) {
 556                 final char t = types.charAt(i);
 557                 final String fieldName = makeFieldName(types, i);
 558                 final String fieldDesc = t == 'L' ? JLO_SIG : String.valueOf(t);
 559                 cw.visitField(ACC_FINAL, fieldName, fieldDesc, null, null).visitEnd();
 560             }
 561 
 562             MethodVisitor mv;
 563 
 564             // emit constructor
 565             mv = cw.visitMethod(ACC_PRIVATE, "<init>", makeSignature(types, true), null, null);
 566             mv.visitCode();
 567             mv.visitVarInsn(ALOAD, 0); // this
 568             mv.visitVarInsn(ALOAD, 1); // type
 569             mv.visitVarInsn(ALOAD, 2); // form
 570 
 571             mv.visitMethodInsn(INVOKESPECIAL, BMH, "<init>", makeSignature("", true), false);
 572 
 573             for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
 574                 // i counts the arguments, j counts corresponding argument slots
 575                 char t = types.charAt(i);
 576                 mv.visitVarInsn(ALOAD, 0);
 577                 mv.visitVarInsn(typeLoadOp(t), j + 3); // parameters start at 3
 578                 mv.visitFieldInsn(PUTFIELD, className, makeFieldName(types, i), typeSig(t));
 579                 if (t == 'J' || t == 'D') {
 580                     ++j; // adjust argument register access
 581                 }
 582             }
 583 
 584             mv.visitInsn(RETURN);
 585             mv.visitMaxs(0, 0);
 586             mv.visitEnd();
 587 
 588             // emit implementation of speciesData()
 589             mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "speciesData", MYSPECIES_DATA_SIG, null, null);
 590             mv.visitCode();
 591             mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 592             mv.visitInsn(ARETURN);
 593             mv.visitMaxs(0, 0);
 594             mv.visitEnd();
 595 
 596             // emit implementation of fieldCount()
 597             mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "fieldCount", INT_SIG, null, null);
 598             mv.visitCode();
 599             int fc = types.length();
 600             if (fc <= (ICONST_5 - ICONST_0)) {
 601                 mv.visitInsn(ICONST_0 + fc);
 602             } else {
 603                 mv.visitIntInsn(SIPUSH, fc);
 604             }
 605             mv.visitInsn(IRETURN);
 606             mv.visitMaxs(0, 0);
 607             mv.visitEnd();
 608             // emit make()  ...factory method wrapping constructor
 609             mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "make", makeSignature(types, false), null, null);
 610             mv.visitCode();
 611             // make instance
 612             mv.visitTypeInsn(NEW, className);
 613             mv.visitInsn(DUP);
 614             // load mt, lf
 615             mv.visitVarInsn(ALOAD, 0);  // type
 616             mv.visitVarInsn(ALOAD, 1);  // form
 617             // load factory method arguments
 618             for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
 619                 // i counts the arguments, j counts corresponding argument slots
 620                 char t = types.charAt(i);
 621                 mv.visitVarInsn(typeLoadOp(t), j + 2); // parameters start at 3
 622                 if (t == 'J' || t == 'D') {
 623                     ++j; // adjust argument register access
 624                 }
 625             }
 626 
 627             // finally, invoke the constructor and return
 628             mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true));
 629             mv.visitInsn(ARETURN);
 630             mv.visitMaxs(0, 0);
 631             mv.visitEnd();
 632 
 633             // emit copyWith()
 634             mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "copyWith", makeSignature("", false), null, null);
 635             mv.visitCode();
 636             // make instance
 637             mv.visitTypeInsn(NEW, className);
 638             mv.visitInsn(DUP);
 639             // load mt, lf
 640             mv.visitVarInsn(ALOAD, 1);
 641             mv.visitVarInsn(ALOAD, 2);
 642             // put fields on the stack
 643             emitPushFields(types, className, mv);
 644             // finally, invoke the constructor and return
 645             mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false);
 646             mv.visitInsn(ARETURN);
 647             mv.visitMaxs(0, 0);
 648             mv.visitEnd();
 649 
 650             // for each type, emit copyWithExtendT()
 651             for (byte bt = 0; bt < ARG_TYPE_LIMIT; bt++) {
 652                 char t = basicTypeChar(bt);
 653                 mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "copyWithExtend" + t, makeSignature(String.valueOf(t), false), null, E_THROWABLE);
 654                 mv.visitCode();
 655                 // return SPECIES_DATA.extendWith(t).constructor[0].invokeBasic(mt, lf, argL0, ..., narg)
 656                 // obtain constructor
 657                 mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 658                 int iconstInsn = ICONST_0 + bt;
 659                 assert(iconstInsn <= ICONST_5);
 660                 mv.visitInsn(iconstInsn);
 661                 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWith", BMHSPECIES_DATA_EWI_SIG, false);
 662                 mv.visitFieldInsn(GETFIELD, SPECIES_DATA, "constructor", "[" + MH_SIG);
 663                 mv.visitInsn(ICONST_0);
 664                 mv.visitInsn(AALOAD);
 665                 // load mt, lf
 666                 mv.visitVarInsn(ALOAD, 1);
 667                 mv.visitVarInsn(ALOAD, 2);
 668                 // put fields on the stack
 669                 emitPushFields(types, className, mv);
 670                 // put narg on stack
 671                 mv.visitVarInsn(typeLoadOp(t), 3);
 672                 // finally, invoke the constructor and return
 673                 mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + t, false), false);
 674                 mv.visitInsn(ARETURN);
 675                 mv.visitMaxs(0, 0);
 676                 mv.visitEnd();
 677             }
 678 
 679             // emit class initializer
 680             mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", VOID_SIG, null, null);
 681             mv.visitCode();
 682             mv.visitLdcInsn(types);
 683             mv.visitLdcInsn(Type.getObjectType(className));
 684             mv.visitMethodInsn(INVOKESTATIC, SPECIES_DATA, "getForClass", BMHSPECIES_DATA_GFC_SIG, false);
 685             mv.visitFieldInsn(PUTSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 686             mv.visitInsn(RETURN);
 687             mv.visitMaxs(0, 0);
 688             mv.visitEnd();
 689 
 690             cw.visitEnd();
 691 
 692             // load class
 693             final byte[] classFile = cw.toByteArray();
 694             InvokerBytecodeGenerator.maybeDump(className, classFile);
 695             Class<? extends BoundMethodHandle> bmhClass =
 696                 //UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class);
 697                 UNSAFE.defineClass(className, classFile, 0, classFile.length,
 698                                    BoundMethodHandle.class.getClassLoader(), null)
 699                     .asSubclass(BoundMethodHandle.class);
 700             UNSAFE.ensureClassInitialized(bmhClass);
 701 
 702             return bmhClass;
 703         }
 704 
 705         private static int typeLoadOp(char t) {
 706             switch (t) {
 707             case 'L': return ALOAD;
 708             case 'I': return ILOAD;
 709             case 'J': return LLOAD;
 710             case 'F': return FLOAD;
 711             case 'D': return DLOAD;
 712             default : throw new InternalError("unrecognized type " + t);
 713             }
 714         }
 715 
 716         private static void emitPushFields(String types, String className, MethodVisitor mv) {
 717             for (int i = 0; i < types.length(); ++i) {
 718                 char tc = types.charAt(i);
 719                 mv.visitVarInsn(ALOAD, 0);
 720                 mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc));
 721             }
 722         }
 723 
 724         static String typeSig(char t) {
 725             return t == 'L' ? JLO_SIG : String.valueOf(t);
 726         }
 727 
 728         //
 729         // Getter MH generation.
 730         //
 731 
 732         private static MethodHandle makeGetter(Class<?> cbmhClass, String types, int index) {
 733             String fieldName = makeFieldName(types, index);
 734             Class<?> fieldType = Wrapper.forBasicType(types.charAt(index)).primitiveType();
 735             try {
 736                 return LOOKUP.findGetter(cbmhClass, fieldName, fieldType);
 737             } catch (NoSuchFieldException | IllegalAccessException e) {
 738                 throw newInternalError(e);
 739             }
 740         }
 741 
 742         static MethodHandle[] makeGetters(Class<?> cbmhClass, String types, MethodHandle[] mhs) {
 743             if (mhs == null)  mhs = new MethodHandle[types.length()];
 744             for (int i = 0; i < mhs.length; ++i) {
 745                 mhs[i] = makeGetter(cbmhClass, types, i);
 746                 assert(mhs[i].internalMemberName().getDeclaringClass() == cbmhClass);
 747             }
 748             return mhs;
 749         }
 750 
 751         static MethodHandle[] makeCtors(Class<? extends BoundMethodHandle> cbmh, String types, MethodHandle mhs[]) {
 752             if (mhs == null)  mhs = new MethodHandle[1];
 753             if (types.equals(""))  return mhs;  // hack for empty BMH species
 754             mhs[0] = makeCbmhCtor(cbmh, types);
 755             return mhs;
 756         }
 757 
 758         static NamedFunction[] makeNominalGetters(Class<?> cbmhClass, String types, NamedFunction[] nfs, MethodHandle[] getters) {
 759             if (nfs == null)  nfs = new NamedFunction[types.length()];
 760             for (int i = 0; i < nfs.length; ++i) {
 761                 nfs[i] = new NamedFunction(getters[i]);
 762             }
 763             return nfs;
 764         }
 765 
 766         //
 767         // Auxiliary methods.
 768         //
 769 
 770         static SpeciesData speciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) {
 771             try {
 772                 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
 773                 return (SpeciesData) F_SPECIES_DATA.get(null);
 774             } catch (ReflectiveOperationException ex) {
 775                 throw newInternalError(ex);
 776             }
 777         }
 778 
 779         /**
 780          * Field names in concrete BMHs adhere to this pattern:
 781          * arg + type + index
 782          * where type is a single character (L, I, J, F, D).
 783          */
 784         private static String makeFieldName(String types, int index) {
 785             assert index >= 0 && index < types.length();
 786             return "arg" + types.charAt(index) + index;
 787         }
 788 
 789         private static String makeSignature(String types, boolean ctor) {
 790             StringBuilder buf = new StringBuilder(SIG_INCIPIT);
 791             for (char c : types.toCharArray()) {
 792                 buf.append(typeSig(c));
 793             }
 794             return buf.append(')').append(ctor ? "V" : BMH_SIG).toString();
 795         }
 796 
 797         static MethodHandle makeCbmhCtor(Class<? extends BoundMethodHandle> cbmh, String types) {
 798             try {
 799                 return LOOKUP.findStatic(cbmh, "make", MethodType.fromMethodDescriptorString(makeSignature(types, false), null));
 800             } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) {
 801                 throw newInternalError(e);
 802             }
 803         }
 804     }
 805 
 806     private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP;
 807 
 808     static void initStatics() {}
 809     static { SpeciesData.initStatics(); }
 810 
 811     /**
 812      * All subclasses must provide such a value describing their type signature.
 813      */
 814     static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY;
 815 
 816     private static final SpeciesData[] SPECIES_DATA_CACHE = new SpeciesData[5];
 817     private static SpeciesData checkCache(int size, String types) {
 818         int idx = size - 1;
 819         SpeciesData data = SPECIES_DATA_CACHE[idx];
 820         if (data != null)  return data;
 821         SPECIES_DATA_CACHE[idx] = data = getSpeciesData(types);
 822         return data;
 823     }
 824     static SpeciesData speciesData_L()     { return checkCache(1, "L"); }
 825     static SpeciesData speciesData_LL()    { return checkCache(2, "LL"); }
 826     static SpeciesData speciesData_LLL()   { return checkCache(3, "LLL"); }
 827     static SpeciesData speciesData_LLLL()  { return checkCache(4, "LLLL"); }
 828     static SpeciesData speciesData_LLLLL() { return checkCache(5, "LLLLL"); }
 829 }