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 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.MethodHandleNatives.Constants.*; 42 import static java.lang.invoke.MethodHandleStatics.UNSAFE; 43 import static java.lang.invoke.MethodHandleStatics.newInternalError; 44 import static java.lang.invoke.MethodTypeForm.*; 45 46 /** 47 * The flavor of method handle which implements a constant reference 48 * to a class member. 49 * @author jrose 50 */ 51 class DirectMethodHandle extends MethodHandle { 52 final MemberName member; 53 54 // Constructors and factory methods in this class *must* be package scoped or private. 55 private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member) { 56 super(mtype, form); 57 if (!member.isResolved()) throw new InternalError(); 58 59 if (member.getDeclaringClass().isInterface() && 60 member.isMethod() && !member.isAbstract()) { 61 // Check for corner case: invokeinterface of Object method 62 MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind()); 63 m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null); 64 if (m != null && m.isPublic()) { 65 assert(member.getReferenceKind() == m.getReferenceKind()); // else this.form is wrong 66 member = m; 67 } 68 } 69 70 this.member = member; 71 } 72 73 // Factory methods: 74 static DirectMethodHandle make(byte refKind, Class<?> receiver, MemberName member) { 75 MethodType mtype = member.getMethodOrFieldType(); 76 if (!member.isStatic()) { 77 if (!member.getDeclaringClass().isAssignableFrom(receiver) || member.isConstructor()) 78 throw new InternalError(member.toString()); 79 mtype = mtype.insertParameterTypes(0, receiver); 80 } 81 if (!member.isField()) { 82 if (refKind == REF_invokeSpecial) { 83 member = member.asSpecial(); 84 LambdaForm lform = preparedLambdaForm(member); 85 return new Special(mtype, lform, member); 86 } else { 87 LambdaForm lform = preparedLambdaForm(member); 88 return new DirectMethodHandle(mtype, lform, member); 89 } 90 } else { 91 LambdaForm lform = preparedFieldLambdaForm(member); 92 if (member.isStatic()) { 93 long offset = MethodHandleNatives.staticFieldOffset(member); 94 Object base = MethodHandleNatives.staticFieldBase(member); 95 return new StaticAccessor(mtype, lform, member, base, offset); 96 } else { 97 long offset = MethodHandleNatives.objectFieldOffset(member); 98 assert(offset == (int)offset); 99 return new Accessor(mtype, lform, member, (int)offset); 100 } 101 } 102 } 103 static DirectMethodHandle make(Class<?> receiver, MemberName member) { 104 byte refKind = member.getReferenceKind(); 105 if (refKind == REF_invokeSpecial) 106 refKind = REF_invokeVirtual; 107 return make(refKind, receiver, member); 108 } 109 static DirectMethodHandle make(MemberName member) { 110 if (member.isConstructor()) 111 return makeAllocator(member); 112 return make(member.getDeclaringClass(), member); 113 } 114 private static DirectMethodHandle makeAllocator(MemberName ctor) { 115 assert(ctor.isConstructor() && ctor.getName().equals("<init>")); 116 Class<?> instanceClass = ctor.getDeclaringClass(); 117 ctor = ctor.asConstructor(); 118 assert(ctor.isConstructor() && ctor.getReferenceKind() == REF_newInvokeSpecial) : ctor; 119 MethodType mtype = ctor.getMethodType().changeReturnType(instanceClass); 120 LambdaForm lform = preparedLambdaForm(ctor); 121 MemberName init = ctor.asSpecial(); 122 assert(init.getMethodType().returnType() == void.class); 123 return new Constructor(mtype, lform, ctor, init, instanceClass); 124 } 125 126 @Override 127 BoundMethodHandle rebind() { 128 return BoundMethodHandle.makeReinvoker(this); 129 } 130 131 @Override 132 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 133 assert(this.getClass() == DirectMethodHandle.class); // must override in subclasses 134 return new DirectMethodHandle(mt, lf, member); 135 } 136 137 @Override 138 String internalProperties() { 139 return "\n& DMH.MN="+internalMemberName(); 140 } 141 142 //// Implementation methods. 143 @Override 144 @ForceInline 145 MemberName internalMemberName() { 146 return member; 147 } 148 149 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory(); 150 151 /** 152 * Create a LF which can invoke the given method. 153 * Cache and share this structure among all methods with 154 * the same basicType and refKind. 155 */ 156 private static LambdaForm preparedLambdaForm(MemberName m) { 157 assert(m.isInvocable()) : m; // call preparedFieldLambdaForm instead 158 MethodType mtype = m.getInvocationType().basicType(); 159 assert(!m.isMethodHandleInvoke()) : m; 160 int which; 161 switch (m.getReferenceKind()) { 162 case REF_invokeVirtual: which = LF_INVVIRTUAL; break; 163 case REF_invokeStatic: which = LF_INVSTATIC; break; 164 case REF_invokeSpecial: which = LF_INVSPECIAL; break; 165 case REF_invokeInterface: which = LF_INVINTERFACE; break; 166 case REF_newInvokeSpecial: which = LF_NEWINVSPECIAL; break; 167 default: throw new InternalError(m.toString()); 168 } 169 if (which == LF_INVSTATIC && shouldBeInitialized(m)) { 170 // precompute the barrier-free version: 171 preparedLambdaForm(mtype, which); 172 which = LF_INVSTATIC_INIT; 173 } 174 LambdaForm lform = preparedLambdaForm(mtype, which); 175 maybeCompile(lform, m); 176 assert(lform.methodType().dropParameterTypes(0, 1) 177 .equals(m.getInvocationType().basicType())) 178 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 179 return lform; 180 } 181 182 private static LambdaForm preparedLambdaForm(MethodType mtype, int which) { 183 LambdaForm lform = mtype.form().cachedLambdaForm(which); 184 if (lform != null) return lform; 185 lform = makePreparedLambdaForm(mtype, which); 186 return mtype.form().setCachedLambdaForm(which, lform); 187 } 188 189 static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) { 190 boolean needsInit = (which == LF_INVSTATIC_INIT); 191 boolean doesAlloc = (which == LF_NEWINVSPECIAL); 192 String linkerName, lambdaName; 193 switch (which) { 194 case LF_INVVIRTUAL: linkerName = "linkToVirtual"; lambdaName = "DMH.invokeVirtual"; break; 195 case LF_INVSTATIC: linkerName = "linkToStatic"; lambdaName = "DMH.invokeStatic"; break; 196 case LF_INVSTATIC_INIT:linkerName = "linkToStatic"; lambdaName = "DMH.invokeStaticInit"; break; 197 case LF_INVSPECIAL: linkerName = "linkToSpecial"; lambdaName = "DMH.invokeSpecial"; break; 198 case LF_INVINTERFACE: linkerName = "linkToInterface"; lambdaName = "DMH.invokeInterface"; break; 199 case LF_NEWINVSPECIAL: linkerName = "linkToSpecial"; lambdaName = "DMH.newInvokeSpecial"; break; 200 default: throw new InternalError("which="+which); 201 } 202 203 MethodType mtypeWithArg = mtype.appendParameterTypes(MemberName.class); 204 if (doesAlloc) 205 mtypeWithArg = mtypeWithArg 206 .insertParameterTypes(0, Object.class) // insert newly allocated obj 207 .changeReturnType(void.class); // <init> returns void 208 MemberName linker = new MemberName(MethodHandle.class, linkerName, mtypeWithArg, REF_invokeStatic); 209 try { 210 linker = IMPL_NAMES.resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class); 211 } catch (ReflectiveOperationException ex) { 212 throw newInternalError(ex); 213 } 214 final int DMH_THIS = 0; 215 final int ARG_BASE = 1; 216 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 217 int nameCursor = ARG_LIMIT; 218 final int NEW_OBJ = (doesAlloc ? nameCursor++ : -1); 219 final int GET_MEMBER = nameCursor++; 220 final int LINKER_CALL = nameCursor++; 221 Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); 222 assert(names.length == nameCursor); 223 if (doesAlloc) { 224 // names = { argx,y,z,... new C, init method } 225 names[NEW_OBJ] = new Name(NF_allocateInstance, names[DMH_THIS]); 226 names[GET_MEMBER] = new Name(NF_constructorMethod, names[DMH_THIS]); 227 } else if (needsInit) { 228 names[GET_MEMBER] = new Name(NF_internalMemberNameEnsureInit, names[DMH_THIS]); 229 } else { 230 names[GET_MEMBER] = new Name(NF_internalMemberName, names[DMH_THIS]); 231 } 232 assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]); 233 Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class); 234 assert(outArgs[outArgs.length-1] == names[GET_MEMBER]); // look, shifted args! 235 int result = LAST_RESULT; 236 if (doesAlloc) { 237 assert(outArgs[outArgs.length-2] == names[NEW_OBJ]); // got to move this one 238 System.arraycopy(outArgs, 0, outArgs, 1, outArgs.length-2); 239 outArgs[0] = names[NEW_OBJ]; 240 result = NEW_OBJ; 241 } 242 names[LINKER_CALL] = new Name(linker, outArgs); 243 lambdaName += "_" + shortenSignature(basicTypeSignature(mtype)); 244 LambdaForm lform = new LambdaForm(lambdaName, ARG_LIMIT, names, result); 245 246 // This is a tricky bit of code. Don't send it through the LF interpreter. 247 lform.compileToBytecode(Holder.class); 248 return lform; 249 } 250 251 static Object findDirectMethodHandle(Name name) { 252 if (name.function == NF_internalMemberName || 253 name.function == NF_internalMemberNameEnsureInit || 254 name.function == NF_constructorMethod) { 255 assert(name.arguments.length == 1); 256 return name.arguments[0]; 257 } 258 return null; 259 } 260 261 private static void maybeCompile(LambdaForm lform, MemberName m) { 262 if (lform.vmentry == null && VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class)) 263 // Help along bootstrapping... 264 lform.compileToBytecode(); 265 } 266 267 /** Static wrapper for DirectMethodHandle.internalMemberName. */ 268 @ForceInline 269 /*non-public*/ static Object internalMemberName(Object mh) { 270 return ((DirectMethodHandle)mh).member; 271 } 272 273 /** Static wrapper for DirectMethodHandle.internalMemberName. 274 * This one also forces initialization. 275 */ 276 /*non-public*/ static Object internalMemberNameEnsureInit(Object mh) { 277 DirectMethodHandle dmh = (DirectMethodHandle)mh; 278 dmh.ensureInitialized(); 279 return dmh.member; 280 } 281 282 /*non-public*/ static 283 boolean shouldBeInitialized(MemberName member) { 284 switch (member.getReferenceKind()) { 285 case REF_invokeStatic: 286 case REF_getStatic: 287 case REF_putStatic: 288 case REF_newInvokeSpecial: 289 break; 290 default: 291 // No need to initialize the class on this kind of member. 292 return false; 293 } 294 Class<?> cls = member.getDeclaringClass(); 295 if (cls == ValueConversions.class || 296 cls == MethodHandleImpl.class || 297 cls == Invokers.class) { 298 // These guys have lots of <clinit> DMH creation but we know 299 // the MHs will not be used until the system is booted. 300 return false; 301 } 302 if (VerifyAccess.isSamePackage(MethodHandle.class, cls) || 303 VerifyAccess.isSamePackage(ValueConversions.class, cls)) { 304 // It is a system class. It is probably in the process of 305 // being initialized, but we will help it along just to be safe. 306 if (UNSAFE.shouldBeInitialized(cls)) { 307 UNSAFE.ensureClassInitialized(cls); 308 } 309 return false; 310 } 311 return UNSAFE.shouldBeInitialized(cls); 312 } 313 314 private static class EnsureInitialized extends ClassValue<WeakReference<Thread>> { 315 @Override 316 protected WeakReference<Thread> computeValue(Class<?> type) { 317 UNSAFE.ensureClassInitialized(type); 318 if (UNSAFE.shouldBeInitialized(type)) 319 // If the previous call didn't block, this can happen. 320 // We are executing inside <clinit>. 321 return new WeakReference<>(Thread.currentThread()); 322 return null; 323 } 324 static final EnsureInitialized INSTANCE = new EnsureInitialized(); 325 } 326 327 private void ensureInitialized() { 328 if (checkInitialized(member)) { 329 // The coast is clear. Delete the <clinit> barrier. 330 if (member.isField()) 331 updateForm(preparedFieldLambdaForm(member)); 332 else 333 updateForm(preparedLambdaForm(member)); 334 } 335 } 336 private static boolean checkInitialized(MemberName member) { 337 Class<?> defc = member.getDeclaringClass(); 338 WeakReference<Thread> ref = EnsureInitialized.INSTANCE.get(defc); 339 if (ref == null) { 340 return true; // the final state 341 } 342 Thread clinitThread = ref.get(); 343 // Somebody may still be running defc.<clinit>. 344 if (clinitThread == Thread.currentThread()) { 345 // If anybody is running defc.<clinit>, it is this thread. 346 if (UNSAFE.shouldBeInitialized(defc)) 347 // Yes, we are running it; keep the barrier for now. 348 return false; 349 } else { 350 // We are in a random thread. Block. 351 UNSAFE.ensureClassInitialized(defc); 352 } 353 assert(!UNSAFE.shouldBeInitialized(defc)); 354 // put it into the final state 355 EnsureInitialized.INSTANCE.remove(defc); 356 return true; 357 } 358 359 /*non-public*/ static void ensureInitialized(Object mh) { 360 ((DirectMethodHandle)mh).ensureInitialized(); 361 } 362 363 /** This subclass represents invokespecial instructions. */ 364 static class Special extends DirectMethodHandle { 365 private Special(MethodType mtype, LambdaForm form, MemberName member) { 366 super(mtype, form, member); 367 } 368 @Override 369 boolean isInvokeSpecial() { 370 return true; 371 } 372 @Override 373 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 374 return new Special(mt, lf, member); 375 } 376 } 377 378 /** This subclass handles constructor references. */ 379 static class Constructor extends DirectMethodHandle { 380 final MemberName initMethod; 381 final Class<?> instanceClass; 382 383 private Constructor(MethodType mtype, LambdaForm form, MemberName constructor, 384 MemberName initMethod, Class<?> instanceClass) { 385 super(mtype, form, constructor); 386 this.initMethod = initMethod; 387 this.instanceClass = instanceClass; 388 assert(initMethod.isResolved()); 389 } 390 @Override 391 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 392 return new Constructor(mt, lf, member, initMethod, instanceClass); 393 } 394 } 395 396 /*non-public*/ static Object constructorMethod(Object mh) { 397 Constructor dmh = (Constructor)mh; 398 return dmh.initMethod; 399 } 400 401 /*non-public*/ static Object allocateInstance(Object mh) throws InstantiationException { 402 Constructor dmh = (Constructor)mh; 403 return UNSAFE.allocateInstance(dmh.instanceClass); 404 } 405 406 /** This subclass handles non-static field references. */ 407 static class Accessor extends DirectMethodHandle { 408 final Class<?> fieldType; 409 final int fieldOffset; 410 private Accessor(MethodType mtype, LambdaForm form, MemberName member, 411 int fieldOffset) { 412 super(mtype, form, member); 413 this.fieldType = member.getFieldType(); 414 this.fieldOffset = fieldOffset; 415 } 416 417 @Override Object checkCast(Object obj) { 418 return fieldType.cast(obj); 419 } 420 @Override 421 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 422 return new Accessor(mt, lf, member, fieldOffset); 423 } 424 } 425 426 @ForceInline 427 /*non-public*/ static long fieldOffset(Object accessorObj) { 428 // Note: We return a long because that is what Unsafe.getObject likes. 429 // We store a plain int because it is more compact. 430 return ((Accessor)accessorObj).fieldOffset; 431 } 432 433 @ForceInline 434 /*non-public*/ static Object checkBase(Object obj) { 435 // Note that the object's class has already been verified, 436 // since the parameter type of the Accessor method handle 437 // is either member.getDeclaringClass or a subclass. 438 // This was verified in DirectMethodHandle.make. 439 // Therefore, the only remaining check is for null. 440 // Since this check is *not* guaranteed by Unsafe.getInt 441 // and its siblings, we need to make an explicit one here. 442 return Objects.requireNonNull(obj); 443 } 444 445 /** This subclass handles static field references. */ 446 static class StaticAccessor extends DirectMethodHandle { 447 private final Class<?> fieldType; 448 private final Object staticBase; 449 private final long staticOffset; 450 451 private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member, 452 Object staticBase, long staticOffset) { 453 super(mtype, form, member); 454 this.fieldType = member.getFieldType(); 455 this.staticBase = staticBase; 456 this.staticOffset = staticOffset; 457 } 458 459 @Override Object checkCast(Object obj) { 460 return fieldType.cast(obj); 461 } 462 @Override 463 MethodHandle copyWith(MethodType mt, LambdaForm lf) { 464 return new StaticAccessor(mt, lf, member, staticBase, staticOffset); 465 } 466 } 467 468 @ForceInline 469 /*non-public*/ static Object nullCheck(Object obj) { 470 return Objects.requireNonNull(obj); 471 } 472 473 @ForceInline 474 /*non-public*/ static Object staticBase(Object accessorObj) { 475 return ((StaticAccessor)accessorObj).staticBase; 476 } 477 478 @ForceInline 479 /*non-public*/ static long staticOffset(Object accessorObj) { 480 return ((StaticAccessor)accessorObj).staticOffset; 481 } 482 483 @ForceInline 484 /*non-public*/ static Object checkCast(Object mh, Object obj) { 485 return ((DirectMethodHandle) mh).checkCast(obj); 486 } 487 488 Object checkCast(Object obj) { 489 return member.getReturnType().cast(obj); 490 } 491 492 // Caching machinery for field accessors: 493 private static final byte 494 AF_GETFIELD = 0, 495 AF_PUTFIELD = 1, 496 AF_GETSTATIC = 2, 497 AF_PUTSTATIC = 3, 498 AF_GETSTATIC_INIT = 4, 499 AF_PUTSTATIC_INIT = 5, 500 AF_LIMIT = 6; 501 // Enumerate the different field kinds using Wrapper, 502 // with an extra case added for checked references. 503 private static final int 504 FT_LAST_WRAPPER = Wrapper.COUNT-1, 505 FT_UNCHECKED_REF = Wrapper.OBJECT.ordinal(), 506 FT_CHECKED_REF = FT_LAST_WRAPPER+1, 507 FT_LIMIT = FT_LAST_WRAPPER+2; 508 private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) { 509 return ((formOp * FT_LIMIT * 2) 510 + (isVolatile ? FT_LIMIT : 0) 511 + ftypeKind); 512 } 513 @Stable 514 private static final LambdaForm[] ACCESSOR_FORMS 515 = new LambdaForm[afIndex(AF_LIMIT, false, 0)]; 516 private static int ftypeKind(Class<?> ftype) { 517 if (ftype.isPrimitive()) 518 return Wrapper.forPrimitiveType(ftype).ordinal(); 519 else if (VerifyType.isNullReferenceConversion(Object.class, ftype)) 520 return FT_UNCHECKED_REF; 521 else 522 return FT_CHECKED_REF; 523 } 524 525 /** 526 * Create a LF which can access the given field. 527 * Cache and share this structure among all fields with 528 * the same basicType and refKind. 529 */ 530 private static LambdaForm preparedFieldLambdaForm(MemberName m) { 531 Class<?> ftype = m.getFieldType(); 532 boolean isVolatile = m.isVolatile(); 533 byte formOp; 534 switch (m.getReferenceKind()) { 535 case REF_getField: formOp = AF_GETFIELD; break; 536 case REF_putField: formOp = AF_PUTFIELD; break; 537 case REF_getStatic: formOp = AF_GETSTATIC; break; 538 case REF_putStatic: formOp = AF_PUTSTATIC; break; 539 default: throw new InternalError(m.toString()); 540 } 541 if (shouldBeInitialized(m)) { 542 // precompute the barrier-free version: 543 preparedFieldLambdaForm(formOp, isVolatile, ftype); 544 assert((AF_GETSTATIC_INIT - AF_GETSTATIC) == 545 (AF_PUTSTATIC_INIT - AF_PUTSTATIC)); 546 formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC); 547 } 548 LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype); 549 maybeCompile(lform, m); 550 assert(lform.methodType().dropParameterTypes(0, 1) 551 .equals(m.getInvocationType().basicType())) 552 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType()); 553 return lform; 554 } 555 private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) { 556 int ftypeKind = ftypeKind(ftype); 557 int afIndex = afIndex(formOp, isVolatile, ftypeKind); 558 LambdaForm lform = ACCESSOR_FORMS[afIndex]; 559 if (lform != null) return lform; 560 lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind); 561 ACCESSOR_FORMS[afIndex] = lform; // don't bother with a CAS 562 return lform; 563 } 564 565 private static final Wrapper[] ALL_WRAPPERS = Wrapper.values(); 566 567 private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) { 568 boolean isGetter = (formOp & 1) == (AF_GETFIELD & 1); 569 boolean isStatic = (formOp >= AF_GETSTATIC); 570 boolean needsInit = (formOp >= AF_GETSTATIC_INIT); 571 boolean needsCast = (ftypeKind == FT_CHECKED_REF); 572 Wrapper fw = (needsCast ? Wrapper.OBJECT : ALL_WRAPPERS[ftypeKind]); 573 Class<?> ft = fw.primitiveType(); 574 assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind); 575 576 // getObject, putIntVolatile, etc. 577 StringBuilder nameBuilder = new StringBuilder(); 578 if (isGetter) { 579 nameBuilder.append("get"); 580 } else { 581 nameBuilder.append("put"); 582 } 583 nameBuilder.append(fw.primitiveSimpleName()); 584 nameBuilder.setCharAt(3, Character.toUpperCase(nameBuilder.charAt(3))); 585 if (isVolatile) { 586 nameBuilder.append("Volatile"); 587 } 588 589 MethodType linkerType; 590 if (isGetter) 591 linkerType = MethodType.methodType(ft, Object.class, long.class); 592 else 593 linkerType = MethodType.methodType(void.class, Object.class, long.class, ft); 594 MemberName linker = new MemberName(Unsafe.class, nameBuilder.toString(), linkerType, REF_invokeVirtual); 595 try { 596 linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class); 597 } catch (ReflectiveOperationException ex) { 598 throw newInternalError(ex); 599 } 600 601 // What is the external type of the lambda form? 602 MethodType mtype; 603 if (isGetter) 604 mtype = MethodType.methodType(ft); 605 else 606 mtype = MethodType.methodType(void.class, ft); 607 mtype = mtype.basicType(); // erase short to int, etc. 608 if (!isStatic) 609 mtype = mtype.insertParameterTypes(0, Object.class); 610 final int DMH_THIS = 0; 611 final int ARG_BASE = 1; 612 final int ARG_LIMIT = ARG_BASE + mtype.parameterCount(); 613 // if this is for non-static access, the base pointer is stored at this index: 614 final int OBJ_BASE = isStatic ? -1 : ARG_BASE; 615 // if this is for write access, the value to be written is stored at this index: 616 final int SET_VALUE = isGetter ? -1 : ARG_LIMIT - 1; 617 int nameCursor = ARG_LIMIT; 618 final int F_HOLDER = (isStatic ? nameCursor++ : -1); // static base if any 619 final int F_OFFSET = nameCursor++; // Either static offset or field offset. 620 final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1); 621 final int INIT_BAR = (needsInit ? nameCursor++ : -1); 622 final int PRE_CAST = (needsCast && !isGetter ? nameCursor++ : -1); 623 final int LINKER_CALL = nameCursor++; 624 final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1); 625 final int RESULT = nameCursor-1; // either the call or the cast 626 Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType()); 627 if (needsInit) 628 names[INIT_BAR] = new Name(NF_ensureInitialized, names[DMH_THIS]); 629 if (needsCast && !isGetter) 630 names[PRE_CAST] = new Name(NF_checkCast, names[DMH_THIS], names[SET_VALUE]); 631 Object[] outArgs = new Object[1 + linkerType.parameterCount()]; 632 assert(outArgs.length == (isGetter ? 3 : 4)); 633 outArgs[0] = UNSAFE; 634 if (isStatic) { 635 outArgs[1] = names[F_HOLDER] = new Name(NF_staticBase, names[DMH_THIS]); 636 outArgs[2] = names[F_OFFSET] = new Name(NF_staticOffset, names[DMH_THIS]); 637 } else { 638 outArgs[1] = names[OBJ_CHECK] = new Name(NF_checkBase, names[OBJ_BASE]); 639 outArgs[2] = names[F_OFFSET] = new Name(NF_fieldOffset, names[DMH_THIS]); 640 } 641 if (!isGetter) { 642 outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]); 643 } 644 for (Object a : outArgs) assert(a != null); 645 names[LINKER_CALL] = new Name(linker, outArgs); 646 if (needsCast && isGetter) 647 names[POST_CAST] = new Name(NF_checkCast, names[DMH_THIS], names[LINKER_CALL]); 648 for (Name n : names) assert(n != null); 649 // add some detail to the lambdaForm debugname, 650 // significant only for debugging 651 if (isStatic) { 652 nameBuilder.append("Static"); 653 } else { 654 nameBuilder.append("Field"); 655 } 656 if (needsCast) nameBuilder.append("Cast"); 657 if (needsInit) nameBuilder.append("Init"); 658 return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT); 659 } 660 661 /** 662 * Pre-initialized NamedFunctions for bootstrapping purposes. 663 * Factored in an inner class to delay initialization until first usage. 664 */ 665 static final NamedFunction 666 NF_internalMemberName, 667 NF_internalMemberNameEnsureInit, 668 NF_ensureInitialized, 669 NF_fieldOffset, 670 NF_checkBase, 671 NF_staticBase, 672 NF_staticOffset, 673 NF_checkCast, 674 NF_allocateInstance, 675 NF_constructorMethod; 676 static { 677 try { 678 NamedFunction nfs[] = { 679 NF_internalMemberName = new NamedFunction(DirectMethodHandle.class 680 .getDeclaredMethod("internalMemberName", Object.class)), 681 NF_internalMemberNameEnsureInit = new NamedFunction(DirectMethodHandle.class 682 .getDeclaredMethod("internalMemberNameEnsureInit", Object.class)), 683 NF_ensureInitialized = new NamedFunction(DirectMethodHandle.class 684 .getDeclaredMethod("ensureInitialized", Object.class)), 685 NF_fieldOffset = new NamedFunction(DirectMethodHandle.class 686 .getDeclaredMethod("fieldOffset", Object.class)), 687 NF_checkBase = new NamedFunction(DirectMethodHandle.class 688 .getDeclaredMethod("checkBase", Object.class)), 689 NF_staticBase = new NamedFunction(DirectMethodHandle.class 690 .getDeclaredMethod("staticBase", Object.class)), 691 NF_staticOffset = new NamedFunction(DirectMethodHandle.class 692 .getDeclaredMethod("staticOffset", Object.class)), 693 NF_checkCast = new NamedFunction(DirectMethodHandle.class 694 .getDeclaredMethod("checkCast", Object.class, Object.class)), 695 NF_allocateInstance = new NamedFunction(DirectMethodHandle.class 696 .getDeclaredMethod("allocateInstance", Object.class)), 697 NF_constructorMethod = new NamedFunction(DirectMethodHandle.class 698 .getDeclaredMethod("constructorMethod", Object.class)) 699 }; 700 // Each nf must be statically invocable or we get tied up in our bootstraps. 701 assert(InvokerBytecodeGenerator.isStaticallyInvocable(nfs)); 702 } catch (ReflectiveOperationException ex) { 703 throw newInternalError(ex); 704 } 705 } 706 707 static { 708 // The DMH class will contain pre-generated DirectMethodHandles resolved 709 // speculatively using MemberName.getFactory().resolveOrNull. However, that 710 // doesn't initialize the class, which subtly breaks inlining etc. By forcing 711 // initialization of the Holder class we avoid these issues. 712 UNSAFE.ensureClassInitialized(Holder.class); 713 } 714 715 /* Placeholder class for DirectMethodHandles generated ahead of time */ 716 private final class Holder {} 717 }