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