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