1 /* 2 * Copyright (c) 2008, 2013, 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 java.security.AccessController; 29 import java.security.PrivilegedAction; 30 import java.util.ArrayList; 31 import java.util.Arrays; 32 import java.util.Collections; 33 import java.util.function.Function; 34 35 import sun.invoke.empty.Empty; 36 import sun.invoke.util.ValueConversions; 37 import sun.invoke.util.VerifyType; 38 import sun.invoke.util.Wrapper; 39 import sun.reflect.CallerSensitive; 40 import sun.reflect.Reflection; 41 import static java.lang.invoke.LambdaForm.*; 42 import static java.lang.invoke.MethodHandleStatics.*; 43 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; 44 45 /** 46 * Trusted implementation code for MethodHandle. 47 * @author jrose 48 */ 49 /*non-public*/ abstract class MethodHandleImpl { 50 // Do not adjust this except for special platforms: 51 private static final int MAX_ARITY; 52 static { 53 final Object[] values = { 255 }; 54 AccessController.doPrivileged(new PrivilegedAction<>() { 55 @Override 56 public Void run() { 57 values[0] = Integer.getInteger(MethodHandleImpl.class.getName()+".MAX_ARITY", 255); 58 return null; 59 } 60 }); 61 MAX_ARITY = (Integer) values[0]; 62 } 63 64 /// Factory methods to create method handles: 65 66 static void initStatics() { 67 // Trigger selected static initializations. 68 MemberName.Factory.INSTANCE.getClass(); 69 } 70 71 static MethodHandle makeArrayElementAccessor(Class<?> arrayClass, boolean isSetter) { 72 if (arrayClass == Object[].class) 73 return (isSetter ? ArrayAccessor.OBJECT_ARRAY_SETTER : ArrayAccessor.OBJECT_ARRAY_GETTER); 74 if (!arrayClass.isArray()) 75 throw newIllegalArgumentException("not an array: "+arrayClass); 76 MethodHandle[] cache = ArrayAccessor.TYPED_ACCESSORS.get(arrayClass); 77 int cacheIndex = (isSetter ? ArrayAccessor.SETTER_INDEX : ArrayAccessor.GETTER_INDEX); 78 MethodHandle mh = cache[cacheIndex]; 79 if (mh != null) return mh; 80 mh = ArrayAccessor.getAccessor(arrayClass, isSetter); 81 MethodType correctType = ArrayAccessor.correctType(arrayClass, isSetter); 82 if (mh.type() != correctType) { 83 assert(mh.type().parameterType(0) == Object[].class); 84 assert((isSetter ? mh.type().parameterType(2) : mh.type().returnType()) == Object.class); 85 assert(isSetter || correctType.parameterType(0).getComponentType() == correctType.returnType()); 86 // safe to view non-strictly, because element type follows from array type 87 mh = mh.viewAsType(correctType, false); 88 } 89 mh = makeIntrinsic(mh, (isSetter ? Intrinsic.ARRAY_STORE : Intrinsic.ARRAY_LOAD)); 90 // Atomically update accessor cache. 91 synchronized(cache) { 92 if (cache[cacheIndex] == null) { 93 cache[cacheIndex] = mh; 94 } else { 95 // Throw away newly constructed accessor and use cached version. 96 mh = cache[cacheIndex]; 97 } 98 } 99 return mh; 100 } 101 102 static final class ArrayAccessor { 103 /// Support for array element access 104 static final int GETTER_INDEX = 0, SETTER_INDEX = 1, INDEX_LIMIT = 2; 105 static final ClassValue<MethodHandle[]> TYPED_ACCESSORS 106 = new ClassValue<MethodHandle[]>() { 107 @Override 108 protected MethodHandle[] computeValue(Class<?> type) { 109 return new MethodHandle[INDEX_LIMIT]; 110 } 111 }; 112 static final MethodHandle OBJECT_ARRAY_GETTER, OBJECT_ARRAY_SETTER; 113 static { 114 MethodHandle[] cache = TYPED_ACCESSORS.get(Object[].class); 115 cache[GETTER_INDEX] = OBJECT_ARRAY_GETTER = makeIntrinsic(getAccessor(Object[].class, false), Intrinsic.ARRAY_LOAD); 116 cache[SETTER_INDEX] = OBJECT_ARRAY_SETTER = makeIntrinsic(getAccessor(Object[].class, true), Intrinsic.ARRAY_STORE); 117 118 assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_GETTER.internalMemberName())); 119 assert(InvokerBytecodeGenerator.isStaticallyInvocable(ArrayAccessor.OBJECT_ARRAY_SETTER.internalMemberName())); 120 } 121 122 static int getElementI(int[] a, int i) { return a[i]; } 123 static long getElementJ(long[] a, int i) { return a[i]; } 124 static float getElementF(float[] a, int i) { return a[i]; } 125 static double getElementD(double[] a, int i) { return a[i]; } 126 static boolean getElementZ(boolean[] a, int i) { return a[i]; } 127 static byte getElementB(byte[] a, int i) { return a[i]; } 128 static short getElementS(short[] a, int i) { return a[i]; } 129 static char getElementC(char[] a, int i) { return a[i]; } 130 static Object getElementL(Object[] a, int i) { return a[i]; } 131 132 static void setElementI(int[] a, int i, int x) { a[i] = x; } 133 static void setElementJ(long[] a, int i, long x) { a[i] = x; } 134 static void setElementF(float[] a, int i, float x) { a[i] = x; } 135 static void setElementD(double[] a, int i, double x) { a[i] = x; } 136 static void setElementZ(boolean[] a, int i, boolean x) { a[i] = x; } 137 static void setElementB(byte[] a, int i, byte x) { a[i] = x; } 138 static void setElementS(short[] a, int i, short x) { a[i] = x; } 139 static void setElementC(char[] a, int i, char x) { a[i] = x; } 140 static void setElementL(Object[] a, int i, Object x) { a[i] = x; } 141 142 static String name(Class<?> arrayClass, boolean isSetter) { 143 Class<?> elemClass = arrayClass.getComponentType(); 144 if (elemClass == null) throw newIllegalArgumentException("not an array", arrayClass); 145 return (!isSetter ? "getElement" : "setElement") + Wrapper.basicTypeChar(elemClass); 146 } 147 static MethodType type(Class<?> arrayClass, boolean isSetter) { 148 Class<?> elemClass = arrayClass.getComponentType(); 149 Class<?> arrayArgClass = arrayClass; 150 if (!elemClass.isPrimitive()) { 151 arrayArgClass = Object[].class; 152 elemClass = Object.class; 153 } 154 return !isSetter ? 155 MethodType.methodType(elemClass, arrayArgClass, int.class) : 156 MethodType.methodType(void.class, arrayArgClass, int.class, elemClass); 157 } 158 static MethodType correctType(Class<?> arrayClass, boolean isSetter) { 159 Class<?> elemClass = arrayClass.getComponentType(); 160 return !isSetter ? 161 MethodType.methodType(elemClass, arrayClass, int.class) : 162 MethodType.methodType(void.class, arrayClass, int.class, elemClass); 163 } 164 static MethodHandle getAccessor(Class<?> arrayClass, boolean isSetter) { 165 String name = name(arrayClass, isSetter); 166 MethodType type = type(arrayClass, isSetter); 167 try { 168 return IMPL_LOOKUP.findStatic(ArrayAccessor.class, name, type); 169 } catch (ReflectiveOperationException ex) { 170 throw uncaughtException(ex); 171 } 172 } 173 } 174 175 /** 176 * Create a JVM-level adapter method handle to conform the given method 177 * handle to the similar newType, using only pairwise argument conversions. 178 * For each argument, convert incoming argument to the exact type needed. 179 * The argument conversions allowed are casting, boxing and unboxing, 180 * integral widening or narrowing, and floating point widening or narrowing. 181 * @param srcType required call type 182 * @param target original method handle 183 * @param strict if true, only asType conversions are allowed; if false, explicitCastArguments conversions allowed 184 * @param monobox if true, unboxing conversions are assumed to be exactly typed (Integer to int only, not long or double) 185 * @return an adapter to the original handle with the desired new type, 186 * or the original target if the types are already identical 187 * or null if the adaptation cannot be made 188 */ 189 static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, 190 boolean strict, boolean monobox) { 191 MethodType dstType = target.type(); 192 if (srcType == dstType) 193 return target; 194 return makePairwiseConvertByEditor(target, srcType, strict, monobox); 195 } 196 197 private static int countNonNull(Object[] array) { 198 int count = 0; 199 for (Object x : array) { 200 if (x != null) ++count; 201 } 202 return count; 203 } 204 205 static MethodHandle makePairwiseConvertByEditor(MethodHandle target, MethodType srcType, 206 boolean strict, boolean monobox) { 207 Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox); 208 int convCount = countNonNull(convSpecs); 209 if (convCount == 0) 210 return target.viewAsType(srcType, strict); 211 MethodType basicSrcType = srcType.basicType(); 212 MethodType midType = target.type().basicType(); 213 BoundMethodHandle mh = target.rebind(); 214 // FIXME: Reduce number of bindings when there is more than one Class conversion. 215 // FIXME: Reduce number of bindings when there are repeated conversions. 216 for (int i = 0; i < convSpecs.length-1; i++) { 217 Object convSpec = convSpecs[i]; 218 if (convSpec == null) continue; 219 MethodHandle fn; 220 if (convSpec instanceof Class) { 221 fn = Lazy.MH_castReference.bindTo(convSpec); 222 } else { 223 fn = (MethodHandle) convSpec; 224 } 225 Class<?> newType = basicSrcType.parameterType(i); 226 if (--convCount == 0) 227 midType = srcType; 228 else 229 midType = midType.changeParameterType(i, newType); 230 LambdaForm form2 = mh.editor().filterArgumentForm(1+i, BasicType.basicType(newType)); 231 mh = mh.copyWithExtendL(midType, form2, fn); 232 mh = mh.rebind(); 233 } 234 Object convSpec = convSpecs[convSpecs.length-1]; 235 if (convSpec != null) { 236 MethodHandle fn; 237 if (convSpec instanceof Class) { 238 if (convSpec == void.class) 239 fn = null; 240 else 241 fn = Lazy.MH_castReference.bindTo(convSpec); 242 } else { 243 fn = (MethodHandle) convSpec; 244 } 245 Class<?> newType = basicSrcType.returnType(); 246 assert(--convCount == 0); 247 midType = srcType; 248 if (fn != null) { 249 mh = mh.rebind(); // rebind if too complex 250 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), false); 251 mh = mh.copyWithExtendL(midType, form2, fn); 252 } else { 253 LambdaForm form2 = mh.editor().filterReturnForm(BasicType.basicType(newType), true); 254 mh = mh.copyWith(midType, form2); 255 } 256 } 257 assert(convCount == 0); 258 assert(mh.type().equals(srcType)); 259 return mh; 260 } 261 262 static MethodHandle makePairwiseConvertIndirect(MethodHandle target, MethodType srcType, 263 boolean strict, boolean monobox) { 264 assert(target.type().parameterCount() == srcType.parameterCount()); 265 // Calculate extra arguments (temporaries) required in the names array. 266 Object[] convSpecs = computeValueConversions(srcType, target.type(), strict, monobox); 267 final int INARG_COUNT = srcType.parameterCount(); 268 int convCount = countNonNull(convSpecs); 269 boolean retConv = (convSpecs[INARG_COUNT] != null); 270 boolean retVoid = srcType.returnType() == void.class; 271 if (retConv && retVoid) { 272 convCount -= 1; 273 retConv = false; 274 } 275 276 final int IN_MH = 0; 277 final int INARG_BASE = 1; 278 final int INARG_LIMIT = INARG_BASE + INARG_COUNT; 279 final int NAME_LIMIT = INARG_LIMIT + convCount + 1; 280 final int RETURN_CONV = (!retConv ? -1 : NAME_LIMIT - 1); 281 final int OUT_CALL = (!retConv ? NAME_LIMIT : RETURN_CONV) - 1; 282 final int RESULT = (retVoid ? -1 : NAME_LIMIT - 1); 283 284 // Now build a LambdaForm. 285 MethodType lambdaType = srcType.basicType().invokerType(); 286 Name[] names = arguments(NAME_LIMIT - INARG_LIMIT, lambdaType); 287 288 // Collect the arguments to the outgoing call, maybe with conversions: 289 final int OUTARG_BASE = 0; // target MH is Name.function, name Name.arguments[0] 290 Object[] outArgs = new Object[OUTARG_BASE + INARG_COUNT]; 291 292 int nameCursor = INARG_LIMIT; 293 for (int i = 0; i < INARG_COUNT; i++) { 294 Object convSpec = convSpecs[i]; 295 if (convSpec == null) { 296 // do nothing: difference is trivial 297 outArgs[OUTARG_BASE + i] = names[INARG_BASE + i]; 298 continue; 299 } 300 301 Name conv; 302 if (convSpec instanceof Class) { 303 Class<?> convClass = (Class<?>) convSpec; 304 conv = new Name(Lazy.MH_castReference, convClass, names[INARG_BASE + i]); 305 } else { 306 MethodHandle fn = (MethodHandle) convSpec; 307 conv = new Name(fn, names[INARG_BASE + i]); 308 } 309 assert(names[nameCursor] == null); 310 names[nameCursor++] = conv; 311 assert(outArgs[OUTARG_BASE + i] == null); 312 outArgs[OUTARG_BASE + i] = conv; 313 } 314 315 // Build argument array for the call. 316 assert(nameCursor == OUT_CALL); 317 names[OUT_CALL] = new Name(target, outArgs); 318 319 Object convSpec = convSpecs[INARG_COUNT]; 320 if (!retConv) { 321 assert(OUT_CALL == names.length-1); 322 } else { 323 Name conv; 324 if (convSpec == void.class) { 325 conv = new Name(LambdaForm.constantZero(BasicType.basicType(srcType.returnType()))); 326 } else if (convSpec instanceof Class) { 327 Class<?> convClass = (Class<?>) convSpec; 328 conv = new Name(Lazy.MH_castReference, convClass, names[OUT_CALL]); 329 } else { 330 MethodHandle fn = (MethodHandle) convSpec; 331 if (fn.type().parameterCount() == 0) 332 conv = new Name(fn); // don't pass retval to void conversion 333 else 334 conv = new Name(fn, names[OUT_CALL]); 335 } 336 assert(names[RETURN_CONV] == null); 337 names[RETURN_CONV] = conv; 338 assert(RETURN_CONV == names.length-1); 339 } 340 341 LambdaForm form = new LambdaForm("convert", lambdaType.parameterCount(), names, RESULT); 342 return SimpleMethodHandle.make(srcType, form); 343 } 344 345 /** 346 * Identity function, with reference cast. 347 * @param t an arbitrary reference type 348 * @param x an arbitrary reference value 349 * @return the same value x 350 */ 351 @ForceInline 352 @SuppressWarnings("unchecked") 353 static <T,U> T castReference(Class<? extends T> t, U x) { 354 // inlined Class.cast because we can't ForceInline it 355 if (x != null && !t.isInstance(x)) 356 throw newClassCastException(t, x); 357 return (T) x; 358 } 359 360 private static ClassCastException newClassCastException(Class<?> t, Object obj) { 361 return new ClassCastException("Cannot cast " + obj.getClass().getName() + " to " + t.getName()); 362 } 363 364 static Object[] computeValueConversions(MethodType srcType, MethodType dstType, 365 boolean strict, boolean monobox) { 366 final int INARG_COUNT = srcType.parameterCount(); 367 Object[] convSpecs = new Object[INARG_COUNT+1]; 368 for (int i = 0; i <= INARG_COUNT; i++) { 369 boolean isRet = (i == INARG_COUNT); 370 Class<?> src = isRet ? dstType.returnType() : srcType.parameterType(i); 371 Class<?> dst = isRet ? srcType.returnType() : dstType.parameterType(i); 372 if (!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)) { 373 convSpecs[i] = valueConversion(src, dst, strict, monobox); 374 } 375 } 376 return convSpecs; 377 } 378 static MethodHandle makePairwiseConvert(MethodHandle target, MethodType srcType, 379 boolean strict) { 380 return makePairwiseConvert(target, srcType, strict, /*monobox=*/ false); 381 } 382 383 /** 384 * Find a conversion function from the given source to the given destination. 385 * This conversion function will be used as a LF NamedFunction. 386 * Return a Class object if a simple cast is needed. 387 * Return void.class if void is involved. 388 */ 389 static Object valueConversion(Class<?> src, Class<?> dst, boolean strict, boolean monobox) { 390 assert(!VerifyType.isNullConversion(src, dst, /*keepInterfaces=*/ strict)); // caller responsibility 391 if (dst == void.class) 392 return dst; 393 MethodHandle fn; 394 if (src.isPrimitive()) { 395 if (src == void.class) { 396 return void.class; // caller must recognize this specially 397 } else if (dst.isPrimitive()) { 398 // Examples: int->byte, byte->int, boolean->int (!strict) 399 fn = ValueConversions.convertPrimitive(src, dst); 400 } else { 401 // Examples: int->Integer, boolean->Object, float->Number 402 Wrapper wsrc = Wrapper.forPrimitiveType(src); 403 fn = ValueConversions.boxExact(wsrc); 404 assert(fn.type().parameterType(0) == wsrc.primitiveType()); 405 assert(fn.type().returnType() == wsrc.wrapperType()); 406 if (!VerifyType.isNullConversion(wsrc.wrapperType(), dst, strict)) { 407 // Corner case, such as int->Long, which will probably fail. 408 MethodType mt = MethodType.methodType(dst, src); 409 if (strict) 410 fn = fn.asType(mt); 411 else 412 fn = MethodHandleImpl.makePairwiseConvert(fn, mt, /*strict=*/ false); 413 } 414 } 415 } else if (dst.isPrimitive()) { 416 Wrapper wdst = Wrapper.forPrimitiveType(dst); 417 if (monobox || src == wdst.wrapperType()) { 418 // Use a strongly-typed unboxer, if possible. 419 fn = ValueConversions.unboxExact(wdst, strict); 420 } else { 421 // Examples: Object->int, Number->int, Comparable->int, Byte->int 422 // must include additional conversions 423 // src must be examined at runtime, to detect Byte, Character, etc. 424 fn = (strict 425 ? ValueConversions.unboxWiden(wdst) 426 : ValueConversions.unboxCast(wdst)); 427 } 428 } else { 429 // Simple reference conversion. 430 // Note: Do not check for a class hierarchy relation 431 // between src and dst. In all cases a 'null' argument 432 // will pass the cast conversion. 433 return dst; 434 } 435 assert(fn.type().parameterCount() <= 1) : "pc"+Arrays.asList(src.getSimpleName(), dst.getSimpleName(), fn); 436 return fn; 437 } 438 439 static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) { 440 MethodType type = target.type(); 441 int last = type.parameterCount() - 1; 442 if (type.parameterType(last) != arrayType) 443 target = target.asType(type.changeParameterType(last, arrayType)); 444 target = target.asFixedArity(); // make sure this attribute is turned off 445 return new AsVarargsCollector(target, arrayType); 446 } 447 448 private static final class AsVarargsCollector extends DelegatingMethodHandle { 449 private final MethodHandle target; 450 private final Class<?> arrayType; 451 private @Stable MethodHandle asCollectorCache; 452 453 AsVarargsCollector(MethodHandle target, Class<?> arrayType) { 454 this(target.type(), target, arrayType); 455 } 456 AsVarargsCollector(MethodType type, MethodHandle target, Class<?> arrayType) { 457 super(type, target); 458 this.target = target; 459 this.arrayType = arrayType; 460 this.asCollectorCache = target.asCollector(arrayType, 0); 461 } 462 463 @Override 464 public boolean isVarargsCollector() { 465 return true; 466 } 467 468 @Override 469 protected MethodHandle getTarget() { 470 return target; 471 } 472 473 @Override 474 public MethodHandle asFixedArity() { 475 return target; 476 } 477 478 @Override 479 MethodHandle setVarargs(MemberName member) { 480 if (member.isVarargs()) return this; 481 return asFixedArity(); 482 } 483 484 @Override 485 public MethodHandle asTypeUncached(MethodType newType) { 486 MethodType type = this.type(); 487 int collectArg = type.parameterCount() - 1; 488 int newArity = newType.parameterCount(); 489 if (newArity == collectArg+1 && 490 type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) { 491 // if arity and trailing parameter are compatible, do normal thing 492 return asTypeCache = asFixedArity().asType(newType); 493 } 494 // check cache 495 MethodHandle acc = asCollectorCache; 496 if (acc != null && acc.type().parameterCount() == newArity) 497 return asTypeCache = acc.asType(newType); 498 // build and cache a collector 499 int arrayLength = newArity - collectArg; 500 MethodHandle collector; 501 try { 502 collector = asFixedArity().asCollector(arrayType, arrayLength); 503 assert(collector.type().parameterCount() == newArity) : "newArity="+newArity+" but collector="+collector; 504 } catch (IllegalArgumentException ex) { 505 throw new WrongMethodTypeException("cannot build collector", ex); 506 } 507 asCollectorCache = collector; 508 return asTypeCache = collector.asType(newType); 509 } 510 511 @Override 512 boolean viewAsTypeChecks(MethodType newType, boolean strict) { 513 super.viewAsTypeChecks(newType, true); 514 if (strict) return true; 515 // extra assertion for non-strict checks: 516 assert (type().lastParameterType().getComponentType() 517 .isAssignableFrom( 518 newType.lastParameterType().getComponentType())) 519 : Arrays.asList(this, newType); 520 return true; 521 } 522 } 523 524 /** Factory method: Spread selected argument. */ 525 static MethodHandle makeSpreadArguments(MethodHandle target, 526 Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) { 527 MethodType targetType = target.type(); 528 529 for (int i = 0; i < spreadArgCount; i++) { 530 Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i); 531 if (arg == null) arg = Object.class; 532 targetType = targetType.changeParameterType(spreadArgPos + i, arg); 533 } 534 target = target.asType(targetType); 535 536 MethodType srcType = targetType 537 .replaceParameterTypes(spreadArgPos, spreadArgPos + spreadArgCount, spreadArgType); 538 // Now build a LambdaForm. 539 MethodType lambdaType = srcType.invokerType(); 540 Name[] names = arguments(spreadArgCount + 2, lambdaType); 541 int nameCursor = lambdaType.parameterCount(); 542 int[] indexes = new int[targetType.parameterCount()]; 543 544 for (int i = 0, argIndex = 1; i < targetType.parameterCount() + 1; i++, argIndex++) { 545 Class<?> src = lambdaType.parameterType(i); 546 if (i == spreadArgPos) { 547 // Spread the array. 548 MethodHandle aload = MethodHandles.arrayElementGetter(spreadArgType); 549 Name array = names[argIndex]; 550 names[nameCursor++] = new Name(Lazy.NF_checkSpreadArgument, array, spreadArgCount); 551 for (int j = 0; j < spreadArgCount; i++, j++) { 552 indexes[i] = nameCursor; 553 names[nameCursor++] = new Name(aload, array, j); 554 } 555 } else if (i < indexes.length) { 556 indexes[i] = argIndex; 557 } 558 } 559 assert(nameCursor == names.length-1); // leave room for the final call 560 561 // Build argument array for the call. 562 Name[] targetArgs = new Name[targetType.parameterCount()]; 563 for (int i = 0; i < targetType.parameterCount(); i++) { 564 int idx = indexes[i]; 565 targetArgs[i] = names[idx]; 566 } 567 names[names.length - 1] = new Name(target, (Object[]) targetArgs); 568 569 LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names); 570 return SimpleMethodHandle.make(srcType, form); 571 } 572 573 static void checkSpreadArgument(Object av, int n) { 574 if (av == null) { 575 if (n == 0) return; 576 } else if (av instanceof Object[]) { 577 int len = ((Object[])av).length; 578 if (len == n) return; 579 } else { 580 int len = java.lang.reflect.Array.getLength(av); 581 if (len == n) return; 582 } 583 // fall through to error: 584 throw newIllegalArgumentException("array is not of length "+n); 585 } 586 587 /** 588 * Pre-initialized NamedFunctions for bootstrapping purposes. 589 * Factored in an inner class to delay initialization until first usage. 590 */ 591 static class Lazy { 592 private static final Class<?> MHI = MethodHandleImpl.class; 593 594 private static final MethodHandle[] ARRAYS; 595 private static final MethodHandle[] FILL_ARRAYS; 596 597 static final NamedFunction NF_checkSpreadArgument; 598 static final NamedFunction NF_guardWithCatch; 599 static final NamedFunction NF_throwException; 600 static final NamedFunction NF_profileBoolean; 601 602 static final MethodHandle MH_castReference; 603 static final MethodHandle MH_selectAlternative; 604 static final MethodHandle MH_copyAsPrimitiveArray; 605 static final MethodHandle MH_fillNewTypedArray; 606 static final MethodHandle MH_fillNewArray; 607 static final MethodHandle MH_arrayIdentity; 608 609 static { 610 ARRAYS = makeArrays(); 611 FILL_ARRAYS = makeFillArrays(); 612 613 try { 614 NF_checkSpreadArgument = new NamedFunction(MHI.getDeclaredMethod("checkSpreadArgument", Object.class, int.class)); 615 NF_guardWithCatch = new NamedFunction(MHI.getDeclaredMethod("guardWithCatch", MethodHandle.class, Class.class, 616 MethodHandle.class, Object[].class)); 617 NF_throwException = new NamedFunction(MHI.getDeclaredMethod("throwException", Throwable.class)); 618 NF_profileBoolean = new NamedFunction(MHI.getDeclaredMethod("profileBoolean", boolean.class, int[].class)); 619 620 NF_checkSpreadArgument.resolve(); 621 NF_guardWithCatch.resolve(); 622 NF_throwException.resolve(); 623 NF_profileBoolean.resolve(); 624 625 MH_castReference = IMPL_LOOKUP.findStatic(MHI, "castReference", 626 MethodType.methodType(Object.class, Class.class, Object.class)); 627 MH_copyAsPrimitiveArray = IMPL_LOOKUP.findStatic(MHI, "copyAsPrimitiveArray", 628 MethodType.methodType(Object.class, Wrapper.class, Object[].class)); 629 MH_arrayIdentity = IMPL_LOOKUP.findStatic(MHI, "identity", 630 MethodType.methodType(Object[].class, Object[].class)); 631 MH_fillNewArray = IMPL_LOOKUP.findStatic(MHI, "fillNewArray", 632 MethodType.methodType(Object[].class, Integer.class, Object[].class)); 633 MH_fillNewTypedArray = IMPL_LOOKUP.findStatic(MHI, "fillNewTypedArray", 634 MethodType.methodType(Object[].class, Object[].class, Integer.class, Object[].class)); 635 636 MH_selectAlternative = makeIntrinsic( 637 IMPL_LOOKUP.findStatic(MHI, "selectAlternative", 638 MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class)), 639 Intrinsic.SELECT_ALTERNATIVE); 640 } catch (ReflectiveOperationException ex) { 641 throw newInternalError(ex); 642 } 643 } 644 } 645 646 /** Factory method: Collect or filter selected argument(s). */ 647 static MethodHandle makeCollectArguments(MethodHandle target, 648 MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) { 649 MethodType targetType = target.type(); // (a..., c, [b...])=>r 650 MethodType collectorType = collector.type(); // (b...)=>c 651 int collectArgCount = collectorType.parameterCount(); 652 Class<?> collectValType = collectorType.returnType(); 653 int collectValCount = (collectValType == void.class ? 0 : 1); 654 MethodType srcType = targetType // (a..., [b...])=>r 655 .dropParameterTypes(collectArgPos, collectArgPos+collectValCount); 656 if (!retainOriginalArgs) { // (a..., b...)=>r 657 srcType = srcType.insertParameterTypes(collectArgPos, collectorType.parameterList()); 658 } 659 // in arglist: [0: ...keep1 | cpos: collect... | cpos+cacount: keep2... ] 660 // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ] 661 // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ] 662 663 // Now build a LambdaForm. 664 MethodType lambdaType = srcType.invokerType(); 665 Name[] names = arguments(2, lambdaType); 666 final int collectNamePos = names.length - 2; 667 final int targetNamePos = names.length - 1; 668 669 Name[] collectorArgs = Arrays.copyOfRange(names, 1 + collectArgPos, 1 + collectArgPos + collectArgCount); 670 names[collectNamePos] = new Name(collector, (Object[]) collectorArgs); 671 672 // Build argument array for the target. 673 // Incoming LF args to copy are: [ (mh) headArgs collectArgs tailArgs ]. 674 // Output argument array is [ headArgs (collectVal)? (collectArgs)? tailArgs ]. 675 Name[] targetArgs = new Name[targetType.parameterCount()]; 676 int inputArgPos = 1; // incoming LF args to copy to target 677 int targetArgPos = 0; // fill pointer for targetArgs 678 int chunk = collectArgPos; // |headArgs| 679 System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk); 680 inputArgPos += chunk; 681 targetArgPos += chunk; 682 if (collectValType != void.class) { 683 targetArgs[targetArgPos++] = names[collectNamePos]; 684 } 685 chunk = collectArgCount; 686 if (retainOriginalArgs) { 687 System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk); 688 targetArgPos += chunk; // optionally pass on the collected chunk 689 } 690 inputArgPos += chunk; 691 chunk = targetArgs.length - targetArgPos; // all the rest 692 System.arraycopy(names, inputArgPos, targetArgs, targetArgPos, chunk); 693 assert(inputArgPos + chunk == collectNamePos); // use of rest of input args also 694 names[targetNamePos] = new Name(target, (Object[]) targetArgs); 695 696 LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names); 697 return SimpleMethodHandle.make(srcType, form); 698 } 699 700 @LambdaForm.Hidden 701 static 702 MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) { 703 if (testResult) { 704 return target; 705 } else { 706 return fallback; 707 } 708 } 709 710 // Intrinsified by C2. Counters are used during parsing to calculate branch frequencies. 711 @LambdaForm.Hidden 712 static 713 boolean profileBoolean(boolean result, int[] counters) { 714 // Profile is int[2] where [0] and [1] correspond to false and true occurrences respectively. 715 int idx = result ? 1 : 0; 716 try { 717 counters[idx] = Math.addExact(counters[idx], 1); 718 } catch (ArithmeticException e) { 719 // Avoid continuous overflow by halving the problematic count. 720 counters[idx] = counters[idx] / 2; 721 } 722 return result; 723 } 724 725 // Intrinsified by C2. Returns true if obj is a compile-time constant. 726 @LambdaForm.Hidden 727 static 728 boolean isCompileConstant(Object obj) { 729 return false; 730 } 731 732 static 733 MethodHandle makeGuardWithTest(MethodHandle test, 734 MethodHandle target, 735 MethodHandle fallback) { 736 MethodType type = target.type(); 737 assert(test.type().equals(type.changeReturnType(boolean.class)) && fallback.type().equals(type)); 738 MethodType basicType = type.basicType(); 739 LambdaForm form = makeGuardWithTestForm(basicType); 740 BoundMethodHandle mh; 741 try { 742 if (PROFILE_GWT) { 743 int[] counts = new int[2]; 744 mh = (BoundMethodHandle) 745 BoundMethodHandle.speciesData_LLLL().constructor().invokeBasic(type, form, 746 (Object) test, (Object) profile(target), (Object) profile(fallback), counts); 747 } else { 748 mh = (BoundMethodHandle) 749 BoundMethodHandle.speciesData_LLL().constructor().invokeBasic(type, form, 750 (Object) test, (Object) profile(target), (Object) profile(fallback)); 751 } 752 } catch (Throwable ex) { 753 throw uncaughtException(ex); 754 } 755 assert(mh.type() == type); 756 return mh; 757 } 758 759 760 static 761 MethodHandle profile(MethodHandle target) { 762 if (DONT_INLINE_THRESHOLD >= 0) { 763 return makeBlockInliningWrapper(target); 764 } else { 765 return target; 766 } 767 } 768 769 /** 770 * Block inlining during JIT-compilation of a target method handle if it hasn't been invoked enough times. 771 * Corresponding LambdaForm has @DontInline when compiled into bytecode. 772 */ 773 static 774 MethodHandle makeBlockInliningWrapper(MethodHandle target) { 775 LambdaForm lform; 776 if (DONT_INLINE_THRESHOLD > 0) { 777 lform = PRODUCE_BLOCK_INLINING_FORM.apply(target); 778 } else { 779 lform = PRODUCE_REINVOKER_FORM.apply(target); 780 } 781 return new CountingWrapper(target, lform, 782 PRODUCE_BLOCK_INLINING_FORM, PRODUCE_REINVOKER_FORM, 783 DONT_INLINE_THRESHOLD); 784 } 785 786 /** Constructs reinvoker lambda form which block inlining during JIT-compilation for a particular method handle */ 787 private static final Function<MethodHandle, LambdaForm> PRODUCE_BLOCK_INLINING_FORM = new Function<MethodHandle, LambdaForm>() { 788 @Override 789 public LambdaForm apply(MethodHandle target) { 790 return DelegatingMethodHandle.makeReinvokerForm(target, 791 MethodTypeForm.LF_DELEGATE_BLOCK_INLINING, CountingWrapper.class, "reinvoker.dontInline", false, 792 DelegatingMethodHandle.NF_getTarget, CountingWrapper.NF_maybeStopCounting); 793 } 794 }; 795 796 /** Constructs simple reinvoker lambda form for a particular method handle */ 797 private static final Function<MethodHandle, LambdaForm> PRODUCE_REINVOKER_FORM = new Function<MethodHandle, LambdaForm>() { 798 @Override 799 public LambdaForm apply(MethodHandle target) { 800 return DelegatingMethodHandle.makeReinvokerForm(target, 801 MethodTypeForm.LF_DELEGATE, DelegatingMethodHandle.class, DelegatingMethodHandle.NF_getTarget); 802 } 803 }; 804 805 /** 806 * Counting method handle. It has 2 states: counting and non-counting. 807 * It is in counting state for the first n invocations and then transitions to non-counting state. 808 * Behavior in counting and non-counting states is determined by lambda forms produced by 809 * countingFormProducer & nonCountingFormProducer respectively. 810 */ 811 static class CountingWrapper extends DelegatingMethodHandle { 812 private final MethodHandle target; 813 private int count; 814 private Function<MethodHandle, LambdaForm> countingFormProducer; 815 private Function<MethodHandle, LambdaForm> nonCountingFormProducer; 816 private volatile boolean isCounting; 817 818 private CountingWrapper(MethodHandle target, LambdaForm lform, 819 Function<MethodHandle, LambdaForm> countingFromProducer, 820 Function<MethodHandle, LambdaForm> nonCountingFormProducer, 821 int count) { 822 super(target.type(), lform); 823 this.target = target; 824 this.count = count; 825 this.countingFormProducer = countingFromProducer; 826 this.nonCountingFormProducer = nonCountingFormProducer; 827 this.isCounting = (count > 0); 828 } 829 830 @Hidden 831 @Override 832 protected MethodHandle getTarget() { 833 return target; 834 } 835 836 @Override 837 public MethodHandle asTypeUncached(MethodType newType) { 838 MethodHandle newTarget = target.asType(newType); 839 MethodHandle wrapper; 840 if (isCounting) { 841 LambdaForm lform; 842 lform = countingFormProducer.apply(newTarget); 843 wrapper = new CountingWrapper(newTarget, lform, countingFormProducer, nonCountingFormProducer, DONT_INLINE_THRESHOLD); 844 } else { 845 wrapper = newTarget; // no need for a counting wrapper anymore 846 } 847 return (asTypeCache = wrapper); 848 } 849 850 boolean countDown() { 851 int c = count; 852 if (c <= 1) { 853 // Try to limit number of updates. MethodHandle.updateForm() doesn't guarantee LF update visibility. 854 if (isCounting) { 855 isCounting = false; 856 return true; 857 } else { 858 return false; 859 } 860 } else { 861 count = c - 1; 862 return false; 863 } 864 } 865 866 @Hidden 867 static void maybeStopCounting(Object o1) { 868 CountingWrapper wrapper = (CountingWrapper) o1; 869 if (wrapper.countDown()) { 870 // Reached invocation threshold. Replace counting behavior with a non-counting one. 871 LambdaForm lform = wrapper.nonCountingFormProducer.apply(wrapper.target); 872 lform.compileToBytecode(); // speed up warmup by avoiding LF interpretation again after transition 873 wrapper.updateForm(lform); 874 } 875 } 876 877 static final NamedFunction NF_maybeStopCounting; 878 static { 879 Class<?> THIS_CLASS = CountingWrapper.class; 880 try { 881 NF_maybeStopCounting = new NamedFunction(THIS_CLASS.getDeclaredMethod("maybeStopCounting", Object.class)); 882 } catch (ReflectiveOperationException ex) { 883 throw newInternalError(ex); 884 } 885 } 886 } 887 888 static 889 LambdaForm makeGuardWithTestForm(MethodType basicType) { 890 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWT); 891 if (lform != null) return lform; 892 final int THIS_MH = 0; // the BMH_LLL 893 final int ARG_BASE = 1; // start of incoming arguments 894 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 895 int nameCursor = ARG_LIMIT; 896 final int GET_TEST = nameCursor++; 897 final int GET_TARGET = nameCursor++; 898 final int GET_FALLBACK = nameCursor++; 899 final int GET_COUNTERS = PROFILE_GWT ? nameCursor++ : -1; 900 final int CALL_TEST = nameCursor++; 901 final int PROFILE = (GET_COUNTERS != -1) ? nameCursor++ : -1; 902 final int TEST = nameCursor-1; // previous statement: either PROFILE or CALL_TEST 903 final int SELECT_ALT = nameCursor++; 904 final int CALL_TARGET = nameCursor++; 905 assert(CALL_TARGET == SELECT_ALT+1); // must be true to trigger IBG.emitSelectAlternative 906 907 MethodType lambdaType = basicType.invokerType(); 908 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 909 910 BoundMethodHandle.SpeciesData data = 911 (GET_COUNTERS != -1) ? BoundMethodHandle.speciesData_LLLL() 912 : BoundMethodHandle.speciesData_LLL(); 913 names[THIS_MH] = names[THIS_MH].withConstraint(data); 914 names[GET_TEST] = new Name(data.getterFunction(0), names[THIS_MH]); 915 names[GET_TARGET] = new Name(data.getterFunction(1), names[THIS_MH]); 916 names[GET_FALLBACK] = new Name(data.getterFunction(2), names[THIS_MH]); 917 if (GET_COUNTERS != -1) { 918 names[GET_COUNTERS] = new Name(data.getterFunction(3), names[THIS_MH]); 919 } 920 Object[] invokeArgs = Arrays.copyOfRange(names, 0, ARG_LIMIT, Object[].class); 921 922 // call test 923 MethodType testType = basicType.changeReturnType(boolean.class).basicType(); 924 invokeArgs[0] = names[GET_TEST]; 925 names[CALL_TEST] = new Name(testType, invokeArgs); 926 927 // profile branch 928 if (PROFILE != -1) { 929 names[PROFILE] = new Name(Lazy.NF_profileBoolean, names[CALL_TEST], names[GET_COUNTERS]); 930 } 931 // call selectAlternative 932 names[SELECT_ALT] = new Name(Lazy.MH_selectAlternative, names[TEST], names[GET_TARGET], names[GET_FALLBACK]); 933 934 // call target or fallback 935 invokeArgs[0] = names[SELECT_ALT]; 936 names[CALL_TARGET] = new Name(basicType, invokeArgs); 937 938 lform = new LambdaForm("guard", lambdaType.parameterCount(), names, /*forceInline=*/true); 939 940 return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWT, lform); 941 } 942 943 /** 944 * The LambdaForm shape for catchException combinator is the following: 945 * <blockquote><pre>{@code 946 * guardWithCatch=Lambda(a0:L,a1:L,a2:L)=>{ 947 * t3:L=BoundMethodHandle$Species_LLLLL.argL0(a0:L); 948 * t4:L=BoundMethodHandle$Species_LLLLL.argL1(a0:L); 949 * t5:L=BoundMethodHandle$Species_LLLLL.argL2(a0:L); 950 * t6:L=BoundMethodHandle$Species_LLLLL.argL3(a0:L); 951 * t7:L=BoundMethodHandle$Species_LLLLL.argL4(a0:L); 952 * t8:L=MethodHandle.invokeBasic(t6:L,a1:L,a2:L); 953 * t9:L=MethodHandleImpl.guardWithCatch(t3:L,t4:L,t5:L,t8:L); 954 * t10:I=MethodHandle.invokeBasic(t7:L,t9:L);t10:I} 955 * }</pre></blockquote> 956 * 957 * argL0 and argL2 are target and catcher method handles. argL1 is exception class. 958 * argL3 and argL4 are auxiliary method handles: argL3 boxes arguments and wraps them into Object[] 959 * (ValueConversions.array()) and argL4 unboxes result if necessary (ValueConversions.unbox()). 960 * 961 * Having t8 and t10 passed outside and not hardcoded into a lambda form allows to share lambda forms 962 * among catchException combinators with the same basic type. 963 */ 964 private static LambdaForm makeGuardWithCatchForm(MethodType basicType) { 965 MethodType lambdaType = basicType.invokerType(); 966 967 LambdaForm lform = basicType.form().cachedLambdaForm(MethodTypeForm.LF_GWC); 968 if (lform != null) { 969 return lform; 970 } 971 final int THIS_MH = 0; // the BMH_LLLLL 972 final int ARG_BASE = 1; // start of incoming arguments 973 final int ARG_LIMIT = ARG_BASE + basicType.parameterCount(); 974 975 int nameCursor = ARG_LIMIT; 976 final int GET_TARGET = nameCursor++; 977 final int GET_CLASS = nameCursor++; 978 final int GET_CATCHER = nameCursor++; 979 final int GET_COLLECT_ARGS = nameCursor++; 980 final int GET_UNBOX_RESULT = nameCursor++; 981 final int BOXED_ARGS = nameCursor++; 982 final int TRY_CATCH = nameCursor++; 983 final int UNBOX_RESULT = nameCursor++; 984 985 Name[] names = arguments(nameCursor - ARG_LIMIT, lambdaType); 986 987 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL(); 988 names[THIS_MH] = names[THIS_MH].withConstraint(data); 989 names[GET_TARGET] = new Name(data.getterFunction(0), names[THIS_MH]); 990 names[GET_CLASS] = new Name(data.getterFunction(1), names[THIS_MH]); 991 names[GET_CATCHER] = new Name(data.getterFunction(2), names[THIS_MH]); 992 names[GET_COLLECT_ARGS] = new Name(data.getterFunction(3), names[THIS_MH]); 993 names[GET_UNBOX_RESULT] = new Name(data.getterFunction(4), names[THIS_MH]); 994 995 // FIXME: rework argument boxing/result unboxing logic for LF interpretation 996 997 // t_{i}:L=MethodHandle.invokeBasic(collectArgs:L,a1:L,...); 998 MethodType collectArgsType = basicType.changeReturnType(Object.class); 999 MethodHandle invokeBasic = MethodHandles.basicInvoker(collectArgsType); 1000 Object[] args = new Object[invokeBasic.type().parameterCount()]; 1001 args[0] = names[GET_COLLECT_ARGS]; 1002 System.arraycopy(names, ARG_BASE, args, 1, ARG_LIMIT-ARG_BASE); 1003 names[BOXED_ARGS] = new Name(makeIntrinsic(invokeBasic, Intrinsic.GUARD_WITH_CATCH), args); 1004 1005 // t_{i+1}:L=MethodHandleImpl.guardWithCatch(target:L,exType:L,catcher:L,t_{i}:L); 1006 Object[] gwcArgs = new Object[] {names[GET_TARGET], names[GET_CLASS], names[GET_CATCHER], names[BOXED_ARGS]}; 1007 names[TRY_CATCH] = new Name(Lazy.NF_guardWithCatch, gwcArgs); 1008 1009 // t_{i+2}:I=MethodHandle.invokeBasic(unbox:L,t_{i+1}:L); 1010 MethodHandle invokeBasicUnbox = MethodHandles.basicInvoker(MethodType.methodType(basicType.rtype(), Object.class)); 1011 Object[] unboxArgs = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]}; 1012 names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs); 1013 1014 lform = new LambdaForm("guardWithCatch", lambdaType.parameterCount(), names); 1015 1016 return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform); 1017 } 1018 1019 static 1020 MethodHandle makeGuardWithCatch(MethodHandle target, 1021 Class<? extends Throwable> exType, 1022 MethodHandle catcher) { 1023 MethodType type = target.type(); 1024 LambdaForm form = makeGuardWithCatchForm(type.basicType()); 1025 1026 // Prepare auxiliary method handles used during LambdaForm interpretation. 1027 // Box arguments and wrap them into Object[]: ValueConversions.array(). 1028 MethodType varargsType = type.changeReturnType(Object[].class); 1029 MethodHandle collectArgs = varargsArray(type.parameterCount()).asType(varargsType); 1030 // Result unboxing: ValueConversions.unbox() OR ValueConversions.identity() OR ValueConversions.ignore(). 1031 MethodHandle unboxResult; 1032 Class<?> rtype = type.returnType(); 1033 if (rtype.isPrimitive()) { 1034 if (rtype == void.class) { 1035 unboxResult = ValueConversions.ignore(); 1036 } else { 1037 Wrapper w = Wrapper.forPrimitiveType(type.returnType()); 1038 unboxResult = ValueConversions.unboxExact(w); 1039 } 1040 } else { 1041 unboxResult = MethodHandles.identity(Object.class); 1042 } 1043 1044 BoundMethodHandle.SpeciesData data = BoundMethodHandle.speciesData_LLLLL(); 1045 BoundMethodHandle mh; 1046 try { 1047 mh = (BoundMethodHandle) 1048 data.constructor().invokeBasic(type, form, (Object) target, (Object) exType, (Object) catcher, 1049 (Object) collectArgs, (Object) unboxResult); 1050 } catch (Throwable ex) { 1051 throw uncaughtException(ex); 1052 } 1053 assert(mh.type() == type); 1054 return mh; 1055 } 1056 1057 /** 1058 * Intrinsified during LambdaForm compilation 1059 * (see {@link InvokerBytecodeGenerator#emitGuardWithCatch emitGuardWithCatch}). 1060 */ 1061 @LambdaForm.Hidden 1062 static Object guardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher, 1063 Object... av) throws Throwable { 1064 // Use asFixedArity() to avoid unnecessary boxing of last argument for VarargsCollector case. 1065 try { 1066 return target.asFixedArity().invokeWithArguments(av); 1067 } catch (Throwable t) { 1068 if (!exType.isInstance(t)) throw t; 1069 return catcher.asFixedArity().invokeWithArguments(prepend(t, av)); 1070 } 1071 } 1072 1073 /** Prepend an element {@code elem} to an {@code array}. */ 1074 @LambdaForm.Hidden 1075 private static Object[] prepend(Object elem, Object[] array) { 1076 Object[] newArray = new Object[array.length+1]; 1077 newArray[0] = elem; 1078 System.arraycopy(array, 0, newArray, 1, array.length); 1079 return newArray; 1080 } 1081 1082 static 1083 MethodHandle throwException(MethodType type) { 1084 assert(Throwable.class.isAssignableFrom(type.parameterType(0))); 1085 int arity = type.parameterCount(); 1086 if (arity > 1) { 1087 MethodHandle mh = throwException(type.dropParameterTypes(1, arity)); 1088 mh = MethodHandles.dropArguments(mh, 1, type.parameterList().subList(1, arity)); 1089 return mh; 1090 } 1091 return makePairwiseConvert(Lazy.NF_throwException.resolvedHandle(), type, false, true); 1092 } 1093 1094 static <T extends Throwable> Empty throwException(T t) throws T { throw t; } 1095 1096 static MethodHandle[] FAKE_METHOD_HANDLE_INVOKE = new MethodHandle[2]; 1097 static MethodHandle fakeMethodHandleInvoke(MemberName method) { 1098 int idx; 1099 assert(method.isMethodHandleInvoke()); 1100 switch (method.getName()) { 1101 case "invoke": idx = 0; break; 1102 case "invokeExact": idx = 1; break; 1103 default: throw new InternalError(method.getName()); 1104 } 1105 MethodHandle mh = FAKE_METHOD_HANDLE_INVOKE[idx]; 1106 if (mh != null) return mh; 1107 MethodType type = MethodType.methodType(Object.class, UnsupportedOperationException.class, 1108 MethodHandle.class, Object[].class); 1109 mh = throwException(type); 1110 mh = mh.bindTo(new UnsupportedOperationException("cannot reflectively invoke MethodHandle")); 1111 if (!method.getInvocationType().equals(mh.type())) 1112 throw new InternalError(method.toString()); 1113 mh = mh.withInternalMemberName(method, false); 1114 mh = mh.asVarargsCollector(Object[].class); 1115 assert(method.isVarargs()); 1116 FAKE_METHOD_HANDLE_INVOKE[idx] = mh; 1117 return mh; 1118 } 1119 1120 /** 1121 * Create an alias for the method handle which, when called, 1122 * appears to be called from the same class loader and protection domain 1123 * as hostClass. 1124 * This is an expensive no-op unless the method which is called 1125 * is sensitive to its caller. A small number of system methods 1126 * are in this category, including Class.forName and Method.invoke. 1127 */ 1128 static 1129 MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) { 1130 return BindCaller.bindCaller(mh, hostClass); 1131 } 1132 1133 // Put the whole mess into its own nested class. 1134 // That way we can lazily load the code and set up the constants. 1135 private static class BindCaller { 1136 static 1137 MethodHandle bindCaller(MethodHandle mh, Class<?> hostClass) { 1138 // Do not use this function to inject calls into system classes. 1139 if (hostClass == null 1140 || (hostClass.isArray() || 1141 hostClass.isPrimitive() || 1142 hostClass.getName().startsWith("java.") || 1143 hostClass.getName().startsWith("sun."))) { 1144 throw new InternalError(); // does not happen, and should not anyway 1145 } 1146 // For simplicity, convert mh to a varargs-like method. 1147 MethodHandle vamh = prepareForInvoker(mh); 1148 // Cache the result of makeInjectedInvoker once per argument class. 1149 MethodHandle bccInvoker = CV_makeInjectedInvoker.get(hostClass); 1150 return restoreToType(bccInvoker.bindTo(vamh), mh, hostClass); 1151 } 1152 1153 private static MethodHandle makeInjectedInvoker(Class<?> hostClass) { 1154 Class<?> bcc = UNSAFE.defineAnonymousClass(hostClass, T_BYTES, null); 1155 if (hostClass.getClassLoader() != bcc.getClassLoader()) 1156 throw new InternalError(hostClass.getName()+" (CL)"); 1157 try { 1158 if (hostClass.getProtectionDomain() != bcc.getProtectionDomain()) 1159 throw new InternalError(hostClass.getName()+" (PD)"); 1160 } catch (SecurityException ex) { 1161 // Self-check was blocked by security manager. This is OK. 1162 // In fact the whole try body could be turned into an assertion. 1163 } 1164 try { 1165 MethodHandle init = IMPL_LOOKUP.findStatic(bcc, "init", MethodType.methodType(void.class)); 1166 init.invokeExact(); // force initialization of the class 1167 } catch (Throwable ex) { 1168 throw uncaughtException(ex); 1169 } 1170 MethodHandle bccInvoker; 1171 try { 1172 MethodType invokerMT = MethodType.methodType(Object.class, MethodHandle.class, Object[].class); 1173 bccInvoker = IMPL_LOOKUP.findStatic(bcc, "invoke_V", invokerMT); 1174 } catch (ReflectiveOperationException ex) { 1175 throw uncaughtException(ex); 1176 } 1177 // Test the invoker, to ensure that it really injects into the right place. 1178 try { 1179 MethodHandle vamh = prepareForInvoker(MH_checkCallerClass); 1180 Object ok = bccInvoker.invokeExact(vamh, new Object[]{hostClass, bcc}); 1181 } catch (Throwable ex) { 1182 throw new InternalError(ex); 1183 } 1184 return bccInvoker; 1185 } 1186 private static ClassValue<MethodHandle> CV_makeInjectedInvoker = new ClassValue<MethodHandle>() { 1187 @Override protected MethodHandle computeValue(Class<?> hostClass) { 1188 return makeInjectedInvoker(hostClass); 1189 } 1190 }; 1191 1192 // Adapt mh so that it can be called directly from an injected invoker: 1193 private static MethodHandle prepareForInvoker(MethodHandle mh) { 1194 mh = mh.asFixedArity(); 1195 MethodType mt = mh.type(); 1196 int arity = mt.parameterCount(); 1197 MethodHandle vamh = mh.asType(mt.generic()); 1198 vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames 1199 vamh = vamh.asSpreader(Object[].class, arity); 1200 vamh.internalForm().compileToBytecode(); // eliminate LFI stack frames 1201 return vamh; 1202 } 1203 1204 // Undo the adapter effect of prepareForInvoker: 1205 private static MethodHandle restoreToType(MethodHandle vamh, 1206 MethodHandle original, 1207 Class<?> hostClass) { 1208 MethodType type = original.type(); 1209 MethodHandle mh = vamh.asCollector(Object[].class, type.parameterCount()); 1210 MemberName member = original.internalMemberName(); 1211 mh = mh.asType(type); 1212 mh = new WrappedMember(mh, type, member, original.isInvokeSpecial(), hostClass); 1213 return mh; 1214 } 1215 1216 private static final MethodHandle MH_checkCallerClass; 1217 static { 1218 final Class<?> THIS_CLASS = BindCaller.class; 1219 assert(checkCallerClass(THIS_CLASS, THIS_CLASS)); 1220 try { 1221 MH_checkCallerClass = IMPL_LOOKUP 1222 .findStatic(THIS_CLASS, "checkCallerClass", 1223 MethodType.methodType(boolean.class, Class.class, Class.class)); 1224 assert((boolean) MH_checkCallerClass.invokeExact(THIS_CLASS, THIS_CLASS)); 1225 } catch (Throwable ex) { 1226 throw new InternalError(ex); 1227 } 1228 } 1229 1230 @CallerSensitive 1231 private static boolean checkCallerClass(Class<?> expected, Class<?> expected2) { 1232 // This method is called via MH_checkCallerClass and so it's 1233 // correct to ask for the immediate caller here. 1234 Class<?> actual = Reflection.getCallerClass(); 1235 if (actual != expected && actual != expected2) 1236 throw new InternalError("found "+actual.getName()+", expected "+expected.getName() 1237 +(expected == expected2 ? "" : ", or else "+expected2.getName())); 1238 return true; 1239 } 1240 1241 private static final byte[] T_BYTES; 1242 static { 1243 final Object[] values = {null}; 1244 AccessController.doPrivileged(new PrivilegedAction<>() { 1245 public Void run() { 1246 try { 1247 Class<T> tClass = T.class; 1248 String tName = tClass.getName(); 1249 String tResource = tName.substring(tName.lastIndexOf('.')+1)+".class"; 1250 java.net.URLConnection uconn = tClass.getResource(tResource).openConnection(); 1251 int len = uconn.getContentLength(); 1252 byte[] bytes = new byte[len]; 1253 try (java.io.InputStream str = uconn.getInputStream()) { 1254 int nr = str.read(bytes); 1255 if (nr != len) throw new java.io.IOException(tResource); 1256 } 1257 values[0] = bytes; 1258 } catch (java.io.IOException ex) { 1259 throw new InternalError(ex); 1260 } 1261 return null; 1262 } 1263 }); 1264 T_BYTES = (byte[]) values[0]; 1265 } 1266 1267 // The following class is used as a template for Unsafe.defineAnonymousClass: 1268 private static class T { 1269 static void init() { } // side effect: initializes this class 1270 static Object invoke_V(MethodHandle vamh, Object[] args) throws Throwable { 1271 return vamh.invokeExact(args); 1272 } 1273 } 1274 } 1275 1276 1277 /** This subclass allows a wrapped method handle to be re-associated with an arbitrary member name. */ 1278 private static final class WrappedMember extends DelegatingMethodHandle { 1279 private final MethodHandle target; 1280 private final MemberName member; 1281 private final Class<?> callerClass; 1282 private final boolean isInvokeSpecial; 1283 1284 private WrappedMember(MethodHandle target, MethodType type, 1285 MemberName member, boolean isInvokeSpecial, 1286 Class<?> callerClass) { 1287 super(type, target); 1288 this.target = target; 1289 this.member = member; 1290 this.callerClass = callerClass; 1291 this.isInvokeSpecial = isInvokeSpecial; 1292 } 1293 1294 @Override 1295 MemberName internalMemberName() { 1296 return member; 1297 } 1298 @Override 1299 Class<?> internalCallerClass() { 1300 return callerClass; 1301 } 1302 @Override 1303 boolean isInvokeSpecial() { 1304 return isInvokeSpecial; 1305 } 1306 @Override 1307 protected MethodHandle getTarget() { 1308 return target; 1309 } 1310 @Override 1311 public MethodHandle asTypeUncached(MethodType newType) { 1312 // This MH is an alias for target, except for the MemberName 1313 // Drop the MemberName if there is any conversion. 1314 return asTypeCache = target.asType(newType); 1315 } 1316 } 1317 1318 static MethodHandle makeWrappedMember(MethodHandle target, MemberName member, boolean isInvokeSpecial) { 1319 if (member.equals(target.internalMemberName()) && isInvokeSpecial == target.isInvokeSpecial()) 1320 return target; 1321 return new WrappedMember(target, target.type(), member, isInvokeSpecial, null); 1322 } 1323 1324 /** Intrinsic IDs */ 1325 /*non-public*/ 1326 enum Intrinsic { 1327 SELECT_ALTERNATIVE, 1328 GUARD_WITH_CATCH, 1329 NEW_ARRAY, 1330 ARRAY_LOAD, 1331 ARRAY_STORE, 1332 IDENTITY, 1333 ZERO, 1334 NONE // no intrinsic associated 1335 } 1336 1337 /** Mark arbitrary method handle as intrinsic. 1338 * InvokerBytecodeGenerator uses this info to produce more efficient bytecode shape. */ 1339 private static final class IntrinsicMethodHandle extends DelegatingMethodHandle { 1340 private final MethodHandle target; 1341 private final Intrinsic intrinsicName; 1342 1343 IntrinsicMethodHandle(MethodHandle target, Intrinsic intrinsicName) { 1344 super(target.type(), target); 1345 this.target = target; 1346 this.intrinsicName = intrinsicName; 1347 } 1348 1349 @Override 1350 protected MethodHandle getTarget() { 1351 return target; 1352 } 1353 1354 @Override 1355 Intrinsic intrinsicName() { 1356 return intrinsicName; 1357 } 1358 1359 @Override 1360 public MethodHandle asTypeUncached(MethodType newType) { 1361 // This MH is an alias for target, except for the intrinsic name 1362 // Drop the name if there is any conversion. 1363 return asTypeCache = target.asType(newType); 1364 } 1365 1366 @Override 1367 String internalProperties() { 1368 return super.internalProperties() + 1369 "\n& Intrinsic="+intrinsicName; 1370 } 1371 1372 @Override 1373 public MethodHandle asCollector(Class<?> arrayType, int arrayLength) { 1374 if (intrinsicName == Intrinsic.IDENTITY) { 1375 MethodType resultType = type().asCollectorType(arrayType, arrayLength); 1376 MethodHandle newArray = MethodHandleImpl.varargsArray(arrayType, arrayLength); 1377 return newArray.asType(resultType); 1378 } 1379 return super.asCollector(arrayType, arrayLength); 1380 } 1381 } 1382 1383 static MethodHandle makeIntrinsic(MethodHandle target, Intrinsic intrinsicName) { 1384 if (intrinsicName == target.intrinsicName()) 1385 return target; 1386 return new IntrinsicMethodHandle(target, intrinsicName); 1387 } 1388 1389 static MethodHandle makeIntrinsic(MethodType type, LambdaForm form, Intrinsic intrinsicName) { 1390 return new IntrinsicMethodHandle(SimpleMethodHandle.make(type, form), intrinsicName); 1391 } 1392 1393 /// Collection of multiple arguments. 1394 1395 private static MethodHandle findCollector(String name, int nargs, Class<?> rtype, Class<?>... ptypes) { 1396 MethodType type = MethodType.genericMethodType(nargs) 1397 .changeReturnType(rtype) 1398 .insertParameterTypes(0, ptypes); 1399 try { 1400 return IMPL_LOOKUP.findStatic(MethodHandleImpl.class, name, type); 1401 } catch (ReflectiveOperationException ex) { 1402 return null; 1403 } 1404 } 1405 1406 private static final Object[] NO_ARGS_ARRAY = {}; 1407 private static Object[] makeArray(Object... args) { return args; } 1408 private static Object[] array() { return NO_ARGS_ARRAY; } 1409 private static Object[] array(Object a0) 1410 { return makeArray(a0); } 1411 private static Object[] array(Object a0, Object a1) 1412 { return makeArray(a0, a1); } 1413 private static Object[] array(Object a0, Object a1, Object a2) 1414 { return makeArray(a0, a1, a2); } 1415 private static Object[] array(Object a0, Object a1, Object a2, Object a3) 1416 { return makeArray(a0, a1, a2, a3); } 1417 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1418 Object a4) 1419 { return makeArray(a0, a1, a2, a3, a4); } 1420 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1421 Object a4, Object a5) 1422 { return makeArray(a0, a1, a2, a3, a4, a5); } 1423 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1424 Object a4, Object a5, Object a6) 1425 { return makeArray(a0, a1, a2, a3, a4, a5, a6); } 1426 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1427 Object a4, Object a5, Object a6, Object a7) 1428 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7); } 1429 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1430 Object a4, Object a5, Object a6, Object a7, 1431 Object a8) 1432 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8); } 1433 private static Object[] array(Object a0, Object a1, Object a2, Object a3, 1434 Object a4, Object a5, Object a6, Object a7, 1435 Object a8, Object a9) 1436 { return makeArray(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); } 1437 1438 private static final int ARRAYS_COUNT = 11; 1439 1440 private static MethodHandle[] makeArrays() { 1441 MethodHandle[] mhs = new MethodHandle[MAX_ARITY + 1]; 1442 for (int i = 0; i < ARRAYS_COUNT; i++) { 1443 MethodHandle mh = findCollector("array", i, Object[].class); 1444 mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY); 1445 mhs[i] = mh; 1446 } 1447 assert(assertArrayMethodCount(mhs)); 1448 return mhs; 1449 } 1450 1451 private static boolean assertArrayMethodCount(MethodHandle[] mhs) { 1452 assert(findCollector("array", ARRAYS_COUNT, Object[].class) == null); 1453 for (int i = 0; i < ARRAYS_COUNT; i++) { 1454 assert(mhs[i] != null); 1455 } 1456 return true; 1457 } 1458 1459 // filling versions of the above: 1460 // using Integer len instead of int len and no varargs to avoid bootstrapping problems 1461 private static Object[] fillNewArray(Integer len, Object[] /*not ...*/ args) { 1462 Object[] a = new Object[len]; 1463 fillWithArguments(a, 0, args); 1464 return a; 1465 } 1466 private static Object[] fillNewTypedArray(Object[] example, Integer len, Object[] /*not ...*/ args) { 1467 Object[] a = Arrays.copyOf(example, len); 1468 assert(a.getClass() != Object[].class); 1469 fillWithArguments(a, 0, args); 1470 return a; 1471 } 1472 private static void fillWithArguments(Object[] a, int pos, Object... args) { 1473 System.arraycopy(args, 0, a, pos, args.length); 1474 } 1475 // using Integer pos instead of int pos to avoid bootstrapping problems 1476 private static Object[] fillArray(Integer pos, Object[] a, Object a0) 1477 { fillWithArguments(a, pos, a0); return a; } 1478 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1) 1479 { fillWithArguments(a, pos, a0, a1); return a; } 1480 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2) 1481 { fillWithArguments(a, pos, a0, a1, a2); return a; } 1482 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3) 1483 { fillWithArguments(a, pos, a0, a1, a2, a3); return a; } 1484 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1485 Object a4) 1486 { fillWithArguments(a, pos, a0, a1, a2, a3, a4); return a; } 1487 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1488 Object a4, Object a5) 1489 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5); return a; } 1490 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1491 Object a4, Object a5, Object a6) 1492 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6); return a; } 1493 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1494 Object a4, Object a5, Object a6, Object a7) 1495 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7); return a; } 1496 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1497 Object a4, Object a5, Object a6, Object a7, 1498 Object a8) 1499 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8); return a; } 1500 private static Object[] fillArray(Integer pos, Object[] a, Object a0, Object a1, Object a2, Object a3, 1501 Object a4, Object a5, Object a6, Object a7, 1502 Object a8, Object a9) 1503 { fillWithArguments(a, pos, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); return a; } 1504 1505 private static final int FILL_ARRAYS_COUNT = 11; // current number of fillArray methods 1506 1507 private static MethodHandle[] makeFillArrays() { 1508 MethodHandle[] mhs = new MethodHandle[FILL_ARRAYS_COUNT]; 1509 mhs[0] = null; // there is no empty fill; at least a0 is required 1510 for (int i = 1; i < FILL_ARRAYS_COUNT; i++) { 1511 MethodHandle mh = findCollector("fillArray", i, Object[].class, Integer.class, Object[].class); 1512 mhs[i] = mh; 1513 } 1514 assert(assertFillArrayMethodCount(mhs)); 1515 return mhs; 1516 } 1517 1518 private static boolean assertFillArrayMethodCount(MethodHandle[] mhs) { 1519 assert(findCollector("fillArray", FILL_ARRAYS_COUNT, Object[].class, Integer.class, Object[].class) == null); 1520 for (int i = 1; i < FILL_ARRAYS_COUNT; i++) { 1521 assert(mhs[i] != null); 1522 } 1523 return true; 1524 } 1525 1526 private static Object copyAsPrimitiveArray(Wrapper w, Object... boxes) { 1527 Object a = w.makeArray(boxes.length); 1528 w.copyArrayUnboxing(boxes, 0, a, 0, boxes.length); 1529 return a; 1530 } 1531 1532 /** Return a method handle that takes the indicated number of Object 1533 * arguments and returns an Object array of them, as if for varargs. 1534 */ 1535 static MethodHandle varargsArray(int nargs) { 1536 MethodHandle mh = Lazy.ARRAYS[nargs]; 1537 if (mh != null) return mh; 1538 mh = buildVarargsArray(Lazy.MH_fillNewArray, Lazy.MH_arrayIdentity, nargs); 1539 assert(assertCorrectArity(mh, nargs)); 1540 mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY); 1541 return Lazy.ARRAYS[nargs] = mh; 1542 } 1543 1544 private static boolean assertCorrectArity(MethodHandle mh, int arity) { 1545 assert(mh.type().parameterCount() == arity) : "arity != "+arity+": "+mh; 1546 return true; 1547 } 1548 1549 // Array identity function (used as Lazy.MH_arrayIdentity). 1550 static <T> T[] identity(T[] x) { 1551 return x; 1552 } 1553 1554 private static MethodHandle buildVarargsArray(MethodHandle newArray, MethodHandle finisher, int nargs) { 1555 // Build up the result mh as a sequence of fills like this: 1556 // finisher(fill(fill(newArrayWA(23,x1..x10),10,x11..x20),20,x21..x23)) 1557 // The various fill(_,10*I,___*[J]) are reusable. 1558 int leftLen = Math.min(nargs, LEFT_ARGS); // absorb some arguments immediately 1559 int rightLen = nargs - leftLen; 1560 MethodHandle leftCollector = newArray.bindTo(nargs); 1561 leftCollector = leftCollector.asCollector(Object[].class, leftLen); 1562 MethodHandle mh = finisher; 1563 if (rightLen > 0) { 1564 MethodHandle rightFiller = fillToRight(LEFT_ARGS + rightLen); 1565 if (mh == Lazy.MH_arrayIdentity) 1566 mh = rightFiller; 1567 else 1568 mh = MethodHandles.collectArguments(mh, 0, rightFiller); 1569 } 1570 if (mh == Lazy.MH_arrayIdentity) 1571 mh = leftCollector; 1572 else 1573 mh = MethodHandles.collectArguments(mh, 0, leftCollector); 1574 return mh; 1575 } 1576 1577 private static final int LEFT_ARGS = FILL_ARRAYS_COUNT - 1; 1578 private static final MethodHandle[] FILL_ARRAY_TO_RIGHT = new MethodHandle[MAX_ARITY+1]; 1579 /** fill_array_to_right(N).invoke(a, argL..arg[N-1]) 1580 * fills a[L]..a[N-1] with corresponding arguments, 1581 * and then returns a. The value L is a global constant (LEFT_ARGS). 1582 */ 1583 private static MethodHandle fillToRight(int nargs) { 1584 MethodHandle filler = FILL_ARRAY_TO_RIGHT[nargs]; 1585 if (filler != null) return filler; 1586 filler = buildFiller(nargs); 1587 assert(assertCorrectArity(filler, nargs - LEFT_ARGS + 1)); 1588 return FILL_ARRAY_TO_RIGHT[nargs] = filler; 1589 } 1590 private static MethodHandle buildFiller(int nargs) { 1591 if (nargs <= LEFT_ARGS) 1592 return Lazy.MH_arrayIdentity; // no args to fill; return the array unchanged 1593 // we need room for both mh and a in mh.invoke(a, arg*[nargs]) 1594 final int CHUNK = LEFT_ARGS; 1595 int rightLen = nargs % CHUNK; 1596 int midLen = nargs - rightLen; 1597 if (rightLen == 0) { 1598 midLen = nargs - (rightLen = CHUNK); 1599 if (FILL_ARRAY_TO_RIGHT[midLen] == null) { 1600 // build some precursors from left to right 1601 for (int j = LEFT_ARGS % CHUNK; j < midLen; j += CHUNK) 1602 if (j > LEFT_ARGS) fillToRight(j); 1603 } 1604 } 1605 if (midLen < LEFT_ARGS) rightLen = nargs - (midLen = LEFT_ARGS); 1606 assert(rightLen > 0); 1607 MethodHandle midFill = fillToRight(midLen); // recursive fill 1608 MethodHandle rightFill = Lazy.FILL_ARRAYS[rightLen].bindTo(midLen); // [midLen..nargs-1] 1609 assert(midFill.type().parameterCount() == 1 + midLen - LEFT_ARGS); 1610 assert(rightFill.type().parameterCount() == 1 + rightLen); 1611 1612 // Combine the two fills: 1613 // right(mid(a, x10..x19), x20..x23) 1614 // The final product will look like this: 1615 // right(mid(newArrayLeft(24, x0..x9), x10..x19), x20..x23) 1616 if (midLen == LEFT_ARGS) 1617 return rightFill; 1618 else 1619 return MethodHandles.collectArguments(rightFill, 0, midFill); 1620 } 1621 1622 // Type-polymorphic version of varargs maker. 1623 private static final ClassValue<MethodHandle[]> TYPED_COLLECTORS 1624 = new ClassValue<MethodHandle[]>() { 1625 @Override 1626 protected MethodHandle[] computeValue(Class<?> type) { 1627 return new MethodHandle[256]; 1628 } 1629 }; 1630 1631 static final int MAX_JVM_ARITY = 255; // limit imposed by the JVM 1632 1633 /** Return a method handle that takes the indicated number of 1634 * typed arguments and returns an array of them. 1635 * The type argument is the array type. 1636 */ 1637 static MethodHandle varargsArray(Class<?> arrayType, int nargs) { 1638 Class<?> elemType = arrayType.getComponentType(); 1639 if (elemType == null) throw new IllegalArgumentException("not an array: "+arrayType); 1640 // FIXME: Need more special casing and caching here. 1641 if (nargs >= MAX_JVM_ARITY/2 - 1) { 1642 int slots = nargs; 1643 final int MAX_ARRAY_SLOTS = MAX_JVM_ARITY - 1; // 1 for receiver MH 1644 if (slots <= MAX_ARRAY_SLOTS && elemType.isPrimitive()) 1645 slots *= Wrapper.forPrimitiveType(elemType).stackSlots(); 1646 if (slots > MAX_ARRAY_SLOTS) 1647 throw new IllegalArgumentException("too many arguments: "+arrayType.getSimpleName()+", length "+nargs); 1648 } 1649 if (elemType == Object.class) 1650 return varargsArray(nargs); 1651 // other cases: primitive arrays, subtypes of Object[] 1652 MethodHandle cache[] = TYPED_COLLECTORS.get(elemType); 1653 MethodHandle mh = nargs < cache.length ? cache[nargs] : null; 1654 if (mh != null) return mh; 1655 if (nargs == 0) { 1656 Object example = java.lang.reflect.Array.newInstance(arrayType.getComponentType(), 0); 1657 mh = MethodHandles.constant(arrayType, example); 1658 } else if (elemType.isPrimitive()) { 1659 MethodHandle builder = Lazy.MH_fillNewArray; 1660 MethodHandle producer = buildArrayProducer(arrayType); 1661 mh = buildVarargsArray(builder, producer, nargs); 1662 } else { 1663 Class<? extends Object[]> objArrayType = arrayType.asSubclass(Object[].class); 1664 Object[] example = Arrays.copyOf(NO_ARGS_ARRAY, 0, objArrayType); 1665 MethodHandle builder = Lazy.MH_fillNewTypedArray.bindTo(example); 1666 MethodHandle producer = Lazy.MH_arrayIdentity; // must be weakly typed 1667 mh = buildVarargsArray(builder, producer, nargs); 1668 } 1669 mh = mh.asType(MethodType.methodType(arrayType, Collections.<Class<?>>nCopies(nargs, elemType))); 1670 mh = makeIntrinsic(mh, Intrinsic.NEW_ARRAY); 1671 assert(assertCorrectArity(mh, nargs)); 1672 if (nargs < cache.length) 1673 cache[nargs] = mh; 1674 return mh; 1675 } 1676 1677 private static MethodHandle buildArrayProducer(Class<?> arrayType) { 1678 Class<?> elemType = arrayType.getComponentType(); 1679 assert(elemType.isPrimitive()); 1680 return Lazy.MH_copyAsPrimitiveArray.bindTo(Wrapper.forPrimitiveType(elemType)); 1681 } 1682 1683 /*non-public*/ static void assertSame(Object mh1, Object mh2) { 1684 if (mh1 != mh2) { 1685 String msg = String.format("mh1 != mh2: mh1 = %s (form: %s); mh2 = %s (form: %s)", 1686 mh1, ((MethodHandle)mh1).form, 1687 mh2, ((MethodHandle)mh2).form); 1688 throw newInternalError(msg); 1689 } 1690 } 1691 }