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