< prev index next >

src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java

Print this page




   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.org.objectweb.asm.ClassWriter;

  29 import jdk.internal.org.objectweb.asm.Label;
  30 import jdk.internal.org.objectweb.asm.MethodVisitor;
  31 import jdk.internal.org.objectweb.asm.Opcodes;
  32 import jdk.internal.org.objectweb.asm.Type;
  33 import sun.invoke.util.VerifyAccess;
  34 import sun.invoke.util.VerifyType;
  35 import sun.invoke.util.Wrapper;
  36 import sun.reflect.misc.ReflectUtil;
  37 
  38 import java.io.File;
  39 import java.io.FileOutputStream;
  40 import java.io.IOException;
  41 import java.lang.reflect.Modifier;
  42 import java.util.ArrayList;
  43 import java.util.Arrays;
  44 import java.util.HashMap;

  45 import java.util.stream.Stream;
  46 
  47 import static java.lang.invoke.LambdaForm.BasicType;
  48 import static java.lang.invoke.LambdaForm.BasicType.*;
  49 import static java.lang.invoke.LambdaForm.*;
  50 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  51 import static java.lang.invoke.MethodHandleStatics.*;

  52 
  53 /**
  54  * Code generation backend for LambdaForm.
  55  * <p>
  56  * @author John Rose, JSR 292 EG
  57  */
  58 class InvokerBytecodeGenerator {
  59     /** Define class names for convenience. */
  60     private static final String MH      = "java/lang/invoke/MethodHandle";
  61     private static final String MHI     = "java/lang/invoke/MethodHandleImpl";
  62     private static final String LF      = "java/lang/invoke/LambdaForm";
  63     private static final String LFN     = "java/lang/invoke/LambdaForm$Name";
  64     private static final String CLS     = "java/lang/Class";
  65     private static final String OBJ     = "java/lang/Object";
  66     private static final String OBJARY  = "[Ljava/lang/Object;";
  67 
  68     private static final String LOOP_CLAUSES = MHI + "$LoopClauses";
  69     private static final String MHARY2       = "[[L" + MH + ";";


  70 
  71     private static final String LF_SIG  = "L" + LF + ";";
  72     private static final String LFN_SIG = "L" + LFN + ";";
  73     private static final String LL_SIG  = "(L" + OBJ + ";)L" + OBJ + ";";
  74     private static final String LLV_SIG = "(L" + OBJ + ";L" + OBJ + ";)V";
  75     private static final String CLASS_PREFIX = LF + "$";
  76     private static final String SOURCE_PREFIX = "LambdaForm$";
  77 
  78     /** Name of its super class*/
  79     static final String INVOKER_SUPER_NAME = OBJ;
  80 
  81     /** Name of new class */
  82     private final String className;
  83 
  84     private final LambdaForm lambdaForm;
  85     private final String     invokerName;
  86     private final MethodType invokerType;
  87 
  88     /** Info about local variables in compiled lambda form */
  89     private int[]       localsMap;    // index
  90     private Class<?>[]  localClasses; // type
  91 
  92     /** ASM bytecode generation. */
  93     private ClassWriter cw;
  94     private MethodVisitor mv;

  95 
  96     /** Single element internal class name lookup cache. */
  97     private Class<?> lastClass;
  98     private String lastInternalName;
  99 
 100     private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory();
 101     private static final Class<?> HOST_CLASS = LambdaForm.class;









 102 
 103     /** Main constructor; other constructors delegate to this one. */
 104     private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize,
 105                                      String className, String invokerName, MethodType invokerType) {
 106         int p = invokerName.indexOf('.');
 107         if (p > -1) {
 108             className = invokerName.substring(0, p);
 109             invokerName = invokerName.substring(p + 1);
 110         }
 111         if (DUMP_CLASS_FILES) {
 112             className = makeDumpableClassName(className);
 113         }
 114         this.className  = className;
 115         this.lambdaForm = lambdaForm;
 116         this.invokerName = invokerName;
 117         this.invokerType = invokerType;
 118         this.localsMap = new int[localsMapSize+1]; // last entry of localsMap is count of allocated local slots
 119         this.localClasses = new Class<?>[localsMapSize+1];
 120     }
 121 


 200                     }
 201                 }
 202             });
 203         }
 204     }
 205 
 206     private static String makeDumpableClassName(String className) {
 207         Integer ctr;
 208         synchronized (DUMP_CLASS_FILES_COUNTERS) {
 209             ctr = DUMP_CLASS_FILES_COUNTERS.get(className);
 210             if (ctr == null)  ctr = 0;
 211             DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1);
 212         }
 213         String sfx = ctr.toString();
 214         while (sfx.length() < 3)
 215             sfx = "0"+sfx;
 216         className += sfx;
 217         return className;
 218     }
 219 
 220     class CpPatch {
 221         final int index;

 222         final Object value;
 223         CpPatch(int index, Object value) {
 224             this.index = index;


 225             this.value = value;
 226         }


 227         public String toString() {
 228             return "CpPatch/index="+index+",value="+value;
 229         }
 230     }
 231 
 232     private final ArrayList<CpPatch> cpPatches = new ArrayList<>();
 233 
 234     private int cph = 0;  // for counting constant placeholders








 235 
 236     String constantPlaceholder(Object arg) {
 237         String cpPlaceholder = "CONSTANT_PLACEHOLDER_" + cph++;
 238         if (DUMP_CLASS_FILES) cpPlaceholder += " <<" + debugString(arg) + ">>";
 239         // TODO check if arg is already in the constant pool
 240         // insert placeholder in CP and remember the patch
 241         int index = cw.newConst((Object) cpPlaceholder);
 242         cpPatches.add(new CpPatch(index, arg));
 243         return cpPlaceholder;

 244     }
 245 
 246     Object[] cpPatches(byte[] classFile) {
 247         int size = getConstantPoolSize(classFile);
 248         Object[] res = new Object[size];
 249         for (CpPatch p : cpPatches) {
 250             if (p.index >= size)
 251                 throw new InternalError("in cpool["+size+"]: "+p+"\n"+Arrays.toString(Arrays.copyOf(classFile, 20)));
 252             res[p.index] = p.value;
 253         }
 254         return res;
 255     }
 256 
 257     private static String debugString(Object arg) {
 258         if (arg instanceof MethodHandle) {
 259             MethodHandle mh = (MethodHandle) arg;
 260             MemberName member = mh.internalMemberName();
 261             if (member != null)
 262                 return member.toString();
 263             return mh.debugString();
 264         }
 265         return arg.toString();
 266     }
 267 
 268     /**
 269      * Extract the number of constant pool entries from a given class file.
 270      *
 271      * @param classFile the bytes of the class file in question.
 272      * @return the number of entries in the constant pool.
 273      */
 274     private static int getConstantPoolSize(byte[] classFile) {
 275         // The first few bytes:
 276         // u4 magic;
 277         // u2 minor_version;
 278         // u2 major_version;
 279         // u2 constant_pool_count;
 280         return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF);
 281     }
 282 
 283     /**
 284      * Extract the MemberName of a newly-defined method.
 285      */
 286     private MemberName loadMethod(byte[] classFile) {
 287         Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, cpPatches(classFile));
 288         return resolveInvokerMember(invokerClass, invokerName, invokerType);
 289     }
 290 
 291     /**
 292      * Define a given class as anonymous class in the runtime system.
 293      */
 294     private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, Object[] patches) {
 295         Class<?> invokerClass = UNSAFE.defineAnonymousClass(HOST_CLASS, classBytes, patches);
 296         UNSAFE.ensureClassInitialized(invokerClass);  // Make sure the class is initialized; VM might complain.
 297         return invokerClass;
 298     }
 299 

 300     private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) {
 301         MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic);
 302         try {
 303             member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class);
 304         } catch (ReflectiveOperationException e) {
 305             throw newInternalError(e);
 306         }
 307         return member;
 308     }
 309 
 310     /**
 311      * Set up class file generation.
 312      */
 313     private ClassWriter classFilePrologue() {
 314         final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 315         cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);

 316         cw.visit(Opcodes.V1_8, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
 317                 CLASS_PREFIX + className, null, INVOKER_SUPER_NAME, null);
 318         cw.visitSource(SOURCE_PREFIX + className, null);
 319         return cw;
 320     }
 321 
 322     private void methodPrologue() {
 323         String invokerDesc = invokerType.toMethodDescriptorString();
 324         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
 325     }
 326 
 327     /**
 328      * Tear down class file generation.
 329      */
 330     private void methodEpilogue() {
 331         mv.visitMaxs(0, 0);
 332         mv.visitEnd();
 333     }
 334 










































 335     /*
 336      * Low-level emit helpers.
 337      */
 338     private void emitConst(Object con) {
 339         if (con == null) {
 340             mv.visitInsn(Opcodes.ACONST_NULL);
 341             return;
 342         }
 343         if (con instanceof Integer) {
 344             emitIconstInsn((int) con);
 345             return;
 346         }
 347         if (con instanceof Byte) {
 348             emitIconstInsn((byte)con);
 349             return;
 350         }
 351         if (con instanceof Short) {
 352             emitIconstInsn((short)con);
 353             return;
 354         }


 387             short sx = (short)x;
 388             if (x == sx) {
 389                 if (sx >= 0 && sx <= 1) {
 390                     mv.visitInsn(Opcodes.DCONST_0 + (int) sx);
 391                 } else {
 392                     emitIconstInsn((int) x);
 393                     mv.visitInsn(Opcodes.I2D);
 394                 }
 395                 return;
 396             }
 397         }
 398         if (con instanceof Boolean) {
 399             emitIconstInsn((boolean) con ? 1 : 0);
 400             return;
 401         }
 402         // fall through:
 403         mv.visitLdcInsn(con);
 404     }
 405 
 406     private void emitIconstInsn(final int cst) {




 407         if (cst >= -1 && cst <= 5) {
 408             mv.visitInsn(Opcodes.ICONST_0 + cst);
 409         } else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) {
 410             mv.visitIntInsn(Opcodes.BIPUSH, cst);
 411         } else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) {
 412             mv.visitIntInsn(Opcodes.SIPUSH, cst);
 413         } else {
 414             mv.visitLdcInsn(cst);
 415         }
 416     }
 417 
 418     /*
 419      * NOTE: These load/store methods use the localsMap to find the correct index!
 420      */
 421     private void emitLoadInsn(BasicType type, int index) {
 422         int opcode = loadInsnOpcode(type);
 423         mv.visitVarInsn(opcode, localsMap[index]);
 424     }
 425 
 426     private int loadInsnOpcode(BasicType type) throws InternalError {


 556         }
 557         return false;
 558     }
 559 
 560     private void emitReferenceCast(Class<?> cls, Object arg) {
 561         Name writeBack = null;  // local to write back result
 562         if (arg instanceof Name) {
 563             Name n = (Name) arg;
 564             if (lambdaForm.useCount(n) > 1) {
 565                 // This guy gets used more than once.
 566                 writeBack = n;
 567                 if (assertStaticType(cls, n)) {
 568                     return; // this cast was already performed
 569                 }
 570             }
 571         }
 572         if (isStaticallyNameable(cls)) {
 573             String sig = getInternalName(cls);
 574             mv.visitTypeInsn(Opcodes.CHECKCAST, sig);
 575         } else {
 576             mv.visitLdcInsn(constantPlaceholder(cls));
 577             mv.visitTypeInsn(Opcodes.CHECKCAST, CLS);
 578             mv.visitInsn(Opcodes.SWAP);
 579             mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLS, "cast", LL_SIG, false);
 580             if (Object[].class.isAssignableFrom(cls))
 581                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY);
 582             else if (PROFILE_LEVEL > 0)
 583                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ);
 584         }
 585         if (writeBack != null) {
 586             mv.visitInsn(Opcodes.DUP);
 587             emitAstoreInsn(writeBack.index());
 588         }
 589     }
 590 
 591     /**
 592      * Emits an actual return instruction conforming to the given return type.
 593      */
 594     private void emitReturnInsn(BasicType type) {
 595         int opcode;
 596         switch (type) {
 597         case I_TYPE:  opcode = Opcodes.IRETURN;  break;


 673             case PUT_DOUBLE:                // fall-through
 674             case DIRECT_NEW_INVOKE_SPECIAL: // fall-through
 675             case DIRECT_INVOKE_INTERFACE:   // fall-through
 676             case DIRECT_INVOKE_SPECIAL:     // fall-through
 677             case DIRECT_INVOKE_SPECIAL_IFC: // fall-through
 678             case DIRECT_INVOKE_STATIC:      // fall-through
 679             case DIRECT_INVOKE_STATIC_INIT: // fall-through
 680             case DIRECT_INVOKE_VIRTUAL:     return resolveFrom(name, invokerType, DirectMethodHandle.Holder.class);
 681         }
 682         return null;
 683     }
 684 
 685     /**
 686      * Generate customized bytecode for a given LambdaForm.
 687      */
 688     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 689         MemberName pregenerated = lookupPregenerated(form, invokerType);
 690         if (pregenerated != null)  return pregenerated; // pre-generated bytecode
 691 
 692         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 693         return g.loadMethod(g.generateCustomizedCodeBytes());
 694     }
 695 
 696     /** Generates code to check that actual receiver and LambdaForm matches */
 697     private boolean checkActualReceiver() {
 698         // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0
 699         mv.visitInsn(Opcodes.DUP);
 700         mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]);
 701         mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false);
 702         return true;
 703     }
 704 
 705     static String className(String cn) {
 706         assert checkClassName(cn): "Class not found: " + cn;
 707         return cn;
 708     }
 709 
 710     static boolean checkClassName(String cn) {
 711         Type tp = Type.getType(cn);
 712         // additional sanity so only valid "L;" descriptors work
 713         if (tp.getSort() != Type.OBJECT) {


 716         try {
 717             Class<?> c = Class.forName(tp.getClassName(), false, null);
 718             return true;
 719         } catch (ClassNotFoundException e) {
 720             return false;
 721         }
 722     }
 723 
 724     static final String      DONTINLINE_SIG = className("Ljdk/internal/vm/annotation/DontInline;");
 725     static final String     FORCEINLINE_SIG = className("Ljdk/internal/vm/annotation/ForceInline;");
 726     static final String          HIDDEN_SIG = className("Ljdk/internal/vm/annotation/Hidden;");
 727     static final String INJECTEDPROFILE_SIG = className("Ljava/lang/invoke/InjectedProfile;");
 728     static final String     LF_COMPILED_SIG = className("Ljava/lang/invoke/LambdaForm$Compiled;");
 729 
 730     /**
 731      * Generate an invoker method for the passed {@link LambdaForm}.
 732      */
 733     private byte[] generateCustomizedCodeBytes() {
 734         classFilePrologue();
 735         addMethod();

 736         bogusMethod(lambdaForm);
 737 
 738         final byte[] classFile = toByteArray();
 739         maybeDump(classFile);
 740         return classFile;
 741     }
 742 
 743     void setClassWriter(ClassWriter cw) {
 744         this.cw = cw;
 745     }
 746 
 747     void addMethod() {
 748         methodPrologue();
 749 
 750         // Suppress this method in backtraces displayed to the user.
 751         mv.visitAnnotation(HIDDEN_SIG, true);
 752 
 753         // Mark this method as a compiled LambdaForm
 754         mv.visitAnnotation(LF_COMPILED_SIG, true);
 755 
 756         if (lambdaForm.forceInline) {
 757             // Force inlining of this invoker method.
 758             mv.visitAnnotation(FORCEINLINE_SIG, true);
 759         } else {
 760             mv.visitAnnotation(DONTINLINE_SIG, true);
 761         }
 762 
 763         constantPlaceholder(lambdaForm); // keep LambdaForm instance & its compiled form lifetime tightly coupled.
 764 
 765         if (lambdaForm.customized != null) {
 766             // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute
 767             // receiver MethodHandle (at slot #0) with an embedded constant and use it instead.
 768             // It enables more efficient code generation in some situations, since embedded constants
 769             // are compile-time constants for JIT compiler.
 770             mv.visitLdcInsn(constantPlaceholder(lambdaForm.customized));
 771             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 772             assert(checkActualReceiver()); // expects MethodHandle on top of the stack
 773             mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]);
 774         }
 775 
 776         // iterate over the form's names, generating bytecode instructions for each
 777         // start iterating at the first name following the arguments
 778         Name onStack = null;
 779         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 780             Name name = lambdaForm.names[i];
 781 
 782             emitStoreResult(onStack);
 783             onStack = name;  // unless otherwise modified below
 784             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 785             switch (intr) {
 786                 case SELECT_ALTERNATIVE:
 787                     assert lambdaForm.isSelectAlternative(i);
 788                     if (PROFILE_GWT) {
 789                         assert(name.arguments[0] instanceof Name &&
 790                                 ((Name)name.arguments[0]).refersTo(MethodHandleImpl.class, "profileBoolean"));


 880         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH;
 881         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 882         assert elementType != null;
 883         emitPushArguments(name, 0);
 884         if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) {
 885             Wrapper w = Wrapper.forPrimitiveType(elementType);
 886             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 887         }
 888         mv.visitInsn(arrayOpcode);
 889     }
 890 
 891     /**
 892      * Emit an invoke for the given name.
 893      */
 894     void emitInvoke(Name name) {
 895         assert(!name.isLinkerMethodInvoke());  // should use the static path for these
 896         if (true) {
 897             // push receiver
 898             MethodHandle target = name.function.resolvedHandle();
 899             assert(target != null) : name.exprString();
 900             mv.visitLdcInsn(constantPlaceholder(target));
 901             emitReferenceCast(MethodHandle.class, target);
 902         } else {
 903             // load receiver
 904             emitAloadInsn(0);
 905             emitReferenceCast(MethodHandle.class, null);
 906             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 907             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 908             // TODO more to come
 909         }
 910 
 911         // push arguments
 912         emitPushArguments(name, 0);
 913 
 914         // invocation
 915         MethodType type = name.function.methodType();
 916         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 917     }
 918 
 919     private static Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 920         // Sample classes from each package we are willing to bind to statically:


 936     static boolean isStaticallyInvocable(Name name) {
 937         return isStaticallyInvocable(name.function.member());
 938     }
 939 
 940     static boolean isStaticallyInvocable(MemberName member) {
 941         if (member == null)  return false;
 942         if (member.isConstructor())  return false;
 943         Class<?> cls = member.getDeclaringClass();
 944         // Fast-path non-private members declared by MethodHandles, which is a common
 945         // case
 946         if (MethodHandle.class.isAssignableFrom(cls) && !member.isPrivate()) {
 947             assert(isStaticallyInvocableType(member.getMethodOrFieldType()));
 948             return true;
 949         }
 950         if (cls.isArray() || cls.isPrimitive())
 951             return false;  // FIXME
 952         if (cls.isAnonymousClass() || cls.isLocalClass())
 953             return false;  // inner class of some sort
 954         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
 955             return false;  // not on BCP
 956         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 957             return false;
 958         if (!isStaticallyInvocableType(member.getMethodOrFieldType()))
 959             return false;
 960         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
 961             return true;   // in java.lang.invoke package
 962         if (member.isPublic() && isStaticallyNameable(cls))
 963             return true;
 964         return false;
 965     }
 966 
 967     private static boolean isStaticallyInvocableType(MethodType mtype) {
 968         if (!isStaticallyNameable(mtype.returnType()))
 969             return false;
 970         for (Class<?> ptype : mtype.parameterArray())
 971             if (!isStaticallyNameable(ptype))
 972                 return false;
 973         return true;
 974     }
 975 
 976     static boolean isStaticallyNameable(Class<?> cls) {
 977         if (cls == Object.class)
 978             return true;
 979         if (MethodHandle.class.isAssignableFrom(cls)) {
 980             assert(!ReflectUtil.isVMAnonymousClass(cls));
 981             return true;
 982         }
 983         while (cls.isArray())
 984             cls = cls.getComponentType();
 985         if (cls.isPrimitive())
 986             return true;  // int[].class, for example
 987         if (ReflectUtil.isVMAnonymousClass(cls)) // FIXME: switch to supported API once it is added
 988             return false;
 989         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
 990         if (cls.getClassLoader() != Object.class.getClassLoader())
 991             return false;
 992         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
 993             return true;
 994         if (!Modifier.isPublic(cls.getModifiers()))
 995             return false;
 996         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
 997             if (VerifyAccess.isSamePackage(pkgcls, cls))
 998                 return true;
 999         }
