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