1 /* 2 * Copyright (c) 2017, 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.loader.BootLoader; 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 jdk.internal.vm.annotation.Stable; 33 import sun.invoke.util.BytecodeName; 34 35 import java.lang.reflect.*; 36 import java.security.AccessController; 37 import java.security.PrivilegedAction; 38 import java.security.ProtectionDomain; 39 import java.util.*; 40 import java.util.concurrent.ConcurrentHashMap; 41 42 import static java.lang.invoke.LambdaForm.*; 43 import static java.lang.invoke.MethodHandleNatives.Constants.REF_getStatic; 44 import static java.lang.invoke.MethodHandleNatives.Constants.REF_putStatic; 45 import static java.lang.invoke.MethodHandleStatics.*; 46 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; 47 import static jdk.internal.org.objectweb.asm.Opcodes.*; 48 49 /** 50 * Class specialization code. 51 * @param <T> top class under which species classes are created. 52 * @param <K> key which identifies individual specializations. 53 * @param <S> species data type. 54 */ 55 /*non-public*/ 56 abstract class ClassSpecializer<T,K,S extends ClassSpecializer<T,K,S>.SpeciesData> { 57 private final Class<T> topClass; 58 private final Class<K> keyType; 59 private final Class<S> metaType; 60 private final MemberName sdAccessor; 61 private final String sdFieldName; 62 private final List<MemberName> transformMethods; 63 private final MethodType baseConstructorType; 64 private final S topSpecies; 65 private final ConcurrentHashMap<K, Object> cache = new ConcurrentHashMap<>(); 66 private final Factory factory; 67 private @Stable boolean topClassIsSuper; 68 69 /** Return the top type mirror, for type {@code T} */ 70 public final Class<T> topClass() { return topClass; } 71 72 /** Return the key type mirror, for type {@code K} */ 73 public final Class<K> keyType() { return keyType; } 74 75 /** Return the species metadata type mirror, for type {@code S} */ 76 public final Class<S> metaType() { return metaType; } 77 78 /** Report the leading arguments (if any) required by every species factory. 79 * Every species factory adds its own field types as additional arguments, 80 * but these arguments always come first, in every factory method. 81 */ 82 protected MethodType baseConstructorType() { return baseConstructorType; } 83 84 /** Return the trivial species for the null sequence of arguments. */ 85 protected final S topSpecies() { return topSpecies; } 86 87 /** Return the list of transform methods originally given at creation of this specializer. */ 88 protected final List<MemberName> transformMethods() { return transformMethods; } 89 90 /** Return the factory object used to build and load concrete species code. */ 91 protected final Factory factory() { return factory; } 92 93 /** 94 * Constructor for this class specializer. 95 * @param topClass type mirror for T 96 * @param keyType type mirror for K 97 * @param metaType type mirror for S 98 * @param baseConstructorType principal constructor type 99 * @param sdAccessor the method used to get the speciesData 100 * @param sdFieldName the name of the species data field, inject the speciesData object 101 * @param transformMethods optional list of transformMethods 102 */ 103 protected ClassSpecializer(Class<T> topClass, 104 Class<K> keyType, 105 Class<S> metaType, 106 MethodType baseConstructorType, 107 MemberName sdAccessor, 108 String sdFieldName, 109 List<MemberName> transformMethods) { 110 this.topClass = topClass; 111 this.keyType = keyType; 112 this.metaType = metaType; 113 this.sdAccessor = sdAccessor; 114 this.transformMethods = List.copyOf(transformMethods); 115 this.sdFieldName = sdFieldName; 116 this.baseConstructorType = baseConstructorType.changeReturnType(void.class); 117 this.factory = makeFactory(); 118 K tsk = topSpeciesKey(); 119 S topSpecies = null; 120 if (tsk != null && topSpecies == null) { 121 // if there is a key, build the top species if needed: 122 topSpecies = findSpecies(tsk); 123 } 124 this.topSpecies = topSpecies; 125 } 126 127 // Utilities for subclass constructors: 128 protected static <T> Constructor<T> reflectConstructor(Class<T> defc, Class<?>... ptypes) { 129 try { 130 return defc.getDeclaredConstructor(ptypes); 131 } catch (NoSuchMethodException ex) { 132 throw newIAE(defc.getName()+"("+MethodType.methodType(void.class, ptypes)+")", ex); 133 } 134 } 135 136 protected static Field reflectField(Class<?> defc, String name) { 137 try { 138 return defc.getDeclaredField(name); 139 } catch (NoSuchFieldException ex) { 140 throw newIAE(defc.getName()+"."+name, ex); 141 } 142 } 143 144 private static RuntimeException newIAE(String message, Throwable cause) { 145 return new IllegalArgumentException(message, cause); 146 } 147 148 @SuppressWarnings("unchecked") 149 public final S findSpecies(K key) { 150 // Note: Species instantiation may throw VirtualMachineError because of 151 // code cache overflow. If this happens the species bytecode may be 152 // loaded but not linked to its species metadata (with MH's etc). 153 // That will cause a throw out of this method with a reservation object 154 // installed in the cache. 155 // 156 // In a latter attempt to get the same species, the already-loaded 157 // class will be present in the system dictionary, causing an 158 // error when the species generator tries to reload it. 159 // We try to detect this case and link the pre-existing code. 160 // 161 // Although it would be better to start fresh by loading a new 162 // copy, we have to salvage the previously loaded but broken code. 163 // (As an alternative, we might spin a new class with a new name, 164 // or use the anonymous class mechanism.) 165 // 166 // In the end, as long as everybody goes through this method, 167 // its initialization logic will ensure only one SpeciesData will be set 168 // successfully on a concrete class if ever. 169 // The concrete class is published via SpeciesData instance 170 // returned here only after the class and species data are linked together. 171 Object reservation = new Object(); 172 S speciesData; 173 Object speciesDataOrReservation = cache.putIfAbsent(key, reservation); 174 if (speciesDataOrReservation instanceof ClassSpecializer<?, ?, ?>.SpeciesData) { 175 // already cached 176 speciesData = (S) speciesDataOrReservation; 177 } else { 178 // resolve the race for reservation 179 if (speciesDataOrReservation != null) { 180 reservation = speciesDataOrReservation; 181 } 182 synchronized (reservation) { 183 // re-check under lock 184 speciesDataOrReservation = cache.get(key); 185 if (speciesDataOrReservation == reservation) { 186 // the thread that enters synchronized (reservation) and finds 187 // reservation still in cache, tries to (re)initialize species data. 188 // if the initialization fails, the reservation object is left in CHM 189 // for next thread to pick it up and retry... 190 speciesData = factory.loadSpecies(newSpeciesData(key)); 191 if (!cache.replace(key, reservation, speciesData)) { 192 throw new AssertionError("Thought this was unreachable"); 193 } 194 } else { 195 // the thread that enters synchronized (reservation) and finds 196 // a reference that is not a reservation, has found the initialized 197 // species data... 198 assert speciesDataOrReservation instanceof ClassSpecializer<?, ?, ?>.SpeciesData; 199 speciesData = (S) speciesDataOrReservation; 200 } 201 } 202 } 203 assert(speciesData != null && speciesData.isResolved()); 204 return speciesData; 205 } 206 207 /** 208 * Meta-data wrapper for concrete subtypes of the top class. 209 * Each concrete subtype corresponds to a given sequence of basic field types (LIJFD). 210 * The fields are immutable; their values are fully specified at object construction. 211 * Each species supplies an array of getter functions which may be used in lambda forms. 212 * A concrete value is always constructed from the full tuple of its field values, 213 * accompanied by the required constructor parameters. 214 * There *may* also be transforms which cloning a species instance and 215 * either replace a constructor parameter or add one or more new field values. 216 * The shortest possible species has zero fields. 217 * Subtypes are not interrelated among themselves by subtyping, even though 218 * it would appear that a shorter species could serve as a supertype of a 219 * longer one which extends it. 220 */ 221 public abstract class SpeciesData { 222 // Bootstrapping requires circular relations Class -> SpeciesData -> Class 223 // Therefore, we need non-final links in the chain. Use @Stable fields. 224 private final K key; 225 private final List<Class<?>> fieldTypes; 226 @Stable private Class<? extends T> speciesCode; 227 @Stable private List<MethodHandle> factories; 228 @Stable private List<MethodHandle> getters; 229 @Stable private List<LambdaForm.NamedFunction> nominalGetters; 230 @Stable private final MethodHandle[] transformHelpers = new MethodHandle[transformMethods.size()]; 231 232 protected SpeciesData(K key) { 233 this.key = keyType.cast(Objects.requireNonNull(key)); 234 List<Class<?>> types = deriveFieldTypes(key); 235 this.fieldTypes = List.copyOf(types); 236 } 237 238 public final K key() { 239 return key; 240 } 241 242 protected final List<Class<?>> fieldTypes() { 243 return fieldTypes; 244 } 245 246 protected final int fieldCount() { 247 return fieldTypes.size(); 248 } 249 250 protected ClassSpecializer<T,K,S> outer() { 251 return ClassSpecializer.this; 252 } 253 254 protected final boolean isResolved() { 255 return speciesCode != null && factories != null && !factories.isEmpty(); 256 } 257 258 @Override public String toString() { 259 return metaType.getSimpleName() + "[" + key.toString() + " => " + (isResolved() ? speciesCode.getSimpleName() : "UNRESOLVED") + "]"; 260 } 261 262 @Override 263 public int hashCode() { 264 return key.hashCode(); 265 } 266 267 @Override 268 public boolean equals(Object obj) { 269 if (!(obj instanceof ClassSpecializer.SpeciesData)) { 270 return false; 271 } 272 @SuppressWarnings("rawtypes") 273 ClassSpecializer.SpeciesData that = (ClassSpecializer.SpeciesData) obj; 274 return this.outer() == that.outer() && this.key.equals(that.key); 275 } 276 277 /** Throws NPE if this species is not yet resolved. */ 278 protected final Class<? extends T> speciesCode() { 279 return Objects.requireNonNull(speciesCode); 280 } 281 282 /** 283 * Return a {@link MethodHandle} which can get the indexed field of this species. 284 * The return type is the type of the species field it accesses. 285 * The argument type is the {@code fieldHolder} class of this species. 286 */ 287 protected MethodHandle getter(int i) { 288 return getters.get(i); 289 } 290 291 /** 292 * Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that 293 * represents a MH bound to a generic invoker, which in turn forwards to the corresponding 294 * getter. 295 */ 296 protected LambdaForm.NamedFunction getterFunction(int i) { 297 LambdaForm.NamedFunction nf = nominalGetters.get(i); 298 assert(nf.memberDeclaringClassOrNull() == speciesCode()); 299 assert(nf.returnType() == BasicType.basicType(fieldTypes.get(i))); 300 return nf; 301 } 302 303 protected List<LambdaForm.NamedFunction> getterFunctions() { 304 return nominalGetters; 305 } 306 307 protected List<MethodHandle> getters() { 308 return getters; 309 } 310 311 protected MethodHandle factory() { 312 return factories.get(0); 313 } 314 315 protected MethodHandle transformHelper(int whichtm) { 316 MethodHandle mh = transformHelpers[whichtm]; 317 if (mh != null) return mh; 318 mh = deriveTransformHelper(transformMethods().get(whichtm), whichtm); 319 // Do a little type checking before we start using the MH. 320 // (It will be called with invokeBasic, so this is our only chance.) 321 final MethodType mt = transformHelperType(whichtm); 322 mh = mh.asType(mt); 323 return transformHelpers[whichtm] = mh; 324 } 325 326 private final MethodType transformHelperType(int whichtm) { 327 MemberName tm = transformMethods().get(whichtm); 328 ArrayList<Class<?>> args = new ArrayList<>(); 329 ArrayList<Class<?>> fields = new ArrayList<>(); 330 Collections.addAll(args, tm.getParameterTypes()); 331 fields.addAll(fieldTypes()); 332 List<Class<?>> helperArgs = deriveTransformHelperArguments(tm, whichtm, args, fields); 333 return MethodType.methodType(tm.getReturnType(), helperArgs); 334 } 335 336 // Hooks for subclasses: 337 338 /** 339 * Given a key, derive the list of field types, which all instances of this 340 * species must store. 341 */ 342 protected abstract List<Class<?>> deriveFieldTypes(K key); 343 344 /** 345 * Given the index of a method in the transforms list, supply a factory 346 * method that takes the arguments of the transform, plus the local fields, 347 * and produce a value of the required type. 348 * You can override this to return null or throw if there are no transforms. 349 * This method exists so that the transforms can be "grown" lazily. 350 * This is necessary if the transform *adds* a field to an instance, 351 * which sometimtes requires the creation, on the fly, of an extended species. 352 * This method is only called once for any particular parameter. 353 * The species caches the result in a private array. 354 * 355 * @param transform the transform being implemented 356 * @param whichtm the index of that transform in the original list of transforms 357 * @return the method handle which creates a new result from a mix of transform 358 * arguments and field values 359 */ 360 protected abstract MethodHandle deriveTransformHelper(MemberName transform, int whichtm); 361 362 /** 363 * During code generation, this method is called once per transform to determine 364 * what is the mix of arguments to hand to the transform-helper. The bytecode 365 * which marshals these arguments is open-coded in the species-specific transform. 366 * The two lists are of opaque objects, which you shouldn't do anything with besides 367 * reordering them into the output list. (They are both mutable, to make editing 368 * easier.) The imputed types of the args correspond to the transform's parameter 369 * list, while the imputed types of the fields correspond to the species field types. 370 * After code generation, this method may be called occasionally by error-checking code. 371 * 372 * @param transform the transform being implemented 373 * @param whichtm the index of that transform in the original list of transforms 374 * @param args a list of opaque objects representing the incoming transform arguments 375 * @param fields a list of opaque objects representing the field values of the receiver 376 * @param <X> the common element type of the various lists 377 * @return a new list 378 */ 379 protected abstract <X> List<X> deriveTransformHelperArguments(MemberName transform, int whichtm, 380 List<X> args, List<X> fields); 381 382 /** Given a key, generate the name of the class which implements the species for that key. 383 * This algorithm must be stable. 384 * 385 * @return class name, which by default is {@code outer().topClass().getName() + "$Species_" + deriveTypeString(key)} 386 */ 387 protected String deriveClassName() { 388 return outer().topClass().getName() + "$Species_" + deriveTypeString(); 389 } 390 391 /** 392 * Default implementation collects basic type characters, 393 * plus possibly type names, if some types don't correspond 394 * to basic types. 395 * 396 * @return a string suitable for use in a class name 397 */ 398 protected String deriveTypeString() { 399 List<Class<?>> types = fieldTypes(); 400 StringBuilder buf = new StringBuilder(); 401 StringBuilder end = new StringBuilder(); 402 for (Class<?> type : types) { 403 BasicType basicType = BasicType.basicType(type); 404 if (basicType.basicTypeClass() == type) { 405 buf.append(basicType.basicTypeChar()); 406 } else { 407 buf.append('V'); 408 end.append(classSig(type)); 409 } 410 } 411 String typeString; 412 if (end.length() > 0) { 413 typeString = BytecodeName.toBytecodeName(buf.append("_").append(end).toString()); 414 } else { 415 typeString = buf.toString(); 416 } 417 return LambdaForm.shortenSignature(typeString); 418 } 419 420 /** 421 * Report what immediate super-class to use for the concrete class of this species. 422 * Normally this is {@code topClass}, but if that is an interface, the factory must override. 423 * The super-class must provide a constructor which takes the {@code baseConstructorType} arguments, if any. 424 * This hook also allows the code generator to use more than one canned supertype for species. 425 * 426 * @return the super-class of the class to be generated 427 */ 428 protected Class<? extends T> deriveSuperClass() { 429 final Class<T> topc = topClass(); 430 if (!topClassIsSuper) { 431 try { 432 final Constructor<T> con = reflectConstructor(topc, baseConstructorType().parameterArray()); 433 if (!topc.isInterface() && !Modifier.isPrivate(con.getModifiers())) { 434 topClassIsSuper = true; 435 } 436 } catch (Exception|InternalError ex) { 437 // fall through... 438 } 439 if (!topClassIsSuper) { 440 throw newInternalError("must override if the top class cannot serve as a super class"); 441 } 442 } 443 return topc; 444 } 445 } 446 447 protected abstract S newSpeciesData(K key); 448 449 protected K topSpeciesKey() { 450 return null; // null means don't report a top species 451 } 452 453 /** 454 * Code generation support for instances. 455 * Subclasses can modify the behavior. 456 */ 457 public class Factory { 458 /** 459 * Get a concrete subclass of the top class for a given combination of bound types. 460 * 461 * @param speciesData the species requiring the class, not yet linked 462 * @return a linked version of the same species 463 */ 464 S loadSpecies(S speciesData) { 465 String className = speciesData.deriveClassName(); 466 assert(className.indexOf('/') < 0) : className; 467 Class<?> salvage = null; 468 try { 469 salvage = BootLoader.loadClassOrNull(className); 470 if (TRACE_RESOLVE && salvage != null) { 471 // Used by jlink species pregeneration plugin, see 472 // jdk.tools.jlink.internal.plugins.GenerateJLIClassesPlugin 473 System.out.println("[SPECIES_RESOLVE] " + className + " (salvaged)"); 474 } 475 } catch (Error ex) { 476 if (TRACE_RESOLVE) { 477 System.out.println("[SPECIES_FRESOLVE] " + className + " (Error) " + ex.getMessage()); 478 } 479 } 480 final Class<? extends T> speciesCode; 481 if (salvage != null) { 482 speciesCode = salvage.asSubclass(topClass()); 483 linkSpeciesDataToCode(speciesData, speciesCode); 484 linkCodeToSpeciesData(speciesCode, speciesData, true); 485 } else { 486 // Not pregenerated, generate the class 487 try { 488 speciesCode = generateConcreteSpeciesCode(className, speciesData); 489 if (TRACE_RESOLVE) { 490 // Used by jlink species pregeneration plugin, see 491 // jdk.tools.jlink.internal.plugins.GenerateJLIClassesPlugin 492 System.out.println("[SPECIES_RESOLVE] " + className + " (generated)"); 493 } 494 // This operation causes a lot of churn: 495 linkSpeciesDataToCode(speciesData, speciesCode); 496 // This operation commits the relation, but causes little churn: 497 linkCodeToSpeciesData(speciesCode, speciesData, false); 498 } catch (Error ex) { 499 if (TRACE_RESOLVE) { 500 System.out.println("[SPECIES_RESOLVE] " + className + " (Error #2)" ); 501 } 502 // We can get here if there is a race condition loading a class. 503 // Or maybe we are out of resources. Back out of the CHM.get and retry. 504 throw ex; 505 } 506 } 507 508 if (!speciesData.isResolved()) { 509 throw newInternalError("bad species class linkage for " + className + ": " + speciesData); 510 } 511 assert(speciesData == loadSpeciesDataFromCode(speciesCode)); 512 return speciesData; 513 } 514 515 /** 516 * Generate a concrete subclass of the top class for a given combination of bound types. 517 * 518 * A concrete species subclass roughly matches the following schema: 519 * 520 * <pre> 521 * class Species_[[types]] extends [[T]] { 522 * final [[S]] speciesData() { return ... } 523 * static [[T]] make([[fields]]) { return ... } 524 * [[fields]] 525 * final [[T]] transform([[args]]) { return ... } 526 * } 527 * </pre> 528 * 529 * The {@code [[types]]} signature is precisely the key for the species. 530 * 531 * The {@code [[fields]]} section consists of one field definition per character in 532 * the type signature, adhering to the naming schema described in the definition of 533 * {@link #chooseFieldName}. 534 * 535 * For example, a concrete species for two references and one integral bound value 536 * has a shape like the following: 537 * 538 * <pre> 539 * class TopClass { ... private static 540 * final class Species_LLI extends TopClass { 541 * final Object argL0; 542 * final Object argL1; 543 * final int argI2; 544 * private Species_LLI(CT ctarg, ..., Object argL0, Object argL1, int argI2) { 545 * super(ctarg, ...); 546 * this.argL0 = argL0; 547 * this.argL1 = argL1; 548 * this.argI2 = argI2; 549 * } 550 * final SpeciesData speciesData() { return BMH_SPECIES; } 551 * @Stable static SpeciesData BMH_SPECIES; // injected afterwards 552 * static TopClass make(CT ctarg, ..., Object argL0, Object argL1, int argI2) { 553 * return new Species_LLI(ctarg, ..., argL0, argL1, argI2); 554 * } 555 * final TopClass copyWith(CT ctarg, ...) { 556 * return new Species_LLI(ctarg, ..., argL0, argL1, argI2); 557 * } 558 * // two transforms, for the sake of illustration: 559 * final TopClass copyWithExtendL(CT ctarg, ..., Object narg) { 560 * return BMH_SPECIES.transform(L_TYPE).invokeBasic(ctarg, ..., argL0, argL1, argI2, narg); 561 * } 562 * final TopClass copyWithExtendI(CT ctarg, ..., int narg) { 563 * return BMH_SPECIES.transform(I_TYPE).invokeBasic(ctarg, ..., argL0, argL1, argI2, narg); 564 * } 565 * } 566 * </pre> 567 * 568 * @param className of the species 569 * @param speciesData what species we are generating 570 * @return the generated concrete TopClass class 571 */ 572 Class<? extends T> generateConcreteSpeciesCode(String className, ClassSpecializer<T,K,S>.SpeciesData speciesData) { 573 byte[] classFile = generateConcreteSpeciesCodeFile(className, speciesData); 574 575 // load class 576 InvokerBytecodeGenerator.maybeDump(classBCName(className), classFile); 577 Class<?> speciesCode; 578 579 ClassLoader cl = topClass().getClassLoader(); 580 ProtectionDomain pd = null; 581 if (cl != null) { 582 pd = AccessController.doPrivileged( 583 new PrivilegedAction<>() { 584 @Override 585 public ProtectionDomain run() { 586 return topClass().getProtectionDomain(); 587 } 588 }); 589 } 590 try { 591 speciesCode = UNSAFE.defineClass(className, classFile, 0, classFile.length, cl, pd); 592 } catch (Exception ex) { 593 throw newInternalError(ex); 594 } 595 596 return speciesCode.asSubclass(topClass()); 597 } 598 599 // These are named like constants because there is only one per specialization scheme: 600 private final String SPECIES_DATA = classBCName(metaType); 601 private final String SPECIES_DATA_SIG = classSig(SPECIES_DATA); 602 private final String SPECIES_DATA_NAME = sdAccessor.getName(); 603 private final int SPECIES_DATA_MODS = sdAccessor.getModifiers(); 604 private final List<String> TRANSFORM_NAMES; // derived from transformMethods 605 private final List<MethodType> TRANSFORM_TYPES; 606 private final List<Integer> TRANSFORM_MODS; 607 { 608 // Tear apart transformMethods to get the names, types, and modifiers. 609 List<String> tns = new ArrayList<>(); 610 List<MethodType> tts = new ArrayList<>(); 611 List<Integer> tms = new ArrayList<>(); 612 for (int i = 0; i < transformMethods.size(); i++) { 613 MemberName tm = transformMethods.get(i); 614 tns.add(tm.getName()); 615 final MethodType tt = tm.getMethodType(); 616 tts.add(tt); 617 tms.add(tm.getModifiers()); 618 } 619 TRANSFORM_NAMES = List.of(tns.toArray(new String[0])); 620 TRANSFORM_TYPES = List.of(tts.toArray(new MethodType[0])); 621 TRANSFORM_MODS = List.of(tms.toArray(new Integer[0])); 622 } 623 private static final int ACC_PPP = ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED; 624 625 /*non-public*/ byte[] generateConcreteSpeciesCodeFile(String className0, ClassSpecializer<T,K,S>.SpeciesData speciesData) { 626 final String className = classBCName(className0); 627 final String superClassName = classBCName(speciesData.deriveSuperClass()); 628 629 final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES); 630 final int NOT_ACC_PUBLIC = 0; // not ACC_PUBLIC 631 cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, superClassName, null); 632 633 final String sourceFile = className.substring(className.lastIndexOf('.')+1); 634 cw.visitSource(sourceFile, null); 635 636 // emit static types and BMH_SPECIES fields 637 FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, sdFieldName, SPECIES_DATA_SIG, null, null); 638 fw.visitAnnotation(STABLE_SIG, true); 639 fw.visitEnd(); 640 641 // handy holder for dealing with groups of typed values (ctor arguments and fields) 642 class Var { 643 final int index; 644 final String name; 645 final Class<?> type; 646 final String desc; 647 final BasicType basicType; 648 final int slotIndex; 649 Var(int index, int slotIndex) { 650 this.index = index; 651 this.slotIndex = slotIndex; 652 name = null; type = null; desc = null; 653 basicType = BasicType.V_TYPE; 654 } 655 Var(String name, Class<?> type, Var prev) { 656 int slotIndex = prev.nextSlotIndex(); 657 int index = prev.nextIndex(); 658 if (name == null) name = "x"; 659 if (name.endsWith("#")) 660 name = name.substring(0, name.length()-1) + index; 661 assert(!type.equals(void.class)); 662 String desc = classSig(type); 663 BasicType basicType = BasicType.basicType(type); 664 this.index = index; 665 this.name = name; 666 this.type = type; 667 this.desc = desc; 668 this.basicType = basicType; 669 this.slotIndex = slotIndex; 670 } 671 Var lastOf(List<Var> vars) { 672 int n = vars.size(); 673 return (n == 0 ? this : vars.get(n-1)); 674 } 675 <X> List<Var> fromTypes(List<X> types) { 676 Var prev = this; 677 ArrayList<Var> result = new ArrayList<>(types.size()); 678 int i = 0; 679 for (X x : types) { 680 String vn = name; 681 Class<?> vt; 682 if (x instanceof Class) { 683 vt = (Class<?>) x; 684 // make the names friendlier if debugging 685 assert((vn = vn + "_" + (i++)) != null); 686 } else { 687 @SuppressWarnings("unchecked") 688 Var v = (Var) x; 689 vn = v.name; 690 vt = v.type; 691 } 692 prev = new Var(vn, vt, prev); 693 result.add(prev); 694 } 695 return result; 696 } 697 698 int slotSize() { return basicType.basicTypeSlots(); } 699 int nextIndex() { return index + (slotSize() == 0 ? 0 : 1); } 700 int nextSlotIndex() { return slotIndex >= 0 ? slotIndex + slotSize() : slotIndex; } 701 boolean isInHeap() { return slotIndex < 0; } 702 void emitVarInstruction(int asmop, MethodVisitor mv) { 703 if (asmop == ALOAD) 704 asmop = typeLoadOp(basicType.basicTypeChar()); 705 else 706 throw new AssertionError("bad op="+asmop+" for desc="+desc); 707 mv.visitVarInsn(asmop, slotIndex); 708 } 709 public void emitFieldInsn(int asmop, MethodVisitor mv) { 710 mv.visitFieldInsn(asmop, className, name, desc); 711 } 712 } 713 714 final Var NO_THIS = new Var(0, 0), 715 AFTER_THIS = new Var(0, 1), 716 IN_HEAP = new Var(0, -1); 717 718 // figure out the field types 719 final List<Class<?>> fieldTypes = speciesData.fieldTypes(); 720 final List<Var> fields = new ArrayList<>(fieldTypes.size()); 721 { 722 Var nextF = IN_HEAP; 723 for (Class<?> ft : fieldTypes) { 724 String fn = chooseFieldName(ft, nextF.nextIndex()); 725 nextF = new Var(fn, ft, nextF); 726 fields.add(nextF); 727 } 728 } 729 730 // emit bound argument fields 731 for (Var field : fields) { 732 cw.visitField(ACC_FINAL, field.name, field.desc, null, null).visitEnd(); 733 } 734 735 MethodVisitor mv; 736 737 // emit implementation of speciesData() 738 mv = cw.visitMethod((SPECIES_DATA_MODS & ACC_PPP) + ACC_FINAL, 739 SPECIES_DATA_NAME, "()" + SPECIES_DATA_SIG, null, null); 740 mv.visitCode(); 741 mv.visitFieldInsn(GETSTATIC, className, sdFieldName, SPECIES_DATA_SIG); 742 mv.visitInsn(ARETURN); 743 mv.visitMaxs(0, 0); 744 mv.visitEnd(); 745 746 // figure out the constructor arguments 747 MethodType superCtorType = ClassSpecializer.this.baseConstructorType(); 748 MethodType thisCtorType = superCtorType.appendParameterTypes(fieldTypes); 749 750 // emit constructor 751 { 752 mv = cw.visitMethod(ACC_PRIVATE, 753 "<init>", methodSig(thisCtorType), null, null); 754 mv.visitCode(); 755 mv.visitVarInsn(ALOAD, 0); // this 756 757 final List<Var> ctorArgs = AFTER_THIS.fromTypes(superCtorType.parameterList()); 758 for (Var ca : ctorArgs) { 759 ca.emitVarInstruction(ALOAD, mv); 760 } 761 762 // super(ca...) 763 mv.visitMethodInsn(INVOKESPECIAL, superClassName, 764 "<init>", methodSig(superCtorType), false); 765 766 // store down fields 767 Var lastFV = AFTER_THIS.lastOf(ctorArgs); 768 for (Var f : fields) { 769 // this.argL1 = argL1 770 mv.visitVarInsn(ALOAD, 0); // this 771 lastFV = new Var(f.name, f.type, lastFV); 772 lastFV.emitVarInstruction(ALOAD, mv); 773 f.emitFieldInsn(PUTFIELD, mv); 774 } 775 776 mv.visitInsn(RETURN); 777 mv.visitMaxs(0, 0); 778 mv.visitEnd(); 779 } 780 781 // emit make() ...factory method wrapping constructor 782 { 783 MethodType ftryType = thisCtorType.changeReturnType(topClass()); 784 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, 785 "make", methodSig(ftryType), null, null); 786 mv.visitCode(); 787 // make instance 788 mv.visitTypeInsn(NEW, className); 789 mv.visitInsn(DUP); 790 // load factory method arguments: ctarg... and arg... 791 for (Var v : NO_THIS.fromTypes(ftryType.parameterList())) { 792 v.emitVarInstruction(ALOAD, mv); 793 } 794 795 // finally, invoke the constructor and return 796 mv.visitMethodInsn(INVOKESPECIAL, className, 797 "<init>", methodSig(thisCtorType), false); 798 mv.visitInsn(ARETURN); 799 mv.visitMaxs(0, 0); 800 mv.visitEnd(); 801 } 802 803 // For each transform, emit the customized override of the transform method. 804 // This method mixes together some incoming arguments (from the transform's 805 // static type signature) with the field types themselves, and passes 806 // the resulting mish-mosh of values to a method handle produced by 807 // the species itself. (Typically this method handle is the factory 808 // method of this species or a related one.) 809 for (int whichtm = 0; whichtm < TRANSFORM_NAMES.size(); whichtm++) { 810 final String TNAME = TRANSFORM_NAMES.get(whichtm); 811 final MethodType TTYPE = TRANSFORM_TYPES.get(whichtm); 812 final int TMODS = TRANSFORM_MODS.get(whichtm); 813 mv = cw.visitMethod((TMODS & ACC_PPP) | ACC_FINAL, 814 TNAME, TTYPE.toMethodDescriptorString(), null, E_THROWABLE); 815 mv.visitCode(); 816 // return a call to the corresponding "transform helper", something like this: 817 // MY_SPECIES.transformHelper(whichtm).invokeBasic(ctarg, ..., argL0, ..., xarg) 818 mv.visitFieldInsn(GETSTATIC, className, 819 sdFieldName, SPECIES_DATA_SIG); 820 emitIntConstant(whichtm, mv); 821 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, 822 "transformHelper", "(I)" + MH_SIG, false); 823 824 List<Var> targs = AFTER_THIS.fromTypes(TTYPE.parameterList()); 825 List<Var> tfields = new ArrayList<>(fields); 826 // mix them up and load them for the transform helper: 827 List<Var> helperArgs = speciesData.deriveTransformHelperArguments(transformMethods.get(whichtm), whichtm, targs, tfields); 828 List<Class<?>> helperTypes = new ArrayList<>(helperArgs.size()); 829 for (Var ha : helperArgs) { 830 helperTypes.add(ha.basicType.basicTypeClass()); 831 if (ha.isInHeap()) { 832 assert(tfields.contains(ha)); 833 mv.visitVarInsn(ALOAD, 0); 834 ha.emitFieldInsn(GETFIELD, mv); 835 } else { 836 assert(targs.contains(ha)); 837 ha.emitVarInstruction(ALOAD, mv); 838 } 839 } 840 841 // jump into the helper (which is probably a factory method) 842 final Class<?> rtype = TTYPE.returnType(); 843 final BasicType rbt = BasicType.basicType(rtype); 844 MethodType invokeBasicType = MethodType.methodType(rbt.basicTypeClass(), helperTypes); 845 mv.visitMethodInsn(INVOKEVIRTUAL, MH, 846 "invokeBasic", methodSig(invokeBasicType), false); 847 if (rbt == BasicType.L_TYPE) { 848 mv.visitTypeInsn(CHECKCAST, classBCName(rtype)); 849 mv.visitInsn(ARETURN); 850 } else { 851 throw newInternalError("NYI: transform of type "+rtype); 852 } 853 mv.visitMaxs(0, 0); 854 mv.visitEnd(); 855 } 856 857 cw.visitEnd(); 858 859 return cw.toByteArray(); 860 } 861 862 private int typeLoadOp(char t) { 863 switch (t) { 864 case 'L': return ALOAD; 865 case 'I': return ILOAD; 866 case 'J': return LLOAD; 867 case 'F': return FLOAD; 868 case 'D': return DLOAD; 869 default : throw newInternalError("unrecognized type " + t); 870 } 871 } 872 873 private void emitIntConstant(int con, MethodVisitor mv) { 874 if (ICONST_M1 - ICONST_0 <= con && con <= ICONST_5 - ICONST_0) 875 mv.visitInsn(ICONST_0 + con); 876 else if (con == (byte) con) 877 mv.visitIntInsn(BIPUSH, con); 878 else if (con == (short) con) 879 mv.visitIntInsn(SIPUSH, con); 880 else { 881 mv.visitLdcInsn(con); 882 } 883 884 } 885 886 // 887 // Getter MH generation. 888 // 889 890 private MethodHandle findGetter(Class<?> speciesCode, List<Class<?>> types, int index) { 891 Class<?> fieldType = types.get(index); 892 String fieldName = chooseFieldName(fieldType, index); 893 try { 894 return IMPL_LOOKUP.findGetter(speciesCode, fieldName, fieldType); 895 } catch (NoSuchFieldException | IllegalAccessException e) { 896 throw newInternalError(e); 897 } 898 } 899 900 private List<MethodHandle> findGetters(Class<?> speciesCode, List<Class<?>> types) { 901 MethodHandle[] mhs = new MethodHandle[types.size()]; 902 for (int i = 0; i < mhs.length; ++i) { 903 mhs[i] = findGetter(speciesCode, types, i); 904 assert(mhs[i].internalMemberName().getDeclaringClass() == speciesCode); 905 } 906 return List.of(mhs); 907 } 908 909 private List<MethodHandle> findFactories(Class<? extends T> speciesCode, List<Class<?>> types) { 910 MethodHandle[] mhs = new MethodHandle[1]; 911 mhs[0] = findFactory(speciesCode, types); 912 return List.of(mhs); 913 } 914 915 List<LambdaForm.NamedFunction> makeNominalGetters(List<Class<?>> types, List<MethodHandle> getters) { 916 LambdaForm.NamedFunction[] nfs = new LambdaForm.NamedFunction[types.size()]; 917 for (int i = 0; i < nfs.length; ++i) { 918 nfs[i] = new LambdaForm.NamedFunction(getters.get(i)); 919 } 920 return List.of(nfs); 921 } 922 923 // 924 // Auxiliary methods. 925 // 926 927 protected void linkSpeciesDataToCode(ClassSpecializer<T,K,S>.SpeciesData speciesData, Class<? extends T> speciesCode) { 928 speciesData.speciesCode = speciesCode.asSubclass(topClass); 929 final List<Class<?>> types = speciesData.fieldTypes; 930 speciesData.factories = this.findFactories(speciesCode, types); 931 speciesData.getters = this.findGetters(speciesCode, types); 932 speciesData.nominalGetters = this.makeNominalGetters(types, speciesData.getters); 933 } 934 935 private Field reflectSDField(Class<? extends T> speciesCode) { 936 final Field field = reflectField(speciesCode, sdFieldName); 937 assert(field.getType() == metaType); 938 assert(Modifier.isStatic(field.getModifiers())); 939 return field; 940 } 941 942 private S readSpeciesDataFromCode(Class<? extends T> speciesCode) { 943 try { 944 MemberName sdField = IMPL_LOOKUP.resolveOrFail(REF_getStatic, speciesCode, sdFieldName, metaType); 945 Object base = MethodHandleNatives.staticFieldBase(sdField); 946 long offset = MethodHandleNatives.staticFieldOffset(sdField); 947 UNSAFE.loadFence(); 948 return metaType.cast(UNSAFE.getObject(base, offset)); 949 } catch (Error err) { 950 throw err; 951 } catch (Exception ex) { 952 throw newInternalError("Failed to load speciesData from speciesCode: " + speciesCode.getName(), ex); 953 } catch (Throwable t) { 954 throw uncaughtException(t); 955 } 956 } 957 958 protected S loadSpeciesDataFromCode(Class<? extends T> speciesCode) { 959 if (speciesCode == topClass()) { 960 return topSpecies; 961 } 962 S result = readSpeciesDataFromCode(speciesCode); 963 if (result.outer() != ClassSpecializer.this) { 964 throw newInternalError("wrong class"); 965 } 966 return result; 967 } 968 969 protected void linkCodeToSpeciesData(Class<? extends T> speciesCode, ClassSpecializer<T,K,S>.SpeciesData speciesData, boolean salvage) { 970 try { 971 assert(readSpeciesDataFromCode(speciesCode) == null || 972 (salvage && readSpeciesDataFromCode(speciesCode).equals(speciesData))); 973 974 MemberName sdField = IMPL_LOOKUP.resolveOrFail(REF_putStatic, speciesCode, sdFieldName, metaType); 975 Object base = MethodHandleNatives.staticFieldBase(sdField); 976 long offset = MethodHandleNatives.staticFieldOffset(sdField); 977 UNSAFE.storeFence(); 978 UNSAFE.putObject(base, offset, speciesData); 979 UNSAFE.storeFence(); 980 } catch (Error err) { 981 throw err; 982 } catch (Exception ex) { 983 throw newInternalError("Failed to link speciesData to speciesCode: " + speciesCode.getName(), ex); 984 } catch (Throwable t) { 985 throw uncaughtException(t); 986 } 987 } 988 989 /** 990 * Field names in concrete species classes adhere to this pattern: 991 * type + index, where type is a single character (L, I, J, F, D). 992 * The factory subclass can customize this. 993 * The name is purely cosmetic, since it applies to a private field. 994 */ 995 protected String chooseFieldName(Class<?> type, int index) { 996 BasicType bt = BasicType.basicType(type); 997 return "" + bt.basicTypeChar() + index; 998 } 999 1000 MethodHandle findFactory(Class<? extends T> speciesCode, List<Class<?>> types) { 1001 final MethodType type = baseConstructorType().changeReturnType(topClass()).appendParameterTypes(types); 1002 try { 1003 return IMPL_LOOKUP.findStatic(speciesCode, "make", type); 1004 } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) { 1005 throw newInternalError(e); 1006 } 1007 } 1008 } 1009 1010 /** Hook that virtualizes the Factory class, allowing subclasses to extend it. */ 1011 protected Factory makeFactory() { 1012 return new Factory(); 1013 } 1014 1015 1016 // Other misc helpers: 1017 private static final String MH = "java/lang/invoke/MethodHandle"; 1018 private static final String MH_SIG = "L" + MH + ";"; 1019 private static final String STABLE = "jdk/internal/vm/annotation/Stable"; 1020 private static final String STABLE_SIG = "L" + STABLE + ";"; 1021 private static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" }; 1022 static { 1023 assert(MH_SIG.equals(classSig(MethodHandle.class))); 1024 assert(MH.equals(classBCName(MethodHandle.class))); 1025 } 1026 1027 static String methodSig(MethodType mt) { 1028 return mt.toMethodDescriptorString(); 1029 } 1030 static String classSig(Class<?> cls) { 1031 if (cls.isPrimitive() || cls.isArray()) 1032 return MethodType.methodType(cls).toMethodDescriptorString().substring(2); 1033 return classSig(classBCName(cls)); 1034 } 1035 static String classSig(String bcName) { 1036 assert(bcName.indexOf('.') < 0); 1037 assert(!bcName.endsWith(";")); 1038 assert(!bcName.startsWith("[")); 1039 return "L" + bcName + ";"; 1040 } 1041 static String classBCName(Class<?> cls) { 1042 return classBCName(className(cls)); 1043 } 1044 static String classBCName(String str) { 1045 assert(str.indexOf('/') < 0) : str; 1046 return str.replace('.', '/'); 1047 } 1048 static String className(Class<?> cls) { 1049 assert(!cls.isArray() && !cls.isPrimitive()); 1050 return cls.getName(); 1051 } 1052 }