1000         return false;
1001     }
1002 
1003     void emitStaticInvoke(Name name) {
1004         emitStaticInvoke(name.function.member(), name);
1005     }
1006 
1007     /**


1039             Class<?> rtype = member.getInvocationType().returnType();
1040             assert(!rtype.isPrimitive());
1041             if (rtype != Object.class && !rtype.isInterface()) {
1042                 assertStaticType(rtype, name);
1043             }
1044         }
1045     }
1046 
1047     void emitNewArray(Name name) throws InternalError {
1048         Class<?> rtype = name.function.methodType().returnType();
1049         if (name.arguments.length == 0) {
1050             // The array will be a constant.
1051             Object emptyArray;
1052             try {
1053                 emptyArray = name.function.resolvedHandle().invoke();
1054             } catch (Throwable ex) {
1055                 throw uncaughtException(ex);
1056             }
1057             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
1058             assert(emptyArray.getClass() == rtype);  // exact typing
1059             mv.visitLdcInsn(constantPlaceholder(emptyArray));
1060             emitReferenceCast(rtype, emptyArray);
1061             return;
1062         }
1063         Class<?> arrayElementType = rtype.getComponentType();
1064         assert(arrayElementType != null);
1065         emitIconstInsn(name.arguments.length);
1066         int xas = Opcodes.AASTORE;
1067         if (!arrayElementType.isPrimitive()) {
1068             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
1069         } else {
1070             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
1071             xas = arrayInsnOpcode(tc, xas);
1072             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
1073         }
1074         // store arguments
1075         for (int i = 0; i < name.arguments.length; i++) {
1076             mv.visitInsn(Opcodes.DUP);
1077             emitIconstInsn(i);
1078             emitPushArgument(name, i);
1079             mv.visitInsn(xas);


1580     }
1581 
1582     private void emitPushArgument(Name name, int paramIndex) {
1583         Object arg = name.arguments[paramIndex];
1584         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1585         emitPushArgument(ptype, arg);
1586     }
1587 
1588     private void emitPushArgument(Class<?> ptype, Object arg) {
1589         BasicType bptype = basicType(ptype);
1590         if (arg instanceof Name) {
1591             Name n = (Name) arg;
1592             emitLoadInsn(n.type, n.index());
1593             emitImplicitConversion(n.type, ptype, n);
1594         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1595             emitConst(arg);
1596         } else {
1597             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1598                 emitConst(arg);
1599             } else {
1600                 mv.visitLdcInsn(constantPlaceholder(arg));
1601                 emitImplicitConversion(L_TYPE, ptype, arg);
1602             }
1603         }
1604     }
1605 
1606     /**
1607      * Store the name to its local, if necessary.
1608      */
1609     private void emitStoreResult(Name name) {
1610         if (name != null && name.type != V_TYPE) {
1611             // non-void: actually assign
1612             emitStoreInsn(name.type, name.index());
1613         }
1614     }
1615 
1616     /**
1617      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1618      */
1619     private void emitReturn(Name onStack) {
1620         // return statement


1727     }
1728 
1729     private void emitX2I(Wrapper type) {
1730         switch (type) {
1731         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1732         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1733         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1734         default:      throw new InternalError("unknown type: " + type);
1735         }
1736     }
1737 
1738     /**
1739      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1740      */
1741     static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) {
1742         assert(isValidSignature(basicTypeSignature(mt)));
1743         String name = "interpret_"+basicTypeChar(mt.returnType());
1744         MethodType type = mt;  // includes leading argument
1745         type = type.changeParameterType(0, MethodHandle.class);
1746         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1747         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
1748     }
1749 
1750     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1751         classFilePrologue();
1752         methodPrologue();
1753 
1754         // Suppress this method in backtraces displayed to the user.
1755         mv.visitAnnotation(HIDDEN_SIG, true);
1756 
1757         // Don't inline the interpreter entry.
1758         mv.visitAnnotation(DONTINLINE_SIG, true);
1759 
1760         // create parameter array
1761         emitIconstInsn(invokerType.parameterCount());
1762         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1763 
1764         // fill parameter array
1765         for (int i = 0; i < invokerType.parameterCount(); i++) {
1766             Class<?> ptype = invokerType.parameterType(i);
1767             mv.visitInsn(Opcodes.DUP);


1772                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1773             }
1774             mv.visitInsn(Opcodes.AASTORE);
1775         }
1776         // invoke
1777         emitAloadInsn(0);
1778         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1779         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1780         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1781 
1782         // maybe unbox
1783         Class<?> rtype = invokerType.returnType();
1784         if (rtype.isPrimitive() && rtype != void.class) {
1785             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1786         }
1787 
1788         // return statement
1789         emitReturnInsn(basicType(rtype));
1790 
1791         methodEpilogue();

