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