1 /* 2 * Copyright (c) 2008, 2018, 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.misc.Unsafe; 29 import jdk.internal.vm.annotation.ForceInline; 30 import jdk.internal.vm.annotation.Stable; 31 import sun.invoke.util.ValueConversions; 32 import sun.invoke.util.VerifyAccess; 33 import sun.invoke.util.VerifyType; 34 import sun.invoke.util.Wrapper; 35 36 import java.lang.ref.WeakReference; 37 import java.util.Arrays; 38 import java.util.Objects; 39 40 import static java.lang.invoke.LambdaForm.*; 41 import static java.lang.invoke.LambdaForm.Kind.*; 42 import static java.lang.invoke.MethodHandleNatives.Constants.*; 43 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 44 import static java.lang.invoke.MethodHandleStatics.newInternalError; 45 import static java.lang.invoke.MethodTypeForm.*; 46 47 /** 48 * The flavor of method handle which implements a constant reference 49 * to a class member. 50 * @author jrose 51 */ 52 class DirectMethodHandle extends MethodHandle { 53 final MemberName member; 54 55 // Constructors and factory methods in this class *must* be package scoped or private. 56 private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member) { 57 super(mtype, form); 58 if (!member.isResolved()) throw new InternalError(); 59 60 if (member.getDeclaringClass().isInterface() && 61 member.isMethod() && !member.isAbstract()) { 62 // Check for corner case: invokeinterface of Object method 63 MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind()); 64 m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null); 65 if (m != null && m.isPublic()) { 66 assert(member.getReferenceKind() == m.getReferenceKind()); // else this.form is wrong 67 member = m; 68 } 69 } 70 71 this.member = member; 72 } 73 74 // Factory methods: 75 static DirectMethodHandle make(byte refKind, Class<?> refc, MemberName member, Class<?> callerClass) { 76 MethodType mtype = member.getMethodOrFieldType(); 77 if (!member.isStatic()) { 78 if (!member.getDeclaringClass().isAssignableFrom(refc) || member.isConstructor()) 79 throw new InternalError(member.toString()); 80 mtype = mtype.insertParameterTypes(0, refc); 81 } 82 if (!member.isField()) { 83 switch (refKind) { 84 case REF_invokeSpecial: { 85 member = member.asSpecial(); 86 LambdaForm lform = preparedLambdaForm(member, callerClass); 87 Class<?> checkClass = refc; // Class to use for receiver type check 88 if (callerClass != null) { 89 checkClass = callerClass; // potentially strengthen to caller class 90 } 91 return new Special(mtype, lform, member, checkClass); 92 } 93 case REF_invokeInterface: { 94 LambdaForm lform = preparedLambdaForm(member, callerClass); 95 return new Interface(mtype, lform, member, refc); 96 } 97 default: { 98 LambdaForm lform = preparedLambdaForm(member, callerClass); 99 return new DirectMethodHandle(mtype, lform, member); 100 } 101 } 102 } else { 103 LambdaForm lform = preparedFieldLambdaForm(member); 104 if (member.isStatic()) { 105 long offset = MethodHandleNatives.staticFieldOffset(member); 106 Object base = MethodHandleNatives.staticFieldBase(member); 107 return new StaticAccessor(mtype, lform, member, base, offset); 108 } else { 109 long offset = MethodHandleNatives.objectFieldOffset(member); 110 assert(offset == (int)offset); 111 return new Accessor(mtype, lform, member, (int)offset); 112 } 113 } 114 } 115 static DirectMethodHandle make(Class<?> refc, MemberName member) { 116 byte refKind = member.getReferenceKind(); 117 if (refKind == REF_invokeSpecial) 118 refKind = REF_invokeVirtual; 119 return make(refKind, refc, member, null /* no callerClass context */); 120 } 121 static DirectMethodHandle make(MemberName member) { 122 if (member.isConstructor()) 123 return makeAllocator(member); 124 return make(member.getDeclaringClass(), member); 125 } 126 private static DirectMethodHandle makeAllocator(MemberName ctor) { 127 assert(ctor.isConstructor() && ctor.getName().equals("<init>")); 128 Class<?> instanceClass = ctor.getDeclaringClass(); 129 ctor = ctor.asConstructor(); 130 assert(ctor.isConstructor() && ctor.getReferenceKind() == REF_newInvokeSpecial) : ctor; 131 MethodType mtype = ctor.getMethodType().changeReturnType(instanceClass); 132 LambdaForm lform = preparedLambdaForm(ctor); 133 MemberName init = ctor.asSpecial(); 134 assert(init.getMethodType().returnType() == void.class); 135 return new Constructor(mtype, lform, ctor, init, instanceClass); 136 } 137 138 @Override 139 BoundMethodHandle rebind() { 140 return BoundMethodHandle.makeReinvoker(this); 141 } 142 143 @Override 144 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 145 assert(this.getClass() == DirectMethodHandle.class); // must override in subclasses 146 return new DirectMethodHandle(mt, lf, member); 147 } 148 149 @Override 150 String internalProperties() { 151 return "\n& DMH.MN="+internalMemberName(); 152 } 153 154 //// Implementation methods. 155 @Override 156 @ForceInline 157 MemberName internalMemberName() { 158 return member; 159 } 160 161 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 162 163 /** 164 * Create a LF which can invoke the given method. 165 * Cache and share this structure among all methods with 166 * the same basicType and refKind. 167 */ 168 private static LambdaForm preparedLambdaForm(MemberName m, Class<?> callerClass) { 169 assert(m.isInvocable()) : m; // call preparedFieldLambdaForm instead 170 MethodType mtype = m.getInvocationType().basicType(); 171 assert(!m.isMethodHandleInvoke()) : m; 172 int which; 173 switch (m.getReferenceKind()) { 174 case REF_invokeVirtual: which = LF_INVVIRTUAL; break; 175 case REF_invokeStatic: which = LF_INVSTATIC; break; 176 case REF_invokeSpecial: which = LF_INVSPECIAL; break; 177 case REF_invokeInterface: which = LF_INVINTERFACE; break; 178 case REF_newInvokeSpecial: which = LF_NEWINVSPECIAL; break; 179 default: throw new InternalError(m.toString()); 180 } 181 if (which == LF_INVSTATIC && shouldBeInitialized(m)) { 182 // precompute the barrier-free version: 183 preparedLambdaForm(mtype, which); 184 which = LF_INVSTATIC_INIT; 185 } 186 if (which == LF_INVSPECIAL && callerClass != null && callerClass.isInterface()) { 187 which = LF_INVSPECIAL_IFC; 188 } 189 LambdaForm lform = preparedLambdaForm(mtype, which); 190 maybeCompile(lform, m); 191 assert(lform.methodType().dropParameterTypes(0, 1) 192 .equals(m.getInvocationType().basicType())) 193 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 194 return lform; 195 } 196 197 private static LambdaForm preparedLambdaForm(MemberName m) { 198 return preparedLambdaForm(m, null); 199 } 200 201 private static LambdaForm preparedLambdaForm(MethodType mtype, int which) { 202 LambdaForm lform = mtype.form().cachedLambdaForm(which); 203 if (lform != null) return lform; 204 lform = makePreparedLambdaForm(mtype, which); 205 return mtype.form().setCachedLambdaForm(which, lform); 206 } 207 208 static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) { 209 boolean needsInit = (which == LF_INVSTATIC_INIT); 210 boolean doesAlloc = (which == LF_NEWINVSPECIAL); 211 boolean needsReceiverCheck = (which == LF_INVINTERFACE || 212 which == LF_INVSPECIAL_IFC); 213 214 String linkerName; 215 LambdaForm.Kind kind; 216 switch (which) { 217 case LF_INVVIRTUAL: linkerName = "linkToVirtual"; kind = DIRECT_INVOKE_VIRTUAL; break; 218 case LF_INVSTATIC: linkerName = "linkToStatic"; kind = DIRECT_INVOKE_STATIC; break; 219 case LF_INVSTATIC_INIT:linkerName = "linkToStatic"; kind = DIRECT_INVOKE_STATIC_INIT; break; 220 case LF_INVSPECIAL_IFC:linkerName = "linkToSpecial"; kind = DIRECT_INVOKE_SPECIAL_IFC; break; 221 case LF_INVSPECIAL: linkerName = "linkToSpecial"; kind = DIRECT_INVOKE_SPECIAL; break; 222 case LF_INVINTERFACE: linkerName = "linkToInterface"; kind = DIRECT_INVOKE_INTERFACE; break; 223 case LF_NEWINVSPECIAL: linkerName = "linkToSpecial"; kind = DIRECT_NEW_INVOKE_SPECIAL; break; 224 default: throw new InternalError("which="+which); 225 } 226 227 MethodType mtypeWithArg = mtype.appendParameterTypes(MemberName.class); 228 if (doesAlloc) 229 mtypeWithArg = mtypeWithArg 230 .insertParameterTypes(0, Object.class) // insert newly allocated obj 231 .changeReturnType(void.class); // <init> returns void 232 MemberName linker = new MemberName(MethodHandle.class, linkerName, mtypeWithArg, REF_invokeStatic); 233 try { 234 linker = IMPL_NAMES.resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class); 235 } catch (ReflectiveOperationException ex) { 236 throw newInternalError(ex); 237 } 238 final int DMH_THIS = 0; 239 final int ARG_BASE = 1; 240 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 241 int nameCursor = ARG_LIMIT; 242 final int NEW_OBJ = (doesAlloc ? nameCursor++ : -1); 243 final int GET_MEMBER = nameCursor++; 244 final int CHECK_RECEIVER = (needsReceiverCheck ? nameCursor++ : -1); 245 final int LINKER_CALL = nameCursor++; 246 Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); 247 assert(names.length == nameCursor); 248 if (doesAlloc) { 249 // names = { argx,y,z,... new C, init method } 250 names[NEW_OBJ] = new Name(getFunction(NF_allocateInstance), names[DMH_THIS]); 251 names[GET_MEMBER] = new Name(getFunction(NF_constructorMethod), names[DMH_THIS]); 252 } else if (needsInit) { 253 names[GET_MEMBER] = new Name(getFunction(NF_internalMemberNameEnsureInit), names[DMH_THIS]); 254 } else { 255 names[GET_MEMBER] = new Name(getFunction(NF_internalMemberName), names[DMH_THIS]); 256 } 257 assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]); 258 Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class); 259 if (needsReceiverCheck) { 260 names[CHECK_RECEIVER] = new Name(getFunction(NF_checkReceiver), names[DMH_THIS], names[ARG_BASE]); 261 outArgs[0] = names[CHECK_RECEIVER]; 262 } 263 assert(outArgs[outArgs.length-1] == names[GET_MEMBER]); // look, shifted args! 264 int result = LAST_RESULT; 265 if (doesAlloc) { 266 assert(outArgs[outArgs.length-2] == names[NEW_OBJ]); // got to move this one 267 System.arraycopy(outArgs, 0, outArgs, 1, outArgs.length-2); 268 outArgs[0] = names[NEW_OBJ]; 269 result = NEW_OBJ; 270 } 271 names[LINKER_CALL] = new Name(linker, outArgs); 272 LambdaForm lform = new LambdaForm(ARG_LIMIT, names, result, kind); 273 274 // This is a tricky bit of code. Don't send it through the LF interpreter. 275 lform.compileToBytecode(); 276 return lform; 277 } 278 279 /* assert */ static Object findDirectMethodHandle(Name name) { 280 if (name.function.equals(getFunction(NF_internalMemberName)) || 281 name.function.equals(getFunction(NF_internalMemberNameEnsureInit)) || 282 name.function.equals(getFunction(NF_constructorMethod))) { 283 assert(name.arguments.length == 1); 284 return name.arguments[0]; 285 } 286 return null; 287 } 288 289 private static void maybeCompile(LambdaForm lform, MemberName m) { 290 if (lform.vmentry == null && VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class)) 291 // Help along bootstrapping... 292 lform.compileToBytecode(); 293 } 294 295 /** Static wrapper for DirectMethodHandle.internalMemberName. */ 296 @ForceInline 297 /*non-public*/ static Object internalMemberName(Object mh) { 298 return ((DirectMethodHandle)mh).member; 299 } 300 301 /** Static wrapper for DirectMethodHandle.internalMemberName. 302 * This one also forces initialization. 303 */ 304 /*non-public*/ static Object internalMemberNameEnsureInit(Object mh) { 305 DirectMethodHandle dmh = (DirectMethodHandle)mh; 306 dmh.ensureInitialized(); 307 return dmh.member; 308 } 309 310 /*non-public*/ static 311 boolean shouldBeInitialized(MemberName member) { 312 switch (member.getReferenceKind()) { 313 case REF_invokeStatic: 314 case REF_getStatic: 315 case REF_putStatic: 316 case REF_newInvokeSpecial: 317 break; 318 default: 319 // No need to initialize the class on this kind of member. 320 return false; 321 } 322 Class<?> cls = member.getDeclaringClass(); 323 if (cls == ValueConversions.class || 324 cls == MethodHandleImpl.class || 325 cls == Invokers.class) { 326 // These guys have lots of <clinit> DMH creation but we know 327 // the MHs will not be used until the system is booted. 328 return false; 329 } 330 if (VerifyAccess.isSamePackage(MethodHandle.class, cls) || 331 VerifyAccess.isSamePackage(ValueConversions.class, cls)) { 332 // It is a system class. It is probably in the process of 333 // being initialized, but we will help it along just to be safe. 334 if (UNSAFE.shouldBeInitialized(cls)) { 335 UNSAFE.ensureClassInitialized(cls); 336 } 337 return false; 338 } 339 return UNSAFE.shouldBeInitialized(cls); 340 } 341 342 private static class EnsureInitialized extends ClassValue<WeakReference<Thread>> { 343 @Override 344 protected WeakReference<Thread> computeValue(Class<?> type) { 345 UNSAFE.ensureClassInitialized(type); 346 if (UNSAFE.shouldBeInitialized(type)) 347 // If the previous call didn't block, this can happen. 348 // We are executing inside <clinit>. 349 return new WeakReference<>(Thread.currentThread()); 350 return null; 351 } 352 static final EnsureInitialized INSTANCE = new EnsureInitialized(); 353 } 354 355 private void ensureInitialized() { 356 if (checkInitialized(member)) { 357 // The coast is clear. Delete the <clinit> barrier. 358 if (member.isField()) 359 updateForm(preparedFieldLambdaForm(member)); 360 else 361 updateForm(preparedLambdaForm(member)); 362 } 363 } 364 private static boolean checkInitialized(MemberName member) { 365 Class<?> defc = member.getDeclaringClass(); 366 WeakReference<Thread> ref = EnsureInitialized.INSTANCE.get(defc); 367 if (ref == null) { 368 return true; // the final state 369 } 370 Thread clinitThread = ref.get(); 371 // Somebody may still be running defc.<clinit>. 372 if (clinitThread == Thread.currentThread()) { 373 // If anybody is running defc.<clinit>, it is this thread. 374 if (UNSAFE.shouldBeInitialized(defc)) 375 // Yes, we are running it; keep the barrier for now. 376 return false; 377 } else { 378 // We are in a random thread. Block. 379 UNSAFE.ensureClassInitialized(defc); 380 } 381 assert(!UNSAFE.shouldBeInitialized(defc)); 382 // put it into the final state 383 EnsureInitialized.INSTANCE.remove(defc); 384 return true; 385 } 386 387 /*non-public*/ static void ensureInitialized(Object mh) { 388 ((DirectMethodHandle)mh).ensureInitialized(); 389 } 390 391 /** This subclass represents invokespecial instructions. */ 392 static class Special extends DirectMethodHandle { 393 private final Class<?> caller; 394 private Special(MethodType mtype, LambdaForm form, MemberName member, Class<?> caller) { 395 super(mtype, form, member); 396 this.caller = caller; 397 } 398 @Override 399 boolean isInvokeSpecial() { 400 return true; 401 } 402 @Override 403 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 404 return new Special(mt, lf, member, caller); 405 } 406 Object checkReceiver(Object recv) { 407 if (!caller.isInstance(recv)) { 408 String msg = String.format("Receiver class %s is not a subclass of caller class %s", 409 recv.getClass().getName(), caller.getName()); 410 throw new IncompatibleClassChangeError(msg); 411 } 412 return recv; 413 } 414 } 415 416 /** This subclass represents invokeinterface instructions. */ 417 static class Interface extends DirectMethodHandle { 418 private final Class<?> refc; 419 private Interface(MethodType mtype, LambdaForm form, MemberName member, Class<?> refc) { 420 super(mtype, form, member); 421 assert refc.isInterface() : refc; 422 this.refc = refc; 423 } 424 @Override 425 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 426 return new Interface(mt, lf, member, refc); 427 } 428 @Override 429 Object checkReceiver(Object recv) { 430 if (!refc.isInstance(recv)) { 431 String msg = String.format("Receiver class %s does not implement the requested interface %s", 432 recv.getClass().getName(), refc.getName()); 433 throw new IncompatibleClassChangeError(msg); 434 } 435 return recv; 436 } 437 } 438 439 /** Used for interface receiver type checks, by Interface and Special modes. */ 440 Object checkReceiver(Object recv) { 441 throw new InternalError("Should only be invoked on a subclass"); 442 } 443 444 445 /** This subclass handles constructor references. */ 446 static class Constructor extends DirectMethodHandle { 447 final MemberName initMethod; 448 final Class<?> instanceClass; 449 450 private Constructor(MethodType mtype, LambdaForm form, MemberName constructor, 451 MemberName initMethod, Class<?> instanceClass) { 452 super(mtype, form, constructor); 453 this.initMethod = initMethod; 454 this.instanceClass = instanceClass; 455 assert(initMethod.isResolved()); 456 } 457 @Override 458 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 459 return new Constructor(mt, lf, member, initMethod, instanceClass); 460 } 461 } 462 463 /*non-public*/ static Object constructorMethod(Object mh) { 464 Constructor dmh = (Constructor)mh; 465 return dmh.initMethod; 466 } 467 468 /*non-public*/ static Object allocateInstance(Object mh) throws InstantiationException { 469 Constructor dmh = (Constructor)mh; 470 return UNSAFE.allocateInstance(dmh.instanceClass); 471 } 472 473 /** This subclass handles non-static field references. */ 474 static class Accessor extends DirectMethodHandle { 475 final Class<?> fieldType; 476 final int fieldOffset; 477 private Accessor(MethodType mtype, LambdaForm form, MemberName member, 478 int fieldOffset) { 479 super(mtype, form, member); 480 this.fieldType = member.getFieldType(); 481 this.fieldOffset = fieldOffset; 482 } 483 484 @Override Object checkCast(Object obj) { 485 return fieldType.cast(obj); 486 } 487 @Override 488 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 489 return new Accessor(mt, lf, member, fieldOffset); 490 } 491 } 492 493 @ForceInline 494 /*non-public*/ static long fieldOffset(Object accessorObj) { 495 // Note: We return a long because that is what Unsafe.getObject likes. 496 // We store a plain int because it is more compact. 497 return ((Accessor)accessorObj).fieldOffset; 498 } 499 500 @ForceInline 501 /*non-public*/ static Object checkBase(Object obj) { 502 // Note that the object's class has already been verified, 503 // since the parameter type of the Accessor method handle 504 // is either member.getDeclaringClass or a subclass. 505 // This was verified in DirectMethodHandle.make. 506 // Therefore, the only remaining check is for null. 507 // Since this check is *not* guaranteed by Unsafe.getInt 508 // and its siblings, we need to make an explicit one here. 509 return Objects.requireNonNull(obj); 510 } 511 512 /** This subclass handles static field references. */ 513 static class StaticAccessor extends DirectMethodHandle { 514 private final Class<?> fieldType; 515 private final Object staticBase; 516 private final long staticOffset; 517 518 private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member, 519 Object staticBase, long staticOffset) { 520 super(mtype, form, member); 521 this.fieldType = member.getFieldType(); 522 this.staticBase = staticBase; 523 this.staticOffset = staticOffset; 524 } 525 526 @Override Object checkCast(Object obj) { 527 return fieldType.cast(obj); 528 } 529 @Override 530 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 531 return new StaticAccessor(mt, lf, member, staticBase, staticOffset); 532 } 533 } 534 535 @ForceInline 536 /*non-public*/ static Object nullCheck(Object obj) { 537 return Objects.requireNonNull(obj); 538 } 539 540 @ForceInline 541 /*non-public*/ static Object staticBase(Object accessorObj) { 542 return ((StaticAccessor)accessorObj).staticBase; 543 } 544 545 @ForceInline 546 /*non-public*/ static long staticOffset(Object accessorObj) { 547 return ((StaticAccessor)accessorObj).staticOffset; 548 } 549 550 @ForceInline 551 /*non-public*/ static Object checkCast(Object mh, Object obj) { 552 return ((DirectMethodHandle) mh).checkCast(obj); 553 } 554 555 Object checkCast(Object obj) { 556 return member.getReturnType().cast(obj); 557 } 558 559 // Caching machinery for field accessors: 560 static final byte 561 AF_GETFIELD = 0, 562 AF_PUTFIELD = 1, 563 AF_GETSTATIC = 2, 564 AF_PUTSTATIC = 3, 565 AF_GETSTATIC_INIT = 4, 566 AF_PUTSTATIC_INIT = 5, 567 AF_LIMIT = 6; 568 // Enumerate the different field kinds using Wrapper, 569 // with an extra case added for checked references. 570 static final int 571 FT_LAST_WRAPPER = Wrapper.COUNT-1, 572 FT_UNCHECKED_REF = Wrapper.OBJECT.ordinal(), 573 FT_CHECKED_REF = FT_LAST_WRAPPER+1, 574 FT_LIMIT = FT_LAST_WRAPPER+2; 575 private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) { 576 return ((formOp * FT_LIMIT * 2) 577 + (isVolatile ? FT_LIMIT : 0) 578 + ftypeKind); 579 } 580 @Stable 581 private static final LambdaForm[] ACCESSOR_FORMS 582 = new LambdaForm[afIndex(AF_LIMIT, false, 0)]; 583 static int ftypeKind(Class<?> ftype) { 584 if (ftype.isPrimitive()) 585 return Wrapper.forPrimitiveType(ftype).ordinal(); 586 else if (VerifyType.isNullReferenceConversion(Object.class, ftype)) 587 return FT_UNCHECKED_REF; 588 else 589 return FT_CHECKED_REF; 590 } 591 592 /** 593 * Create a LF which can access the given field. 594 * Cache and share this structure among all fields with 595 * the same basicType and refKind. 596 */ 597 private static LambdaForm preparedFieldLambdaForm(MemberName m) { 598 Class<?> ftype = m.getFieldType(); 599 boolean isVolatile = m.isVolatile(); 600 byte formOp; 601 switch (m.getReferenceKind()) { 602 case REF_getField: formOp = AF_GETFIELD; break; 603 case REF_putField: formOp = AF_PUTFIELD; break; 604 case REF_getStatic: formOp = AF_GETSTATIC; break; 605 case REF_putStatic: formOp = AF_PUTSTATIC; break; 606 default: throw new InternalError(m.toString()); 607 } 608 if (shouldBeInitialized(m)) { 609 // precompute the barrier-free version: 610 preparedFieldLambdaForm(formOp, isVolatile, ftype); 611 assert((AF_GETSTATIC_INIT - AF_GETSTATIC) == 612 (AF_PUTSTATIC_INIT - AF_PUTSTATIC)); 613 formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC); 614 } 615 LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype); 616 maybeCompile(lform, m); 617 assert(lform.methodType().dropParameterTypes(0, 1) 618 .equals(m.getInvocationType().basicType())) 619 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 620 return lform; 621 } 622 private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) { 623 int ftypeKind = ftypeKind(ftype); 624 int afIndex = afIndex(formOp, isVolatile, ftypeKind); 625 LambdaForm lform = ACCESSOR_FORMS[afIndex]; 626 if (lform != null) return lform; 627 lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind); 628 ACCESSOR_FORMS[afIndex] = lform; // don't bother with a CAS 629 return lform; 630 } 631 632 private static final Wrapper[] ALL_WRAPPERS = Wrapper.values(); 633 634 private static Kind getFieldKind(boolean isGetter, boolean isVolatile, Wrapper wrapper) { 635 if (isGetter) { 636 if (isVolatile) { 637 switch (wrapper) { 638 case BOOLEAN: return GET_BOOLEAN_VOLATILE; 639 case BYTE: return GET_BYTE_VOLATILE; 640 case SHORT: return GET_SHORT_VOLATILE; 641 case CHAR: return GET_CHAR_VOLATILE; 642 case INT: return GET_INT_VOLATILE; 643 case LONG: return GET_LONG_VOLATILE; 644 case FLOAT: return GET_FLOAT_VOLATILE; 645 case DOUBLE: return GET_DOUBLE_VOLATILE; 646 case OBJECT: return GET_OBJECT_VOLATILE; 647 } 648 } else { 649 switch (wrapper) { 650 case BOOLEAN: return GET_BOOLEAN; 651 case BYTE: return GET_BYTE; 652 case SHORT: return GET_SHORT; 653 case CHAR: return GET_CHAR; 654 case INT: return GET_INT; 655 case LONG: return GET_LONG; 656 case FLOAT: return GET_FLOAT; 657 case DOUBLE: return GET_DOUBLE; 658 case OBJECT: return GET_OBJECT; 659 } 660 } 661 } else { 662 if (isVolatile) { 663 switch (wrapper) { 664 case BOOLEAN: return PUT_BOOLEAN_VOLATILE; 665 case BYTE: return PUT_BYTE_VOLATILE; 666 case SHORT: return PUT_SHORT_VOLATILE; 667 case CHAR: return PUT_CHAR_VOLATILE; 668 case INT: return PUT_INT_VOLATILE; 669 case LONG: return PUT_LONG_VOLATILE; 670 case FLOAT: return PUT_FLOAT_VOLATILE; 671 case DOUBLE: return PUT_DOUBLE_VOLATILE; 672 case OBJECT: return PUT_OBJECT_VOLATILE; 673 } 674 } else { 675 switch (wrapper) { 676 case BOOLEAN: return PUT_BOOLEAN; 677 case BYTE: return PUT_BYTE; 678 case SHORT: return PUT_SHORT; 679 case CHAR: return PUT_CHAR; 680 case INT: return PUT_INT; 681 case LONG: return PUT_LONG; 682 case FLOAT: return PUT_FLOAT; 683 case DOUBLE: return PUT_DOUBLE; 684 case OBJECT: return PUT_OBJECT; 685 } 686 } 687 } 688 throw new AssertionError("Invalid arguments"); 689 } 690 691 static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) { 692 boolean isGetter = (formOp & 1) == (AF_GETFIELD & 1); 693 boolean isStatic = (formOp >= AF_GETSTATIC); 694 boolean needsInit = (formOp >= AF_GETSTATIC_INIT); 695 boolean needsCast = (ftypeKind == FT_CHECKED_REF); 696 Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]); 697 Class<?> ft = fw.primitiveType(); 698 assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind); 699 700 // getObject, putIntVolatile, etc. 701 Kind kind = getFieldKind(isGetter, isVolatile, fw); 702 703 MethodType linkerType; 704 if (isGetter) 705 linkerType = MethodType.methodType(ft, Object.class, long.class); 706 else 707 linkerType = MethodType.methodType(void.class, Object.class, long.class, ft); 708 MemberName linker = new MemberName(Unsafe.class, kind.methodName, linkerType, REF_invokeVirtual); 709 try { 710 linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class); 711 } catch (ReflectiveOperationException ex) { 712 throw newInternalError(ex); 713 } 714 715 // What is the external type of the lambda form? 716 MethodType mtype; 717 if (isGetter) 718 mtype = MethodType.methodType(ft); 719 else 720 mtype = MethodType.methodType(void.class, ft); 721 mtype = mtype.basicType(); // erase short to int, etc. 722 if (!isStatic) 723 mtype = mtype.insertParameterTypes(0, Object.class); 724 final int DMH_THIS = 0; 725 final int ARG_BASE = 1; 726 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 727 // if this is for non-static access, the base pointer is stored at this index: 728 final int OBJ_BASE = isStatic ? -1 : ARG_BASE; 729 // if this is for write access, the value to be written is stored at this index: 730 final int SET_VALUE = isGetter ? -1 : ARG_LIMIT - 1; 731 int nameCursor = ARG_LIMIT; 732 final int F_HOLDER = (isStatic ? nameCursor++ : -1); // static base if any 733 final int F_OFFSET = nameCursor++; // Either static offset or field offset. 734 final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1); 735 final int U_HOLDER = nameCursor++; // UNSAFE holder 736 final int INIT_BAR = (needsInit ? nameCursor++ : -1); 737 final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1); 738 final int LINKER_CALL = nameCursor++; 739 final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1); 740 final int RESULT = nameCursor-1; // either the call or the cast 741 Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); 742 if (needsInit) 743 names[INIT_BAR] = new Name(getFunction(NF_ensureInitialized), names[DMH_THIS]); 744 if (needsCast && !isGetter) 745 names[PRE_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[SET_VALUE]); 746 Object[] outArgs = new Object[1 + linkerType.parameterCount()]; 747 assert(outArgs.length == (isGetter ? 3 : 4)); 748 outArgs[0] = names[U_HOLDER] = new Name(getFunction(NF_UNSAFE)); 749 if (isStatic) { 750 outArgs[1] = names[F_HOLDER] = new Name(getFunction(NF_staticBase), names[DMH_THIS]); 751 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_staticOffset), names[DMH_THIS]); 752 } else { 753 outArgs[1] = names[OBJ_CHECK] = new Name(getFunction(NF_checkBase), names[OBJ_BASE]); 754 outArgs[2] = names[F_OFFSET] = new Name(getFunction(NF_fieldOffset), names[DMH_THIS]); 755 } 756 if (!isGetter) { 757 outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]); 758 } 759 for (Object a : outArgs) assert(a != null); 760 names[LINKER_CALL] = new Name(linker, outArgs); 761 if (needsCast && isGetter) 762 names[POST_CAST] = new Name(getFunction(NF_checkCast), names[DMH_THIS], names[LINKER_CALL]); 763 for (Name n : names) assert(n != null); 764 765 LambdaForm form; 766 if (needsCast || needsInit) { 767 // can't use the pre-generated form when casting and/or initializing 768 form = new LambdaForm(ARG_LIMIT, names, RESULT); 769 } else { 770 form = new LambdaForm(ARG_LIMIT, names, RESULT, kind); 771 } 772 773 if (LambdaForm.debugNames()) { 774 // add some detail to the lambdaForm debugname, 775 // significant only for debugging 776 StringBuilder nameBuilder = new StringBuilder(kind.methodName); 777 if (isStatic) { 778 nameBuilder.append("Static"); 779 } else { 780 nameBuilder.append("Field"); 781 } 782 if (needsCast) { 783 nameBuilder.append("Cast"); 784 } 785 if (needsInit) { 786 nameBuilder.append("Init"); 787 } 788 LambdaForm.associateWithDebugName(form, nameBuilder.toString()); 789 } 790 return form; 791 } 792 793 /** 794 * Pre-initialized NamedFunctions for bootstrapping purposes. 795 */ 796 static final byte NF_internalMemberName = 0, 797 NF_internalMemberNameEnsureInit = 1, 798 NF_ensureInitialized = 2, 799 NF_fieldOffset = 3, 800 NF_checkBase = 4, 801 NF_staticBase = 5, 802 NF_staticOffset = 6, 803 NF_checkCast = 7, 804 NF_allocateInstance = 8, 805 NF_constructorMethod = 9, 806 NF_UNSAFE = 10, 807 NF_checkReceiver = 11, 808 NF_LIMIT = 12; 809 810 private static final @Stable NamedFunction[] NFS = new NamedFunction[NF_LIMIT]; 811 812 private static NamedFunction getFunction(byte func) { 813 NamedFunction nf = NFS[func]; 814 if (nf != null) { 815 return nf; 816 } 817 // Each nf must be statically invocable or we get tied up in our bootstraps. 818 nf = NFS[func] = createFunction(func); 819 assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf)); 820 return nf; 821 } 822 823 private static final MethodType OBJ_OBJ_TYPE = MethodType.methodType(Object.class, Object.class); 824 825 private static final MethodType LONG_OBJ_TYPE = MethodType.methodType(long.class, Object.class); 826 827 private static NamedFunction createFunction(byte func) { 828 try { 829 switch (func) { 830 case NF_internalMemberName: 831 return getNamedFunction("internalMemberName", OBJ_OBJ_TYPE); 832 case NF_internalMemberNameEnsureInit: 833 return getNamedFunction("internalMemberNameEnsureInit", OBJ_OBJ_TYPE); 834 case NF_ensureInitialized: 835 return getNamedFunction("ensureInitialized", MethodType.methodType(void.class, Object.class)); 836 case NF_fieldOffset: 837 return getNamedFunction("fieldOffset", LONG_OBJ_TYPE); 838 case NF_checkBase: 839 return getNamedFunction("checkBase", OBJ_OBJ_TYPE); 840 case NF_staticBase: 841 return getNamedFunction("staticBase", OBJ_OBJ_TYPE); 842 case NF_staticOffset: 843 return getNamedFunction("staticOffset", LONG_OBJ_TYPE); 844 case NF_checkCast: 845 return getNamedFunction("checkCast", MethodType.methodType(Object.class, Object.class, Object.class)); 846 case NF_allocateInstance: 847 return getNamedFunction("allocateInstance", OBJ_OBJ_TYPE); 848 case NF_constructorMethod: 849 return getNamedFunction("constructorMethod", OBJ_OBJ_TYPE); 850 case NF_UNSAFE: 851 MemberName member = new MemberName(MethodHandleStatics.class, "UNSAFE", Unsafe.class, REF_getField); 852 return new NamedFunction( 853 MemberName.getFactory() 854 .resolveOrFail(REF_getField, member, DirectMethodHandle.class, NoSuchMethodException.class)); 855 case NF_checkReceiver: 856 member = new MemberName(DirectMethodHandle.class, "checkReceiver", OBJ_OBJ_TYPE, REF_invokeVirtual); 857 return new NamedFunction( 858 MemberName.getFactory() 859 .resolveOrFail(REF_invokeVirtual, member, DirectMethodHandle.class, NoSuchMethodException.class)); 860 default: 861 throw newInternalError("Unknown function: " + func); 862 } 863 } catch (ReflectiveOperationException ex) { 864 throw newInternalError(ex); 865 } 866 } 867 868 private static NamedFunction getNamedFunction(String name, MethodType type) 869 throws ReflectiveOperationException 870 { 871 MemberName member = new MemberName(DirectMethodHandle.class, name, type, REF_invokeStatic); 872 return new NamedFunction( 873 MemberName.getFactory() 874 .resolveOrFail(REF_invokeStatic, member, DirectMethodHandle.class, NoSuchMethodException.class)); 875 } 876 877 static { 878 // The Holder class will contain pre-generated DirectMethodHandles resolved 879 // speculatively using MemberName.getFactory().resolveOrNull. However, that 880 // doesn't initialize the class, which subtly breaks inlining etc. By forcing 881 // initialization of the Holder class we avoid these issues. 882 UNSAFE.ensureClassInitialized(Holder.class); 883 } 884 885 /* Placeholder class for DirectMethodHandles generated ahead of time */ 886 final class Holder {} 887 }