1792         bogusMethod(invokerType);
1793 
1794         final byte[] classFile = cw.toByteArray();
1795         maybeDump(classFile);
1796         return classFile;
1797     }
1798 
1799     /**
1800      * Generate bytecode for a NamedFunction invoker.
1801      */
1802     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1803         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1804         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1805         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1806         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
1807     }
1808 
1809     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1810         MethodType dstType = typeForm.erasedType();
1811         classFilePrologue();
1812         methodPrologue();
1813 
1814         // Suppress this method in backtraces displayed to the user.
1815         mv.visitAnnotation(HIDDEN_SIG, true);
1816 
1817         // Force inlining of this invoker method.
1818         mv.visitAnnotation(FORCEINLINE_SIG, true);
1819 
1820         // Load receiver
1821         emitAloadInsn(0);
1822 
1823         // Load arguments from array
1824         for (int i = 0; i < dstType.parameterCount(); i++) {
1825             emitAloadInsn(1);
1826             emitIconstInsn(i);


1840         String targetDesc = dstType.basicType().toMethodDescriptorString();
1841         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1842 
1843         // Box primitive types
1844         Class<?> rtype = dstType.returnType();
1845         if (rtype != void.class && rtype.isPrimitive()) {
1846             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1847             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1848             // boolean casts not allowed
1849             emitPrimCast(srcWrapper, dstWrapper);
1850             emitBoxing(dstWrapper);
1851         }
1852 
1853         // If the return type is void we return a null reference.
1854         if (rtype == void.class) {
1855             mv.visitInsn(Opcodes.ACONST_NULL);
1856         }
1857         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1858 
1859         methodEpilogue();

1860         bogusMethod(dstType);
1861 
1862         final byte[] classFile = cw.toByteArray();
1863         maybeDump(classFile);
1864         return classFile;
1865     }
1866 
1867     /**
1868      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1869      * for debugging purposes.
1870      */
1871     private void bogusMethod(Object os) {
1872         if (DUMP_CLASS_FILES) {
1873             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1874             mv.visitLdcInsn(os.toString());
1875             mv.visitInsn(Opcodes.POP);
1876             mv.visitInsn(Opcodes.RETURN);
1877             mv.visitMaxs(0, 0);
1878             mv.visitEnd();
1879         }


   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.org.objectweb.asm.ClassWriter;
  29 import jdk.internal.org.objectweb.asm.FieldVisitor;
  30 import jdk.internal.org.objectweb.asm.Label;
  31 import jdk.internal.org.objectweb.asm.MethodVisitor;
  32 import jdk.internal.org.objectweb.asm.Opcodes;
  33 import jdk.internal.org.objectweb.asm.Type;
  34 import sun.invoke.util.VerifyAccess;
  35 import sun.invoke.util.VerifyType;
  36 import sun.invoke.util.Wrapper;
  37 import sun.reflect.misc.ReflectUtil;
  38 
  39 import java.io.File;
  40 import java.io.FileOutputStream;
  41 import java.io.IOException;
  42 import java.lang.reflect.Modifier;
  43 import java.util.ArrayList;
  44 import java.util.Arrays;
  45 import java.util.HashMap;
  46 import java.util.List;
  47 import java.util.stream.Stream;
  48 
  49 import static java.lang.invoke.LambdaForm.BasicType;
  50 import static java.lang.invoke.LambdaForm.BasicType.*;
  51 import static java.lang.invoke.LambdaForm.*;
  52 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  53 import static java.lang.invoke.MethodHandleStatics.*;
  54 import static java.lang.invoke.MethodHandles.Lookup.*;
  55 
  56 /**
  57  * Code generation backend for LambdaForm.
  58  * <p>
  59  * @author John Rose, JSR 292 EG
  60  */
  61 class InvokerBytecodeGenerator {
  62     /** Define class names for convenience. */
  63     private static final String MH      = "java/lang/invoke/MethodHandle";
  64     private static final String MHI     = "java/lang/invoke/MethodHandleImpl";
  65     private static final String LF      = "java/lang/invoke/LambdaForm";
  66     private static final String LFN     = "java/lang/invoke/LambdaForm$Name";
  67     private static final String CLS     = "java/lang/Class";
  68     private static final String OBJ     = "java/lang/Object";
  69     private static final String OBJARY  = "[Ljava/lang/Object;";
  70 
  71     private static final String LOOP_CLAUSES = MHI + "$LoopClauses";
  72     private static final String MHARY2       = "[[L" + MH + ";";
  73     private static final String MH_SIG       = "L" + MH + ";";
  74 
  75 
  76     private static final String LF_SIG  = "L" + LF + ";";
  77     private static final String LFN_SIG = "L" + LFN + ";";
  78     private static final String LL_SIG  = "(L" + OBJ + ";)L" + OBJ + ";";
  79     private static final String LLV_SIG = "(L" + OBJ + ";L" + OBJ + ";)V";
  80     private static final String CLASS_PREFIX = LF + "$";
  81     private static final String SOURCE_PREFIX = "LambdaForm$";
  82 
  83     /** Name of its super class*/
  84     static final String INVOKER_SUPER_NAME = OBJ;
  85 
  86     /** Name of new class */
  87     private final String className;
  88 
  89     private final LambdaForm lambdaForm;
  90     private final String     invokerName;
  91     private final MethodType invokerType;
  92 
  93     /** Info about local variables in compiled lambda form */
  94     private int[]       localsMap;    // index
  95     private Class<?>[]  localClasses; // type
  96 
  97     /** ASM bytecode generation. */
  98     private ClassWriter cw;
  99     private MethodVisitor mv;
 100     private final List<ClassData> classData = new ArrayList<>();
 101 
 102     /** Single element internal class name lookup cache. */
 103     private Class<?> lastClass;
 104     private String lastInternalName;
 105 
 106     private static final MemberName.Factory MEMBERNAME_FACTORY = MemberName.getFactory();
 107     private static final Class<?> HOST_CLASS = LambdaForm.class;
 108     private static final MethodHandles.Lookup LOOKUP = lookup();
 109 
 110     private static MethodHandles.Lookup lookup() {
 111         try {
 112             return MethodHandles.privateLookupIn(HOST_CLASS, IMPL_LOOKUP);
 113         } catch (IllegalAccessException e) {
 114             throw newInternalError(e);
 115         }
 116     }
 117 
 118     /** Main constructor; other constructors delegate to this one. */
 119     private InvokerBytecodeGenerator(LambdaForm lambdaForm, int localsMapSize,
 120                                      String className, String invokerName, MethodType invokerType) {
 121         int p = invokerName.indexOf('.');
 122         if (p > -1) {
 123             className = invokerName.substring(0, p);
 124             invokerName = invokerName.substring(p + 1);
 125         }
 126         if (DUMP_CLASS_FILES) {
 127             className = makeDumpableClassName(className);
 128         }
 129         this.className  = className;
 130         this.lambdaForm = lambdaForm;
 131         this.invokerName = invokerName;
 132         this.invokerType = invokerType;
 133         this.localsMap = new int[localsMapSize+1]; // last entry of localsMap is count of allocated local slots
 134         this.localClasses = new Class<?>[localsMapSize+1];
 135     }
 136 


 215                     }
 216                 }
 217             });
 218         }
 219     }
 220 
 221     private static String makeDumpableClassName(String className) {
 222         Integer ctr;
 223         synchronized (DUMP_CLASS_FILES_COUNTERS) {
 224             ctr = DUMP_CLASS_FILES_COUNTERS.get(className);
 225             if (ctr == null)  ctr = 0;
 226             DUMP_CLASS_FILES_COUNTERS.put(className, ctr+1);
 227         }
 228         String sfx = ctr.toString();
 229         while (sfx.length() < 3)
 230             sfx = "0"+sfx;
 231         className += sfx;
 232         return className;
 233     }
 234 
 235     public static class ClassData {
 236         final String name;
 237         final String desc;
 238         final Object value;
 239 
 240         ClassData(String name, String desc, Object value) {
 241             this.name = name;
 242             this.desc = desc;
 243             this.value = value;
 244         }
 245 
 246         public String name() { return name; }
 247         public String toString() {
 248             return name + ",value="+value;
 249         }
 250     }
 251 
 252     String classData(Object arg) {
 253         String desc;
 254         if (arg instanceof Class) {
 255             desc = "Ljava/lang/Class;";
 256         } else if (arg instanceof MethodHandle) {
 257             desc = MH_SIG;
 258         } else if (arg instanceof LambdaForm) {
 259             desc = LF_SIG;
 260         } else {
 261             desc = "Ljava/lang/Object;";
 262         }
 263 
 264         Class<?> c = arg.getClass();
 265         while (c.isArray()) {
 266             c = c.getComponentType();
 267         }
 268         // unique static variable name
 269         String name = "_DATA_" + c.getSimpleName() + "_" + classData.size();
 270         ClassData cd = new ClassData(name, desc, arg);
 271         classData.add(cd);
 272         return cd.name();
 273     }
 274 
 275     List<Object> classDataValues() {
 276         Object[] data = new Object[classData.size()];
 277         for (int i = 0; i < classData.size(); i++) {
 278             data[i] = classData.get(i).value;



 279         }
 280         return List.of(data);
 281     }
 282 
 283     private static String debugString(Object arg) {
 284         if (arg instanceof MethodHandle) {
 285             MethodHandle mh = (MethodHandle) arg;
 286             MemberName member = mh.internalMemberName();
 287             if (member != null)
 288                 return member.toString();
 289             return mh.debugString();
 290         }
 291         return arg.toString();
 292     }
 293 
 294     /**
 295      * Extract the number of constant pool entries from a given class file.
 296      *
 297      * @param classFile the bytes of the class file in question.
 298      * @return the number of entries in the constant pool.
 299      */
 300     private static int getConstantPoolSize(byte[] classFile) {
 301         // The first few bytes:
 302         // u4 magic;
 303         // u2 minor_version;
 304         // u2 major_version;
 305         // u2 constant_pool_count;
 306         return ((classFile[8] & 0xFF) << 8) | (classFile[9] & 0xFF);
 307     }
 308 
 309     /**
 310      * Extract the MemberName of a newly-defined method.
 311      */
 312     private MemberName loadMethod(byte[] classFile, List<Object> classData) {
 313         Class<?> invokerClass = loadAndInitializeInvokerClass(classFile, classData);
 314         return resolveInvokerMember(invokerClass, invokerName, invokerType);
 315     }
 316 
 317     /**
 318      * Define a given class as anonymous class in the runtime system.
 319      */
 320     private static Class<?> loadAndInitializeInvokerClass(byte[] classBytes, List<Object> classData) {
 321         Class<?> invokerClass = LOOKUP.defineClassWithNoCheck(classBytes, WEAK_HIDDEN_NESTMATE, classData);
 322         UNSAFE.ensureClassInitialized(invokerClass);  // Make sure the class is initialized; VM might complain.
 323         return invokerClass;
 324     }
 325 
 326 
 327     private static MemberName resolveInvokerMember(Class<?> invokerClass, String name, MethodType type) {
 328         MemberName member = new MemberName(invokerClass, name, type, REF_invokeStatic);
 329         try {
 330             member = MEMBERNAME_FACTORY.resolveOrFail(REF_invokeStatic, member, HOST_CLASS, ReflectiveOperationException.class);
 331         } catch (ReflectiveOperationException e) {
 332             throw newInternalError(e);
 333         }
 334         return member;
 335     }
 336 
 337     /**
 338      * Set up class file generation.
 339      */
 340     private ClassWriter classFilePrologue() {
 341         final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 342         ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 343         setClassWriter(cw);
 344         cw.visit(Opcodes.V1_8, NOT_ACC_PUBLIC + Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
 345                 CLASS_PREFIX + className, null, INVOKER_SUPER_NAME, null);
 346         cw.visitSource(SOURCE_PREFIX + className, null);
 347         return cw;
 348     }
 349 
 350     private void methodPrologue() {
 351         String invokerDesc = invokerType.toMethodDescriptorString();
 352         mv = cw.visitMethod(Opcodes.ACC_STATIC, invokerName, invokerDesc, null, null);
 353     }
 354 
 355     /**
 356      * Tear down class file generation.
 357      */
 358     private void methodEpilogue() {
 359         mv.visitMaxs(0, 0);
 360         mv.visitEnd();
 361     }
 362 
 363     private String className() {
 364         return CLASS_PREFIX + className;
 365     }
 366 
 367     private void clinit() {
 368         clinit(cw, className(), classData);
 369     }
 370 
 371     static void clinit(ClassWriter cw, String className, List<ClassData> classData) {
 372         if (classData.isEmpty())
 373             return;
 374 
 375         for (ClassData p : classData) {
 376             // add the static field
 377             FieldVisitor fv = cw.visitField(Opcodes.ACC_STATIC|Opcodes.ACC_FINAL, p.name, p.desc, null, null);
 378             fv.visitEnd();
 379         }
 380 
 381         MethodVisitor mv = cw.visitMethod(Opcodes.ACC_STATIC, "<clinit>", "()V", null, null);
 382         mv.visitCode();
 383         mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/invoke/MethodHandles",
 384                            "lookup", "()Ljava/lang/invoke/MethodHandles$Lookup;", false);
 385         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup",
 386                            "classData", "()Ljava/lang/Object;", false);
 387         // we should optimize one single element case that does not need to create a List
 388         mv.visitTypeInsn(Opcodes.CHECKCAST, "java/util/List");
 389         mv.visitVarInsn(Opcodes.ASTORE, 0);
 390         int index = 0;
 391         for (ClassData p : classData) {
 392             // initialize the static field
 393             mv.visitVarInsn(Opcodes.ALOAD, 0);
 394             emitIconstInsn(mv, index++);
 395             mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, "java/util/List",
 396                                "get", "(I)Ljava/lang/Object;", true);
 397             mv.visitTypeInsn(Opcodes.CHECKCAST, p.desc.substring(1, p.desc.length()-1));
 398             mv.visitFieldInsn(Opcodes.PUTSTATIC, className, p.name, p.desc);
 399         }
 400         mv.visitInsn(Opcodes.RETURN);
 401         mv.visitMaxs(2, 1);
 402         mv.visitEnd();
 403     }
 404 
 405     /*
 406      * Low-level emit helpers.
 407      */
 408     private void emitConst(Object con) {
 409         if (con == null) {
 410             mv.visitInsn(Opcodes.ACONST_NULL);
 411             return;
 412         }
 413         if (con instanceof Integer) {
 414             emitIconstInsn((int) con);
 415             return;
 416         }
 417         if (con instanceof Byte) {
 418             emitIconstInsn((byte)con);
 419             return;
 420         }
 421         if (con instanceof Short) {
 422             emitIconstInsn((short)con);
 423             return;
 424         }


 457             short sx = (short)x;
 458             if (x == sx) {
 459                 if (sx >= 0 && sx <= 1) {
 460                     mv.visitInsn(Opcodes.DCONST_0 + (int) sx);
 461                 } else {
 462                     emitIconstInsn((int) x);
 463                     mv.visitInsn(Opcodes.I2D);
 464                 }
 465                 return;
 466             }
 467         }
 468         if (con instanceof Boolean) {
 469             emitIconstInsn((boolean) con ? 1 : 0);
 470             return;
 471         }
 472         // fall through:
 473         mv.visitLdcInsn(con);
 474     }
 475 
 476     private void emitIconstInsn(final int cst) {
 477         emitIconstInsn(mv, cst);
 478     }
 479 
 480     private static void emitIconstInsn(MethodVisitor mv, int cst) {
 481         if (cst >= -1 && cst <= 5) {
 482             mv.visitInsn(Opcodes.ICONST_0 + cst);
 483         } else if (cst >= Byte.MIN_VALUE && cst <= Byte.MAX_VALUE) {
 484             mv.visitIntInsn(Opcodes.BIPUSH, cst);
 485         } else if (cst >= Short.MIN_VALUE && cst <= Short.MAX_VALUE) {
 486             mv.visitIntInsn(Opcodes.SIPUSH, cst);
 487         } else {
 488             mv.visitLdcInsn(cst);
 489         }
 490     }
 491 
 492     /*
 493      * NOTE: These load/store methods use the localsMap to find the correct index!
 494      */
 495     private void emitLoadInsn(BasicType type, int index) {
 496         int opcode = loadInsnOpcode(type);
 497         mv.visitVarInsn(opcode, localsMap[index]);
 498     }
 499 
 500     private int loadInsnOpcode(BasicType type) throws InternalError {


 630         }
 631         return false;
 632     }
 633 
 634     private void emitReferenceCast(Class<?> cls, Object arg) {
 635         Name writeBack = null;  // local to write back result
 636         if (arg instanceof Name) {
 637             Name n = (Name) arg;
 638             if (lambdaForm.useCount(n) > 1) {
 639                 // This guy gets used more than once.
 640                 writeBack = n;
 641                 if (assertStaticType(cls, n)) {
 642                     return; // this cast was already performed
 643                 }
 644             }
 645         }
 646         if (isStaticallyNameable(cls)) {
 647             String sig = getInternalName(cls);
 648             mv.visitTypeInsn(Opcodes.CHECKCAST, sig);
 649         } else {
 650             mv.visitFieldInsn(Opcodes.GETSTATIC, className(), classData(cls), "Ljava/lang/Class;");

 651             mv.visitInsn(Opcodes.SWAP);
 652             mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, CLS, "cast", LL_SIG, false);
 653             if (Object[].class.isAssignableFrom(cls))
 654                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJARY);
 655             else if (PROFILE_LEVEL > 0)
 656                 mv.visitTypeInsn(Opcodes.CHECKCAST, OBJ);
 657         }
 658         if (writeBack != null) {
 659             mv.visitInsn(Opcodes.DUP);
 660             emitAstoreInsn(writeBack.index());
 661         }
 662     }
 663 
 664     /**
 665      * Emits an actual return instruction conforming to the given return type.
 666      */
 667     private void emitReturnInsn(BasicType type) {
 668         int opcode;
 669         switch (type) {
 670         case I_TYPE:  opcode = Opcodes.IRETURN;  break;


 746             case PUT_DOUBLE:                // fall-through
 747             case DIRECT_NEW_INVOKE_SPECIAL: // fall-through
 748             case DIRECT_INVOKE_INTERFACE:   // fall-through
 749             case DIRECT_INVOKE_SPECIAL:     // fall-through
 750             case DIRECT_INVOKE_SPECIAL_IFC: // fall-through
 751             case DIRECT_INVOKE_STATIC:      // fall-through
 752             case DIRECT_INVOKE_STATIC_INIT: // fall-through
 753             case DIRECT_INVOKE_VIRTUAL:     return resolveFrom(name, invokerType, DirectMethodHandle.Holder.class);
 754         }
 755         return null;
 756     }
 757 
 758     /**
 759      * Generate customized bytecode for a given LambdaForm.
 760      */
 761     static MemberName generateCustomizedCode(LambdaForm form, MethodType invokerType) {
 762         MemberName pregenerated = lookupPregenerated(form, invokerType);
 763         if (pregenerated != null)  return pregenerated; // pre-generated bytecode
 764 
 765         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("MH", form, invokerType);
 766         return g.loadMethod(g.generateCustomizedCodeBytes(), g.classDataValues());
 767     }
 768 
 769     /** Generates code to check that actual receiver and LambdaForm matches */
 770     private boolean checkActualReceiver() {
 771         // Expects MethodHandle on the stack and actual receiver MethodHandle in slot #0
 772         mv.visitInsn(Opcodes.DUP);
 773         mv.visitVarInsn(Opcodes.ALOAD, localsMap[0]);
 774         mv.visitMethodInsn(Opcodes.INVOKESTATIC, MHI, "assertSame", LLV_SIG, false);
 775         return true;
 776     }
 777 
 778     static String className(String cn) {
 779         assert checkClassName(cn): "Class not found: " + cn;
 780         return cn;
 781     }
 782 
 783     static boolean checkClassName(String cn) {
 784         Type tp = Type.getType(cn);
 785         // additional sanity so only valid "L;" descriptors work
 786         if (tp.getSort() != Type.OBJECT) {


 789         try {
 790             Class<?> c = Class.forName(tp.getClassName(), false, null);
 791             return true;
 792         } catch (ClassNotFoundException e) {
 793             return false;
 794         }
 795     }
 796 
 797     static final String      DONTINLINE_SIG = className("Ljdk/internal/vm/annotation/DontInline;");
 798     static final String     FORCEINLINE_SIG = className("Ljdk/internal/vm/annotation/ForceInline;");
 799     static final String          HIDDEN_SIG = className("Ljdk/internal/vm/annotation/Hidden;");
 800     static final String INJECTEDPROFILE_SIG = className("Ljava/lang/invoke/InjectedProfile;");
 801     static final String     LF_COMPILED_SIG = className("Ljava/lang/invoke/LambdaForm$Compiled;");
 802 
 803     /**
 804      * Generate an invoker method for the passed {@link LambdaForm}.
 805      */
 806     private byte[] generateCustomizedCodeBytes() {
 807         classFilePrologue();
 808         addMethod();
 809         clinit();
 810         bogusMethod(lambdaForm);
 811 
 812         final byte[] classFile = toByteArray();
 813         maybeDump(classFile);
 814         return classFile;
 815     }
 816 
 817     void setClassWriter(ClassWriter cw) {
 818         this.cw = cw;
 819     }
 820 
 821     void addMethod() {
 822         methodPrologue();
 823 
 824         // Suppress this method in backtraces displayed to the user.
 825         mv.visitAnnotation(HIDDEN_SIG, true);
 826 
 827         // Mark this method as a compiled LambdaForm
 828         mv.visitAnnotation(LF_COMPILED_SIG, true);
 829 
 830         if (lambdaForm.forceInline) {
 831             // Force inlining of this invoker method.
 832             mv.visitAnnotation(FORCEINLINE_SIG, true);
 833         } else {
 834             mv.visitAnnotation(DONTINLINE_SIG, true);
 835         }
 836 
 837         classData(lambdaForm); // keep LambdaForm instance & its compiled form lifetime tightly coupled.
 838 
 839         if (lambdaForm.customized != null) {
 840             // Since LambdaForm is customized for a particular MethodHandle, it's safe to substitute
 841             // receiver MethodHandle (at slot #0) with an embedded constant and use it instead.
 842             // It enables more efficient code generation in some situations, since embedded constants
 843             // are compile-time constants for JIT compiler.
 844             mv.visitFieldInsn(Opcodes.GETSTATIC, className(), classData(lambdaForm.customized), MH_SIG);
 845             mv.visitTypeInsn(Opcodes.CHECKCAST, MH);
 846             assert(checkActualReceiver()); // expects MethodHandle on top of the stack
 847             mv.visitVarInsn(Opcodes.ASTORE, localsMap[0]);
 848         }
 849 
 850         // iterate over the form's names, generating bytecode instructions for each
 851         // start iterating at the first name following the arguments
 852         Name onStack = null;
 853         for (int i = lambdaForm.arity; i < lambdaForm.names.length; i++) {
 854             Name name = lambdaForm.names[i];
 855 
 856             emitStoreResult(onStack);
 857             onStack = name;  // unless otherwise modified below
 858             MethodHandleImpl.Intrinsic intr = name.function.intrinsicName();
 859             switch (intr) {
 860                 case SELECT_ALTERNATIVE:
 861                     assert lambdaForm.isSelectAlternative(i);
 862                     if (PROFILE_GWT) {
 863                         assert(name.arguments[0] instanceof Name &&
 864                                 ((Name)name.arguments[0]).refersTo(MethodHandleImpl.class, "profileBoolean"));


 954         assert arrayOpcode == Opcodes.AALOAD || arrayOpcode == Opcodes.AASTORE || arrayOpcode == Opcodes.ARRAYLENGTH;
 955         Class<?> elementType = name.function.methodType().parameterType(0).getComponentType();
 956         assert elementType != null;
 957         emitPushArguments(name, 0);
 958         if (arrayOpcode != Opcodes.ARRAYLENGTH && elementType.isPrimitive()) {
 959             Wrapper w = Wrapper.forPrimitiveType(elementType);
 960             arrayOpcode = arrayInsnOpcode(arrayTypeCode(w), arrayOpcode);
 961         }
 962         mv.visitInsn(arrayOpcode);
 963     }
 964 
 965     /**
 966      * Emit an invoke for the given name.
 967      */
 968     void emitInvoke(Name name) {
 969         assert(!name.isLinkerMethodInvoke());  // should use the static path for these
 970         if (true) {
 971             // push receiver
 972             MethodHandle target = name.function.resolvedHandle();
 973             assert(target != null) : name.exprString();
 974             mv.visitFieldInsn(Opcodes.GETSTATIC, className(), classData(target), MH_SIG);
 975             emitReferenceCast(MethodHandle.class, target);
 976         } else {
 977             // load receiver
 978             emitAloadInsn(0);
 979             emitReferenceCast(MethodHandle.class, null);
 980             mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", LF_SIG);
 981             mv.visitFieldInsn(Opcodes.GETFIELD, LF, "names", LFN_SIG);
 982             // TODO more to come
 983         }
 984 
 985         // push arguments
 986         emitPushArguments(name, 0);
 987 
 988         // invocation
 989         MethodType type = name.function.methodType();
 990         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", type.basicType().toMethodDescriptorString(), false);
 991     }
 992 
 993     private static Class<?>[] STATICALLY_INVOCABLE_PACKAGES = {
 994         // Sample classes from each package we are willing to bind to statically:


1010     static boolean isStaticallyInvocable(Name name) {
1011         return isStaticallyInvocable(name.function.member());
1012     }
1013 
1014     static boolean isStaticallyInvocable(MemberName member) {
1015         if (member == null)  return false;
1016         if (member.isConstructor())  return false;
1017         Class<?> cls = member.getDeclaringClass();
1018         // Fast-path non-private members declared by MethodHandles, which is a common
1019         // case
1020         if (MethodHandle.class.isAssignableFrom(cls) && !member.isPrivate()) {
1021             assert(isStaticallyInvocableType(member.getMethodOrFieldType()));
1022             return true;
1023         }
1024         if (cls.isArray() || cls.isPrimitive())
1025             return false;  // FIXME
1026         if (cls.isAnonymousClass() || cls.isLocalClass())
1027             return false;  // inner class of some sort
1028         if (cls.getClassLoader() != MethodHandle.class.getClassLoader())
1029             return false;  // not on BCP
1030         if (cls.isHidden())
1031             return false;
1032         if (!isStaticallyInvocableType(member.getMethodOrFieldType()))
1033             return false;
1034         if (!member.isPrivate() && VerifyAccess.isSamePackage(MethodHandle.class, cls))
1035             return true;   // in java.lang.invoke package
1036         if (member.isPublic() && isStaticallyNameable(cls))
1037             return true;
1038         return false;
1039     }
1040 
1041     private static boolean isStaticallyInvocableType(MethodType mtype) {
1042         if (!isStaticallyNameable(mtype.returnType()))
1043             return false;
1044         for (Class<?> ptype : mtype.parameterArray())
1045             if (!isStaticallyNameable(ptype))
1046                 return false;
1047         return true;
1048     }
1049 
1050     static boolean isStaticallyNameable(Class<?> cls) {
1051         if (cls == Object.class)
1052             return true;
1053         if (MethodHandle.class.isAssignableFrom(cls)) {
1054             assert(!cls.isHidden());
1055             return true;
1056         }
1057         while (cls.isArray())
1058             cls = cls.getComponentType();
1059         if (cls.isPrimitive())
1060             return true;  // int[].class, for example
1061         if (cls.isHidden())
1062             return false;
1063         // could use VerifyAccess.isClassAccessible but the following is a safe approximation
1064         if (cls.getClassLoader() != Object.class.getClassLoader())
1065             return false;
1066         if (VerifyAccess.isSamePackage(MethodHandle.class, cls))
1067             return true;
1068         if (!Modifier.isPublic(cls.getModifiers()))
1069             return false;
1070         for (Class<?> pkgcls : STATICALLY_INVOCABLE_PACKAGES) {
1071             if (VerifyAccess.isSamePackage(pkgcls, cls))
1072                 return true;
1073         }
1074         return false;
1075     }
1076 
1077     void emitStaticInvoke(Name name) {
1078         emitStaticInvoke(name.function.member(), name);
1079     }
1080 
1081     /**


1113             Class<?> rtype = member.getInvocationType().returnType();
1114             assert(!rtype.isPrimitive());
1115             if (rtype != Object.class && !rtype.isInterface()) {
1116                 assertStaticType(rtype, name);
1117             }
1118         }
1119     }
1120 
1121     void emitNewArray(Name name) throws InternalError {
1122         Class<?> rtype = name.function.methodType().returnType();
1123         if (name.arguments.length == 0) {
1124             // The array will be a constant.
1125             Object emptyArray;
1126             try {
1127                 emptyArray = name.function.resolvedHandle().invoke();
1128             } catch (Throwable ex) {
1129                 throw uncaughtException(ex);
1130             }
1131             assert(java.lang.reflect.Array.getLength(emptyArray) == 0);
1132             assert(emptyArray.getClass() == rtype);  // exact typing
1133             mv.visitFieldInsn(Opcodes.GETSTATIC, className(), classData(emptyArray), "Ljava/lang/Object;");
1134             emitReferenceCast(rtype, emptyArray);
1135             return;
1136         }
1137         Class<?> arrayElementType = rtype.getComponentType();
1138         assert(arrayElementType != null);
1139         emitIconstInsn(name.arguments.length);
1140         int xas = Opcodes.AASTORE;
1141         if (!arrayElementType.isPrimitive()) {
1142             mv.visitTypeInsn(Opcodes.ANEWARRAY, getInternalName(arrayElementType));
1143         } else {
1144             byte tc = arrayTypeCode(Wrapper.forPrimitiveType(arrayElementType));
1145             xas = arrayInsnOpcode(tc, xas);
1146             mv.visitIntInsn(Opcodes.NEWARRAY, tc);
1147         }
1148         // store arguments
1149         for (int i = 0; i < name.arguments.length; i++) {
1150             mv.visitInsn(Opcodes.DUP);
1151             emitIconstInsn(i);
1152             emitPushArgument(name, i);
1153             mv.visitInsn(xas);


1654     }
1655 
1656     private void emitPushArgument(Name name, int paramIndex) {
1657         Object arg = name.arguments[paramIndex];
1658         Class<?> ptype = name.function.methodType().parameterType(paramIndex);
1659         emitPushArgument(ptype, arg);
1660     }
1661 
1662     private void emitPushArgument(Class<?> ptype, Object arg) {
1663         BasicType bptype = basicType(ptype);
1664         if (arg instanceof Name) {
1665             Name n = (Name) arg;
1666             emitLoadInsn(n.type, n.index());
1667             emitImplicitConversion(n.type, ptype, n);
1668         } else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
1669             emitConst(arg);
1670         } else {
1671             if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
1672                 emitConst(arg);
1673             } else {
1674                 mv.visitFieldInsn(Opcodes.GETSTATIC, className(), classData(arg), "Ljava/lang/Object;");
1675                 emitImplicitConversion(L_TYPE, ptype, arg);
1676             }
1677         }
1678     }
1679 
1680     /**
1681      * Store the name to its local, if necessary.
1682      */
1683     private void emitStoreResult(Name name) {
1684         if (name != null && name.type != V_TYPE) {
1685             // non-void: actually assign
1686             emitStoreInsn(name.type, name.index());
1687         }
1688     }
1689 
1690     /**
1691      * Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
1692      */
1693     private void emitReturn(Name onStack) {
1694         // return statement


1801     }
1802 
1803     private void emitX2I(Wrapper type) {
1804         switch (type) {
1805         case LONG:    mv.visitInsn(Opcodes.L2I);  break;
1806         case FLOAT:   mv.visitInsn(Opcodes.F2I);  break;
1807         case DOUBLE:  mv.visitInsn(Opcodes.D2I);  break;
1808         default:      throw new InternalError("unknown type: " + type);
1809         }
1810     }
1811 
1812     /**
1813      * Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
1814      */
1815     static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) {
1816         assert(isValidSignature(basicTypeSignature(mt)));
1817         String name = "interpret_"+basicTypeChar(mt.returnType());
1818         MethodType type = mt;  // includes leading argument
1819         type = type.changeParameterType(0, MethodHandle.class);
1820         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
1821         return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes(), g.classDataValues());
1822     }
1823 
1824     private byte[] generateLambdaFormInterpreterEntryPointBytes() {
1825         classFilePrologue();
1826         methodPrologue();
1827 
1828         // Suppress this method in backtraces displayed to the user.
1829         mv.visitAnnotation(HIDDEN_SIG, true);
1830 
1831         // Don't inline the interpreter entry.
1832         mv.visitAnnotation(DONTINLINE_SIG, true);
1833 
1834         // create parameter array
1835         emitIconstInsn(invokerType.parameterCount());
1836         mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
1837 
1838         // fill parameter array
1839         for (int i = 0; i < invokerType.parameterCount(); i++) {
1840             Class<?> ptype = invokerType.parameterType(i);
1841             mv.visitInsn(Opcodes.DUP);


1846                 emitBoxing(Wrapper.forPrimitiveType(ptype));
1847             }
1848             mv.visitInsn(Opcodes.AASTORE);
1849         }
1850         // invoke
1851         emitAloadInsn(0);
1852         mv.visitFieldInsn(Opcodes.GETFIELD, MH, "form", "Ljava/lang/invoke/LambdaForm;");
1853         mv.visitInsn(Opcodes.SWAP);  // swap form and array; avoid local variable
1854         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, LF, "interpretWithArguments", "([Ljava/lang/Object;)Ljava/lang/Object;", false);
1855 
1856         // maybe unbox
1857         Class<?> rtype = invokerType.returnType();
1858         if (rtype.isPrimitive() && rtype != void.class) {
1859             emitUnboxing(Wrapper.forPrimitiveType(rtype));
1860         }
1861 
1862         // return statement
1863         emitReturnInsn(basicType(rtype));
1864 
1865         methodEpilogue();
1866         clinit();
1867         bogusMethod(invokerType);
1868 
1869         final byte[] classFile = cw.toByteArray();
1870         maybeDump(classFile);
1871         return classFile;
1872     }
1873 
1874     /**
1875      * Generate bytecode for a NamedFunction invoker.
1876      */
1877     static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
1878         MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
1879         String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
1880         InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
1881         return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm), g.classDataValues());
1882     }
1883 
1884     private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
1885         MethodType dstType = typeForm.erasedType();
1886         classFilePrologue();
1887         methodPrologue();
1888 
1889         // Suppress this method in backtraces displayed to the user.
1890         mv.visitAnnotation(HIDDEN_SIG, true);
1891 
1892         // Force inlining of this invoker method.
1893         mv.visitAnnotation(FORCEINLINE_SIG, true);
1894 
1895         // Load receiver
1896         emitAloadInsn(0);
1897 
1898         // Load arguments from array
1899         for (int i = 0; i < dstType.parameterCount(); i++) {
1900             emitAloadInsn(1);
1901             emitIconstInsn(i);


1915         String targetDesc = dstType.basicType().toMethodDescriptorString();
1916         mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, MH, "invokeBasic", targetDesc, false);
1917 
1918         // Box primitive types
1919         Class<?> rtype = dstType.returnType();
1920         if (rtype != void.class && rtype.isPrimitive()) {
1921             Wrapper srcWrapper = Wrapper.forBasicType(rtype);
1922             Wrapper dstWrapper = srcWrapper.isSubwordOrInt() ? Wrapper.INT : srcWrapper;  // widen subword to int
1923             // boolean casts not allowed
1924             emitPrimCast(srcWrapper, dstWrapper);
1925             emitBoxing(dstWrapper);
1926         }
1927 
1928         // If the return type is void we return a null reference.
1929         if (rtype == void.class) {
1930             mv.visitInsn(Opcodes.ACONST_NULL);
1931         }
1932         emitReturnInsn(L_TYPE);  // NOTE: NamedFunction invokers always return a reference value.
1933 
1934         methodEpilogue();
1935         clinit();
1936         bogusMethod(dstType);
1937 
1938         final byte[] classFile = cw.toByteArray();
1939         maybeDump(classFile);
1940         return classFile;
1941     }
1942 
1943     /**
1944      * Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
1945      * for debugging purposes.
1946      */
1947     private void bogusMethod(Object os) {
1948         if (DUMP_CLASS_FILES) {
1949             mv = cw.visitMethod(Opcodes.ACC_STATIC, "dummy", "()V", null, null);
1950             mv.visitLdcInsn(os.toString());
1951             mv.visitInsn(Opcodes.POP);
1952             mv.visitInsn(Opcodes.RETURN);
1953             mv.visitMaxs(0, 0);
1954             mv.visitEnd();
1955         }
< prev index next >