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