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 return d; 408 } 409 static SpeciesData getForClass(String types, Class<? extends BoundMethodHandle> clazz) { 410 // clazz is a new class which is initializing its SPECIES_DATA field 411 return updateCache(types, new SpeciesData(types, clazz)); 412 } 413 private static synchronized SpeciesData lookupCache(String types) { 414 SpeciesData d = CACHE.get(types); 415 if (d != null) return d; 416 d = new SpeciesData(types); 417 assert(d.isPlaceholder()); 418 CACHE.put(types, d); 419 return d; 420 } 421 private static synchronized SpeciesData updateCache(String types, SpeciesData d) { 422 SpeciesData d2; 423 assert((d2 = CACHE.get(types)) == null || d2.isPlaceholder()); 424 assert(!d.isPlaceholder()); 425 CACHE.put(types, d); 426 return d; 427 } 428 429 static { 430 // pre-fill the BMH speciesdata cache with BMH's inner classes 431 final Class<BoundMethodHandle> rootCls = BoundMethodHandle.class; 432 try { 433 for (Class<?> c : rootCls.getDeclaredClasses()) { 434 if (rootCls.isAssignableFrom(c)) { 435 final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class); 436 SpeciesData d = Factory.speciesDataFromConcreteBMHClass(cbmh); 437 assert(d != null) : cbmh.getName(); 438 assert(d.clazz == cbmh); 439 assert(d == lookupCache(d.typeChars)); 440 } 441 } 442 } catch (Throwable e) { 443 throw newInternalError(e); 444 } 445 446 for (SpeciesData d : CACHE.values()) { 447 d.initForBootstrap(); 448 } 449 // Note: Do not simplify this, because INIT_DONE must not be 450 // a compile-time constant during bootstrapping. 451 INIT_DONE = Boolean.TRUE; 452 } 453 } 454 455 static SpeciesData getSpeciesData(String types) { 456 return SpeciesData.get(types); 457 } 458 459 /** 460 * Generation of concrete BMH classes. 461 * 462 * A concrete BMH species is fit for binding a number of values adhering to a 463 * given type pattern. Reference types are erased. 464 * 465 * BMH species are cached by type pattern. 466 * 467 * A BMH species has a number of fields with the concrete (possibly erased) types of 468 * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs, 469 * which can be included as names in lambda forms. 470 */ 471 static class Factory { 472 473 static final String JLO_SIG = "Ljava/lang/Object;"; 474 static final String JLS_SIG = "Ljava/lang/String;"; 475 static final String JLC_SIG = "Ljava/lang/Class;"; 476 static final String MH = "java/lang/invoke/MethodHandle"; 477 static final String MH_SIG = "L"+MH+";"; 478 static final String BMH = "java/lang/invoke/BoundMethodHandle"; 479 static final String BMH_SIG = "L"+BMH+";"; 480 static final String SPECIES_DATA = "java/lang/invoke/BoundMethodHandle$SpeciesData"; 481 static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";"; 482 483 static final String SPECIES_PREFIX_NAME = "Species_"; 484 static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME; 485 486 static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG; 487 static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG; 488 static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG; 489 static final String VOID_SIG = "()V"; 490 static final String INT_SIG = "()I"; 491 492 static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;"; 493 494 static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" }; 495 496 /** 497 * Generate a concrete subclass of BMH for a given combination of bound types. 498 * 499 * A concrete BMH species adheres to the following schema: 500 * 501 * <pre> 502 * class Species_[[types]] extends BoundMethodHandle { 503 * [[fields]] 504 * final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); } 505 * } 506 * </pre> 507 * 508 * The {@code [[types]]} signature is precisely the string that is passed to this 509 * method. 510 * 511 * The {@code [[fields]]} section consists of one field definition per character in 512 * the type signature, adhering to the naming schema described in the definition of 513 * {@link #makeFieldName}. 514 * 515 * For example, a concrete BMH species for two reference and one integral bound values 516 * would have the following shape: 517 * 518 * <pre> 519 * class BoundMethodHandle { ... private static 520 * final class Species_LLI extends BoundMethodHandle { 521 * final Object argL0; 522 * final Object argL1; 523 * final int argI2; 524 * private Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { 525 * super(mt, lf); 526 * this.argL0 = argL0; 527 * this.argL1 = argL1; 528 * this.argI2 = argI2; 529 * } 530 * final SpeciesData speciesData() { return SPECIES_DATA; } 531 * final int fieldCount() { return 3; } 532 * static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("LLI", Species_LLI.class); 533 * static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) { 534 * return new Species_LLI(mt, lf, argL0, argL1, argI2); 535 * } 536 * final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) { 537 * return new Species_LLI(mt, lf, argL0, argL1, argI2); 538 * } 539 * final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) { 540 * return SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 541 * } 542 * final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) { 543 * return SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 544 * } 545 * final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) { 546 * return SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 547 * } 548 * final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) { 549 * return SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 550 * } 551 * public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) { 552 * return SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg); 553 * } 554 * } 555 * </pre> 556 * 557 * @param types the type signature, wherein reference types are erased to 'L' 558 * @return the generated concrete BMH class 559 */ 560 static Class<? extends BoundMethodHandle> generateConcreteBMHClass(String types) { 561 final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); 562 563 String shortTypes = LambdaForm.shortenSignature(types); 564 final String className = SPECIES_PREFIX_PATH + shortTypes; 565 final String sourceFile = SPECIES_PREFIX_NAME + shortTypes; 566 final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC 567 cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null); 568 cw.visitSource(sourceFile, null); 569 570 // emit static types and SPECIES_DATA fields 571 cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null).visitEnd(); 572 573 // emit bound argument fields 574 for (int i = 0; i < types.length(); ++i) { 575 final char t = types.charAt(i); 576 final String fieldName = makeFieldName(types, i); 577 final String fieldDesc = t == 'L' ? JLO_SIG : String.valueOf(t); 578 cw.visitField(ACC_FINAL, fieldName, fieldDesc, null, null).visitEnd(); 579 } 580 581 MethodVisitor mv; 582 583 // emit constructor 584 mv = cw.visitMethod(ACC_PRIVATE, "<init>", makeSignature(types, true), null, null); 585 mv.visitCode(); 586 mv.visitVarInsn(ALOAD, 0); // this 587 mv.visitVarInsn(ALOAD, 1); // type 588 mv.visitVarInsn(ALOAD, 2); // form 589 590 mv.visitMethodInsn(INVOKESPECIAL, BMH, "<init>", makeSignature("", true), false); 591 592 for (int i = 0, j = 0; i < types.length(); ++i, ++j) { 593 // i counts the arguments, j counts corresponding argument slots 594 char t = types.charAt(i); 595 mv.visitVarInsn(ALOAD, 0); 596 mv.visitVarInsn(typeLoadOp(t), j + 3); // parameters start at 3 597 mv.visitFieldInsn(PUTFIELD, className, makeFieldName(types, i), typeSig(t)); 598 if (t == 'J' || t == 'D') { 599 ++j; // adjust argument register access 600 } 601 } 602 603 mv.visitInsn(RETURN); 604 mv.visitMaxs(0, 0); 605 mv.visitEnd(); 606 607 // emit implementation of speciesData() 608 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "speciesData", MYSPECIES_DATA_SIG, null, null); 609 mv.visitCode(); 610 mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG); 611 mv.visitInsn(ARETURN); 612 mv.visitMaxs(0, 0); 613 mv.visitEnd(); 614 615 // emit implementation of fieldCount() 616 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "fieldCount", INT_SIG, null, null); 617 mv.visitCode(); 618 int fc = types.length(); 619 if (fc <= (ICONST_5 - ICONST_0)) { 620 mv.visitInsn(ICONST_0 + fc); 621 } else { 622 mv.visitIntInsn(SIPUSH, fc); 623 } 624 mv.visitInsn(IRETURN); 625 mv.visitMaxs(0, 0); 626 mv.visitEnd(); 627 // emit make() ...factory method wrapping constructor 628 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, "make", makeSignature(types, 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, 0); // type 635 mv.visitVarInsn(ALOAD, 1); // form 636 // load factory method arguments 637 for (int i = 0, j = 0; i < types.length(); ++i, ++j) { 638 // i counts the arguments, j counts corresponding argument slots 639 char t = types.charAt(i); 640 mv.visitVarInsn(typeLoadOp(t), j + 2); // parameters start at 3 641 if (t == 'J' || t == 'D') { 642 ++j; // adjust argument register access 643 } 644 } 645 646 // finally, invoke the constructor and return 647 mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false); 648 mv.visitInsn(ARETURN); 649 mv.visitMaxs(0, 0); 650 mv.visitEnd(); 651 652 // emit copyWith() 653 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWith", makeSignature("", false), null, null); 654 mv.visitCode(); 655 // make instance 656 mv.visitTypeInsn(NEW, className); 657 mv.visitInsn(DUP); 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 // finally, invoke the constructor and return 664 mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false); 665 mv.visitInsn(ARETURN); 666 mv.visitMaxs(0, 0); 667 mv.visitEnd(); 668 669 // for each type, emit copyWithExtendT() 670 for (BasicType type : BasicType.ARG_TYPES) { 671 int ord = type.ordinal(); 672 char btChar = type.basicTypeChar(); 673 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWithExtend" + btChar, makeSignature(String.valueOf(btChar), false), null, E_THROWABLE); 674 mv.visitCode(); 675 // return SPECIES_DATA.extendWith(t).constructor().invokeBasic(mt, lf, argL0, ..., narg) 676 // obtain constructor 677 mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG); 678 int iconstInsn = ICONST_0 + ord; 679 assert(iconstInsn <= ICONST_5); 680 mv.visitInsn(iconstInsn); 681 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWith", BMHSPECIES_DATA_EWI_SIG, false); 682 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "constructor", "()" + MH_SIG, false); 683 // load mt, lf 684 mv.visitVarInsn(ALOAD, 1); 685 mv.visitVarInsn(ALOAD, 2); 686 // put fields on the stack 687 emitPushFields(types, className, mv); 688 // put narg on stack 689 mv.visitVarInsn(typeLoadOp(btChar), 3); 690 // finally, invoke the constructor and return 691 mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + btChar, false), false); 692 mv.visitInsn(ARETURN); 693 mv.visitMaxs(0, 0); 694 mv.visitEnd(); 695 } 696 697 // emit class initializer 698 mv = cw.visitMethod(NOT_ACC_PUBLIC | ACC_STATIC, "<clinit>", VOID_SIG, null, null); 699 mv.visitCode(); 700 mv.visitLdcInsn(types); 701 mv.visitLdcInsn(Type.getObjectType(className)); 702 mv.visitMethodInsn(INVOKESTATIC, SPECIES_DATA, "getForClass", BMHSPECIES_DATA_GFC_SIG, false); 703 mv.visitFieldInsn(PUTSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG); 704 mv.visitInsn(RETURN); 705 mv.visitMaxs(0, 0); 706 mv.visitEnd(); 707 708 cw.visitEnd(); 709 710 // load class 711 final byte[] classFile = cw.toByteArray(); 712 InvokerBytecodeGenerator.maybeDump(className, classFile); 713 Class<? extends BoundMethodHandle> bmhClass = 714 //UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class); 715 UNSAFE.defineClass(className, classFile, 0, classFile.length, 716 BoundMethodHandle.class.getClassLoader(), null) 717 .asSubclass(BoundMethodHandle.class); 718 UNSAFE.ensureClassInitialized(bmhClass); 719 720 return bmhClass; 721 } 722 723 private static int typeLoadOp(char t) { 724 switch (t) { 725 case 'L': return ALOAD; 726 case 'I': return ILOAD; 727 case 'J': return LLOAD; 728 case 'F': return FLOAD; 729 case 'D': return DLOAD; 730 default : throw newInternalError("unrecognized type " + t); 731 } 732 } 733 734 private static void emitPushFields(String types, String className, MethodVisitor mv) { 735 for (int i = 0; i < types.length(); ++i) { 736 char tc = types.charAt(i); 737 mv.visitVarInsn(ALOAD, 0); 738 mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc)); 739 } 740 } 741 742 static String typeSig(char t) { 743 return t == 'L' ? JLO_SIG : String.valueOf(t); 744 } 745 746 // 747 // Getter MH generation. 748 // 749 750 private static MethodHandle makeGetter(Class<?> cbmhClass, String types, int index) { 751 String fieldName = makeFieldName(types, index); 752 Class<?> fieldType = Wrapper.forBasicType(types.charAt(index)).primitiveType(); 753 try { 754 return LOOKUP.findGetter(cbmhClass, fieldName, fieldType); 755 } catch (NoSuchFieldException | IllegalAccessException e) { 756 throw newInternalError(e); 757 } 758 } 759 760 static MethodHandle[] makeGetters(Class<?> cbmhClass, String types, MethodHandle[] mhs) { 761 if (mhs == null) mhs = new MethodHandle[types.length()]; 762 for (int i = 0; i < mhs.length; ++i) { 763 mhs[i] = makeGetter(cbmhClass, types, i); 764 assert(mhs[i].internalMemberName().getDeclaringClass() == cbmhClass); 765 } 766 return mhs; 767 } 768 769 static MethodHandle[] makeCtors(Class<? extends BoundMethodHandle> cbmh, String types, MethodHandle mhs[]) { 770 if (mhs == null) mhs = new MethodHandle[1]; 771 if (types.equals("")) return mhs; // hack for empty BMH species 772 mhs[0] = makeCbmhCtor(cbmh, types); 773 return mhs; 774 } 775 776 static NamedFunction[] makeNominalGetters(String types, NamedFunction[] nfs, MethodHandle[] getters) { 777 if (nfs == null) nfs = new NamedFunction[types.length()]; 778 for (int i = 0; i < nfs.length; ++i) { 779 nfs[i] = new NamedFunction(getters[i]); 780 } 781 return nfs; 782 } 783 784 // 785 // Auxiliary methods. 786 // 787 788 static SpeciesData speciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) { 789 try { 790 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA"); 791 return (SpeciesData) F_SPECIES_DATA.get(null); 792 } catch (ReflectiveOperationException ex) { 793 throw newInternalError(ex); 794 } 795 } 796 797 /** 798 * Field names in concrete BMHs adhere to this pattern: 799 * arg + type + index 800 * where type is a single character (L, I, J, F, D). 801 */ 802 private static String makeFieldName(String types, int index) { 803 assert index >= 0 && index < types.length(); 804 return "arg" + types.charAt(index) + index; 805 } 806 807 private static String makeSignature(String types, boolean ctor) { 808 StringBuilder buf = new StringBuilder(SIG_INCIPIT); 809 for (char c : types.toCharArray()) { 810 buf.append(typeSig(c)); 811 } 812 return buf.append(')').append(ctor ? "V" : BMH_SIG).toString(); 813 } 814 815 static MethodHandle makeCbmhCtor(Class<? extends BoundMethodHandle> cbmh, String types) { 816 try { 817 return LOOKUP.findStatic(cbmh, "make", MethodType.fromDescriptor(makeSignature(types, false), null)); 818 } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) { 819 throw newInternalError(e); 820 } 821 } 822 } 823 824 private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP; 825 826 /** 827 * All subclasses must provide such a value describing their type signature. 828 */ 829 static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY; 830 831 private static final SpeciesData[] SPECIES_DATA_CACHE = new SpeciesData[5]; 832 private static SpeciesData checkCache(int size, String types) { 833 int idx = size - 1; 834 SpeciesData data = SPECIES_DATA_CACHE[idx]; 835 if (data != null) return data; 836 SPECIES_DATA_CACHE[idx] = data = getSpeciesData(types); 837 return data; 838 } 839 static SpeciesData speciesData_L() { return checkCache(1, "L"); } 840 static SpeciesData speciesData_LL() { return checkCache(2, "LL"); } 841 static SpeciesData speciesData_LLL() { return checkCache(3, "LLL"); } 842 static SpeciesData speciesData_LLLL() { return checkCache(4, "LLLL"); } 843 static SpeciesData speciesData_LLLLL() { return checkCache(5, "LLLLL"); } 844 }