/* * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.lang.invoke; import sun.invoke.util.VerifyAccess; import sun.invoke.util.VerifyType; import sun.invoke.util.Wrapper; import java.lang.classfile.*; import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute; import java.lang.classfile.attribute.SourceFileAttribute; import java.lang.classfile.constantpool.ClassEntry; import java.lang.classfile.constantpool.ConstantPoolBuilder; import java.lang.classfile.constantpool.FieldRefEntry; import java.lang.classfile.instruction.SwitchCase; import java.lang.constant.ClassDesc; import java.lang.constant.ConstantDesc; import java.lang.constant.MethodTypeDesc; import java.lang.invoke.LambdaForm.BasicType; import java.lang.invoke.LambdaForm.Name; import java.lang.invoke.LambdaForm.NamedFunction; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import jdk.internal.constant.MethodTypeDescImpl; import jdk.internal.constant.ReferenceClassDescImpl; import static java.lang.classfile.ClassFile.*; import static java.lang.constant.ConstantDescs.*; import static java.lang.invoke.LambdaForm.*; import static java.lang.invoke.LambdaForm.BasicType.*; import static java.lang.invoke.MethodHandleNatives.Constants.*; import static java.lang.invoke.MethodHandleStatics.*; import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; import static jdk.internal.constant.ConstantUtils.concat; import static jdk.internal.constant.ConstantUtils.validateInternalClassName; /** * Code generation backend for LambdaForm. *
* @author John Rose, JSR 292 EG
*/
class InvokerBytecodeGenerator {
/** Define class names for convenience. */
private static final ClassDesc CD_CasesHolder = ReferenceClassDescImpl.ofValidated("Ljava/lang/invoke/MethodHandleImpl$CasesHolder;");
private static final ClassDesc CD_DirectMethodHandle = ReferenceClassDescImpl.ofValidated("Ljava/lang/invoke/DirectMethodHandle;");
private static final ClassDesc CD_MemberName = ReferenceClassDescImpl.ofValidated("Ljava/lang/invoke/MemberName;");
private static final ClassDesc CD_MethodHandleImpl = ReferenceClassDescImpl.ofValidated("Ljava/lang/invoke/MethodHandleImpl;");
private static final ClassDesc CD_LambdaForm = ReferenceClassDescImpl.ofValidated("Ljava/lang/invoke/LambdaForm;");
private static final ClassDesc CD_LambdaForm_Name = ReferenceClassDescImpl.ofValidated("Ljava/lang/invoke/LambdaForm$Name;");
private static final ClassDesc CD_LoopClauses = ReferenceClassDescImpl.ofValidated("Ljava/lang/invoke/MethodHandleImpl$LoopClauses;");
private static final ClassDesc CD_Object_array = ReferenceClassDescImpl.ofValidated("[Ljava/lang/Object;");
private static final ClassDesc CD_MethodHandle_array = ReferenceClassDescImpl.ofValidated("[Ljava/lang/invoke/MethodHandle;");
private static final ClassDesc CD_MethodHandle_array2 = ReferenceClassDescImpl.ofValidated("[[Ljava/lang/invoke/MethodHandle;");
private static final MethodTypeDesc MTD_boolean_Object = MethodTypeDescImpl.ofValidated(CD_boolean, CD_Object);
private static final MethodTypeDesc MTD_Object_int = MethodTypeDescImpl.ofValidated(CD_Object, CD_int);
private static final MethodTypeDesc MTD_Object_Class = MethodTypeDescImpl.ofValidated(CD_Object, CD_Class);
private static final MethodTypeDesc MTD_Object_Object = MethodTypeDescImpl.ofValidated(CD_Object, CD_Object);
private static final String CLASS_PREFIX = "java/lang/invoke/LambdaForm$";
private static final String SOURCE_PREFIX = "LambdaForm$";
/** Name of its super class*/
static final ClassDesc INVOKER_SUPER_DESC = CD_Object;
/** Name of new class */
private final String name;
private final String className;
private final ConstantPoolBuilder pool = ConstantPoolBuilder.of();
private final ClassEntry classEntry;
private final LambdaForm lambdaForm;
private final String invokerName;
private final MethodType invokerType;
/** Info about local variables in compiled lambda form */
private int[] localsMap; // index
private Class>[] localClasses; // type
private final List
* The pattern looks like (Cf. MethodHandleImpl.makeTryFinally):
*
* It is compiled into bytecode equivalent to the following code:
*
* Specifically, the bytecode will have the following form (the stack effects are given for the beginnings of
* blocks, and for the situations after executing the given instruction - the code will have a slightly different
* shape if the return type is {@code void}):
*
* The pattern looks like (Cf. MethodHandleImpl.loop):
*
* It is compiled into bytecode equivalent to the code seen in {@link MethodHandleImpl#loop(BasicType[],
* MethodHandleImpl.LoopClauses, Object...)}, with the difference that no arrays
* will be used for local state storage. Instead, the local state will be mapped to actual stack slots.
*
* Bytecode generation applies an unrolling scheme to enable better bytecode generation regarding local state type
* handling. The generated bytecode will have the following form ({@code void} types are ignored for convenience).
* Assume there are {@code C} clauses in the loop.
*
* The {@code INIT_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has
* the following shape. Assume slot {@code vx} is used to hold the state for clause {@code x}.
*
* The {@code LOOP_SEQ_x} sequence for clause {@code x} (with {@code x} ranging from {@code 0} to {@code C-1}) has
* the following shape. Again, assume slot {@code vx} is used to hold the state for clause {@code x}.
*
*/
private Name emitSelectAlternative(CodeBuilder cob, Name selectAlternativeName, Name invokeBasicName) {
assert isStaticallyInvocable(invokeBasicName);
Name receiver = (Name) invokeBasicName.arguments[0];
Label L_fallback = cob.newLabel();
Label L_done = cob.newLabel();
// load test result
emitPushArgument(cob, selectAlternativeName, 0);
// if_icmpne L_fallback
cob.ifeq(L_fallback);
// invoke selectAlternativeName.arguments[1]
Class>[] preForkClasses = localClasses.clone();
emitPushArgument(cob, selectAlternativeName, 1); // get 2nd argument of selectAlternative
emitStoreInsn(cob, TypeKind.REFERENCE, receiver.index()); // store the MH in the receiver slot
emitStaticInvoke(cob, invokeBasicName);
// goto L_done
cob.goto_w(L_done)
// L_fallback:
.labelBinding(L_fallback);
// invoke selectAlternativeName.arguments[2]
System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
emitPushArgument(cob, selectAlternativeName, 2); // get 3rd argument of selectAlternative
emitStoreInsn(cob, TypeKind.REFERENCE, receiver.index()); // store the MH in the receiver slot
emitStaticInvoke(cob, invokeBasicName);
// L_done:
cob.labelBinding(L_done);
// for now do not bother to merge typestate; just reset to the dominator state
System.arraycopy(preForkClasses, 0, localClasses, 0, preForkClasses.length);
return invokeBasicName; // return what's on stack
}
/**
* Emit bytecode for the guardWithCatch idiom.
*
* The pattern looks like (Cf. MethodHandleImpl.makeGuardWithCatch):
* {@code
* Lambda(a0:L,a1:I)=>{
* t2:I=foo.test(a1:I);
* t3:L=MethodHandleImpl.selectAlternative(t2:I,(MethodHandle(int)int),(MethodHandle(int)int));
* t4:I=MethodHandle.invokeBasic(t3:L,a1:I);t4:I}
* }
*
* It is compiled into bytecode equivalent of the following code:
* {@code
* guardWithCatch=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L,a6:L,a7:L)=>{
* t8:L=MethodHandle.invokeBasic(a4:L,a6:L,a7:L);
* t9:L=MethodHandleImpl.guardWithCatch(a1:L,a2:L,a3:L,t8:L);
* t10:I=MethodHandle.invokeBasic(a5:L,t9:L);t10:I}
* }
*/
private Name emitGuardWithCatch(CodeBuilder cob, int pos) {
Name args = lambdaForm.names[pos];
Name invoker = lambdaForm.names[pos+1];
Name result = lambdaForm.names[pos+2];
Label L_startBlock = cob.newLabel();
Label L_endBlock = cob.newLabel();
Label L_handler = cob.newLabel();
Label L_done = cob.newLabel();
Class> returnType = result.function.resolvedHandle().type().returnType();
MethodType type = args.function.resolvedHandle().type()
.dropParameterTypes(0,1)
.changeReturnType(returnType);
cob.exceptionCatch(L_startBlock, L_endBlock, L_handler, CD_Throwable)
// Normal case
.labelBinding(L_startBlock);
// load target
emitPushArgument(cob, invoker, 0);
emitPushArguments(cob, args, 1); // skip 1st argument: method handle
cob.invokevirtual(CD_MethodHandle, "invokeBasic", methodDesc(type.basicType()))
.labelBinding(L_endBlock)
.goto_w(L_done)
// Exceptional case
.labelBinding(L_handler)
// Check exception's type
.dup();
// load exception class
emitPushArgument(cob, invoker, 1);
cob.swap()
.invokevirtual(CD_Class, "isInstance", MTD_boolean_Object);
Label L_rethrow = cob.newLabel();
cob.ifeq(L_rethrow);
// Invoke catcher
// load catcher
emitPushArgument(cob, invoker, 2);
cob.swap();
emitPushArguments(cob, args, 1); // skip 1st argument: method handle
MethodType catcherType = type.insertParameterTypes(0, Throwable.class);
cob.invokevirtual(CD_MethodHandle, "invokeBasic", methodDesc(catcherType.basicType()))
.goto_w(L_done)
.labelBinding(L_rethrow)
.athrow()
.labelBinding(L_done);
return result;
}
/**
* Emit bytecode for the tryFinally idiom.
* {@code
* try {
* return a1.invokeBasic(a6, a7);
* } catch (Throwable e) {
* if (!a2.isInstance(e)) throw e;
* return a3.invokeBasic(ex, a6, a7);
* }}
* {@code
* // a0: BMH
* // a1: target, a2: cleanup
* // a3: box, a4: unbox
* // a5 (and following): arguments
* tryFinally=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L,a5:L)=>{
* t6:L=MethodHandle.invokeBasic(a3:L,a5:L); // box the arguments into an Object[]
* t7:L=MethodHandleImpl.tryFinally(a1:L,a2:L,t6:L); // call the tryFinally executor
* t8:L=MethodHandle.invokeBasic(a4:L,t7:L);t8:L} // unbox the result; return the result
* }
* {@code
* Throwable t;
* Object r;
* try {
* r = a1.invokeBasic(a5);
* } catch (Throwable thrown) {
* t = thrown;
* throw t;
* } finally {
* r = a2.invokeBasic(t, r, a5);
* }
* return r;
* }
* * = depends on whether the return type takes up 2 stack slots.
*/
private Name emitTryFinally(CodeBuilder cob, int pos) {
Name args = lambdaForm.names[pos];
Name invoker = lambdaForm.names[pos+1];
Name result = lambdaForm.names[pos+2];
Label lFrom = cob.newLabel();
Label lTo = cob.newLabel();
Label lCatch = cob.newLabel();
Label lDone = cob.newLabel();
Class> returnType = result.function.resolvedHandle().type().returnType();
BasicType basicReturnType = BasicType.basicType(returnType);
boolean isNonVoid = returnType != void.class;
MethodType type = args.function.resolvedHandle().type()
.dropParameterTypes(0,1)
.changeReturnType(returnType);
MethodType cleanupType = type.insertParameterTypes(0, Throwable.class);
if (isNonVoid) {
cleanupType = cleanupType.insertParameterTypes(1, returnType);
}
MethodTypeDesc cleanupDesc = methodDesc(cleanupType.basicType());
// exception handler table
cob.exceptionCatch(lFrom, lTo, lCatch, CD_Throwable);
// TRY:
cob.labelBinding(lFrom);
emitPushArgument(cob, invoker, 0); // load target
emitPushArguments(cob, args, 1); // load args (skip 0: method handle)
cob.invokevirtual(CD_MethodHandle, "invokeBasic", methodDesc(type.basicType()))
.labelBinding(lTo);
// FINALLY_NORMAL:
int index = extendLocalsMap(new Class>[]{ returnType });
if (isNonVoid) {
emitStoreInsn(cob, basicReturnType.basicTypeKind(), index);
}
emitPushArgument(cob, invoker, 1); // load cleanup
cob.aconst_null();
if (isNonVoid) {
emitLoadInsn(cob, basicReturnType.basicTypeKind(), index);
}
emitPushArguments(cob, args, 1); // load args (skip 0: method handle)
cob.invokevirtual(CD_MethodHandle, "invokeBasic", cleanupDesc)
.goto_w(lDone)
// CATCH:
.labelBinding(lCatch)
.dup();
// FINALLY_EXCEPTIONAL:
emitPushArgument(cob, invoker, 1); // load cleanup
cob.swap();
if (isNonVoid) {
emitZero(cob, BasicType.basicType(returnType)); // load default for result
}
emitPushArguments(cob, args, 1); // load args (skip 0: method handle)
cob.invokevirtual(CD_MethodHandle, "invokeBasic", cleanupDesc);
if (isNonVoid) {
emitPopInsn(cob, basicReturnType);
}
cob.athrow()
// DONE:
.labelBinding(lDone);
return result;
}
private void emitPopInsn(CodeBuilder cob, BasicType type) {
switch (type) {
case I_TYPE, F_TYPE, L_TYPE -> cob.pop();
case J_TYPE, D_TYPE -> cob.pop2();
default -> throw new InternalError("unknown type: " + type);
}
}
private Name emitTableSwitch(CodeBuilder cob, int pos, int numCases) {
Name args = lambdaForm.names[pos];
Name invoker = lambdaForm.names[pos + 1];
Name result = lambdaForm.names[pos + 2];
Class> returnType = result.function.resolvedHandle().type().returnType();
MethodType caseType = args.function.resolvedHandle().type()
.dropParameterTypes(0, 1) // drop collector
.changeReturnType(returnType);
MethodTypeDesc caseDescriptor = methodDesc(caseType.basicType());
emitPushArgument(cob, invoker, 2); // push cases
cob.getfield(CD_CasesHolder, "cases", CD_MethodHandle_array);
int casesLocal = extendLocalsMap(new Class>[] { MethodHandle[].class });
emitStoreInsn(cob, TypeKind.REFERENCE, casesLocal);
Label endLabel = cob.newLabel();
Label defaultLabel = cob.newLabel();
List{@code
* TRY: (--)
* load target (-- target)
* load args (-- args... target)
* INVOKEVIRTUAL MethodHandle.invokeBasic (depends)
* FINALLY_NORMAL: (-- r_2nd* r)
* store returned value (--)
* load cleanup (-- cleanup)
* ACONST_NULL (-- t cleanup)
* load returned value (-- r_2nd* r t cleanup)
* load args (-- args... r_2nd* r t cleanup)
* INVOKEVIRTUAL MethodHandle.invokeBasic (-- r_2nd* r)
* GOTO DONE
* CATCH: (-- t)
* DUP (-- t t)
* FINALLY_EXCEPTIONAL: (-- t t)
* load cleanup (-- cleanup t t)
* SWAP (-- t cleanup t)
* load default for r (-- r_2nd* r t cleanup t)
* load args (-- args... r_2nd* r t cleanup t)
* INVOKEVIRTUAL MethodHandle.invokeBasic (-- r_2nd* r t)
* POP/POP2* (-- t)
* ATHROW
* DONE: (-- r)
* }
* {@code
* // a0: BMH
* // a1: LoopClauses (containing an array of arrays: inits, steps, preds, finis)
* // a2: box, a3: unbox
* // a4 (and following): arguments
* loop=Lambda(a0:L,a1:L,a2:L,a3:L,a4:L)=>{
* t5:L=MethodHandle.invokeBasic(a2:L,a4:L); // box the arguments into an Object[]
* t6:L=MethodHandleImpl.loop(bt:L,a1:L,t5:L); // call the loop executor (with supplied types in bt)
* t7:L=MethodHandle.invokeBasic(a3:L,t6:L);t7:L} // unbox the result; return the result
* }
* {@code
* PREINIT: ALOAD_1
* CHECKCAST LoopClauses
* GETFIELD LoopClauses.clauses
* ASTORE clauseDataIndex // place the clauses 2-dimensional array on the stack
* INIT: (INIT_SEQ for clause 1)
* ...
* (INIT_SEQ for clause C)
* LOOP: (LOOP_SEQ for clause 1)
* ...
* (LOOP_SEQ for clause C)
* GOTO LOOP
* DONE: ...
* }
* {@code
* INIT_SEQ_x: ALOAD clauseDataIndex
* ICONST_0
* AALOAD // load the inits array
* ICONST x
* AALOAD // load the init handle for clause x
* load args
* INVOKEVIRTUAL MethodHandle.invokeBasic
* store vx
* }
*/
private Name emitLoop(CodeBuilder cob, int pos) {
Name args = lambdaForm.names[pos];
Name invoker = lambdaForm.names[pos+1];
Name result = lambdaForm.names[pos+2];
// extract clause and loop-local state types
// find the type info in the loop invocation
BasicType[] loopClauseTypes = (BasicType[]) invoker.arguments[0];
Class>[] loopLocalStateTypes = Stream.of(loopClauseTypes)
.filter(bt -> bt != BasicType.V_TYPE)
.map(BasicType::basicTypeClass).toArray(Class>[]::new);
Class>[] localTypes = new Class>[loopLocalStateTypes.length + 1];
localTypes[0] = MethodHandleImpl.LoopClauses.class;
System.arraycopy(loopLocalStateTypes, 0, localTypes, 1, loopLocalStateTypes.length);
final int clauseDataIndex = extendLocalsMap(localTypes);
final int firstLoopStateIndex = clauseDataIndex + 1;
Class> returnType = result.function.resolvedHandle().type().returnType();
MethodType loopType = args.function.resolvedHandle().type()
.dropParameterTypes(0,1)
.changeReturnType(returnType);
MethodType loopHandleType = loopType.insertParameterTypes(0, loopLocalStateTypes);
MethodType predType = loopHandleType.changeReturnType(boolean.class);
MethodType finiType = loopHandleType;
final int nClauses = loopClauseTypes.length;
// indices to invoker arguments to load method handle arrays
final int inits = 1;
final int steps = 2;
final int preds = 3;
final int finis = 4;
Label lLoop = cob.newLabel();
Label lDone = cob.newLabel();
Label lNext;
// PREINIT:
emitPushArgument(cob, MethodHandleImpl.LoopClauses.class, invoker.arguments[1]);
cob.getfield(CD_LoopClauses, "clauses", CD_MethodHandle_array2);
emitStoreInsn(cob, TypeKind.REFERENCE, clauseDataIndex);
// INIT:
for (int c = 0, state = 0; c < nClauses; ++c) {
MethodType cInitType = loopType.changeReturnType(loopClauseTypes[c].basicTypeClass());
emitLoopHandleInvoke(cob, invoker, inits, c, args, false, cInitType, loopLocalStateTypes, clauseDataIndex,
firstLoopStateIndex);
if (cInitType.returnType() != void.class) {
emitStoreInsn(cob, BasicType.basicType(cInitType.returnType()).basicTypeKind(), firstLoopStateIndex + state);
++state;
}
}
// LOOP:
cob.labelBinding(lLoop);
for (int c = 0, state = 0; c < nClauses; ++c) {
lNext = cob.newLabel();
MethodType stepType = loopHandleType.changeReturnType(loopClauseTypes[c].basicTypeClass());
boolean isVoid = stepType.returnType() == void.class;
// invoke loop step
emitLoopHandleInvoke(cob, invoker, steps, c, args, true, stepType, loopLocalStateTypes, clauseDataIndex,
firstLoopStateIndex);
if (!isVoid) {
emitStoreInsn(cob, BasicType.basicType(stepType.returnType()).basicTypeKind(), firstLoopStateIndex + state);
++state;
}
// invoke loop predicate
emitLoopHandleInvoke(cob, invoker, preds, c, args, true, predType, loopLocalStateTypes, clauseDataIndex,
firstLoopStateIndex);
cob.ifne(lNext);
// invoke fini
emitLoopHandleInvoke(cob, invoker, finis, c, args, true, finiType, loopLocalStateTypes, clauseDataIndex,
firstLoopStateIndex);
cob.goto_w(lDone)
// this is the beginning of the next loop clause
.labelBinding(lNext);
}
cob.goto_w(lLoop)
// DONE:
.labelBinding(lDone);
return result;
}
private int extendLocalsMap(Class>[] types) {
int firstSlot = localsMap.length - 1;
localsMap = Arrays.copyOf(localsMap, localsMap.length + types.length);
localClasses = Arrays.copyOf(localClasses, localClasses.length + types.length);
System.arraycopy(types, 0, localClasses, firstSlot, types.length);
int index = localsMap[firstSlot - 1] + 1;
int lastSlots = 0;
for (int i = 0; i < types.length; ++i) {
localsMap[firstSlot + i] = index;
lastSlots = BasicType.basicType(localClasses[firstSlot + i]).basicTypeSlots();
index += lastSlots;
}
localsMap[localsMap.length - 1] = index - lastSlots;
return firstSlot;
}
private void emitLoopHandleInvoke(CodeBuilder cob, Name holder, int handles, int clause, Name args, boolean pushLocalState,
MethodType type, Class>[] loopLocalStateTypes, int clauseDataSlot,
int firstLoopStateSlot) {
// load handle for clause
emitPushClauseArray(cob, clauseDataSlot, handles);
cob.loadConstant(clause)
.aaload();
// load loop state (preceding the other arguments)
if (pushLocalState) {
for (int s = 0; s < loopLocalStateTypes.length; ++s) {
emitLoadInsn(cob, BasicType.basicType(loopLocalStateTypes[s]).basicTypeKind(), firstLoopStateSlot + s);
}
}
// load loop args (skip 0: method handle)
emitPushArguments(cob, args, 1);
cob.invokevirtual(CD_MethodHandle, "invokeBasic", methodDesc(type));
}
private void emitPushClauseArray(CodeBuilder cob, int clauseDataSlot, int which) {
emitLoadInsn(cob, TypeKind.REFERENCE, clauseDataSlot);
cob.loadConstant(which - 1)
.aaload();
}
private void emitZero(CodeBuilder cob, BasicType type) {
switch (type) {
case I_TYPE -> cob.iconst_0();
case J_TYPE -> cob.lconst_0();
case F_TYPE -> cob.fconst_0();
case D_TYPE -> cob.dconst_0();
case L_TYPE -> cob.aconst_null();
default -> throw new InternalError("unknown type: " + type);
};
}
private void emitPushArguments(CodeBuilder cob, Name args, int start) {
MethodType type = args.function.methodType();
for (int i = start; i < args.arguments.length; i++) {
emitPushArgument(cob, type.parameterType(i), args.arguments[i]);
}
}
private void emitPushArgument(CodeBuilder cob, Name name, int paramIndex) {
Object arg = name.arguments[paramIndex];
Class> ptype = name.function.methodType().parameterType(paramIndex);
emitPushArgument(cob, ptype, arg);
}
private void emitPushArgument(CodeBuilder cob, Class> ptype, Object arg) {
BasicType bptype = basicType(ptype);
if (arg instanceof Name n) {
emitLoadInsn(cob, n.type.basicTypeKind(), n.index());
emitImplicitConversion(cob, n.type, ptype, n);
} else if ((arg == null || arg instanceof String) && bptype == L_TYPE) {
cob.loadConstant((ConstantDesc)arg);
} else {
if (Wrapper.isWrapperType(arg.getClass()) && bptype != L_TYPE) {
cob.loadConstant((ConstantDesc)arg);
} else {
cob.getstatic(classData(cob, arg, CD_Object));
emitImplicitConversion(cob, L_TYPE, ptype, arg);
}
}
}
/**
* Store the name to its local, if necessary.
*/
private void emitStoreResult(CodeBuilder cob, Name name) {
if (name != null && name.type != V_TYPE) {
// non-void: actually assign
emitStoreInsn(cob, name.type.basicTypeKind(), name.index());
}
}
/**
* Emits a return statement from a LF invoker. If required, the result type is cast to the correct return type.
*/
private void emitReturn(CodeBuilder cob, Name onStack) {
// return statement
Class> rclass = invokerType.returnType();
BasicType rtype = lambdaForm.returnType();
assert(rtype == basicType(rclass)); // must agree
if (rtype == V_TYPE) {
// void
cob.return_();
// it doesn't matter what rclass is; the JVM will discard any value
} else {
LambdaForm.Name rn = lambdaForm.names[lambdaForm.result];
// put return value on the stack if it is not already there
if (rn != onStack) {
emitLoadInsn(cob, rtype.basicTypeKind(), lambdaForm.result);
}
emitImplicitConversion(cob, rtype, rclass, rn);
// generate actual return statement
cob.return_(rtype.basicTypeKind());
}
}
/**
* Emit a type conversion bytecode casting from "from" to "to".
*/
private void emitPrimCast(CodeBuilder cob, TypeKind from, TypeKind to) {
// Here's how.
// - indicates forbidden
// <-> indicates implicit
// to ----> boolean byte short char int long float double
// from boolean <-> - - - - - - -
// byte - <-> i2s i2c <-> i2l i2f i2d
// short - i2b <-> i2c <-> i2l i2f i2d
// char - i2b i2s <-> <-> i2l i2f i2d
// int - i2b i2s i2c <-> i2l i2f i2d
// long - l2i,i2b l2i,i2s l2i,i2c l2i <-> l2f l2d
// float - f2i,i2b f2i,i2s f2i,i2c f2i f2l <-> f2d
// double - d2i,i2b d2i,i2s d2i,i2c d2i d2l d2f <->
if (from != to && from != TypeKind.BOOLEAN) try {
cob.conversion(from, to);
} catch (IllegalArgumentException e) {
throw new IllegalStateException("unhandled prim cast: " + from + "2" + to);
}
}
/**
* Generate bytecode for a LambdaForm.vmentry which calls interpretWithArguments.
*/
static MemberName generateLambdaFormInterpreterEntryPoint(MethodType mt) {
assert(isValidSignature(basicTypeSignature(mt)));
String name = "interpret_"+basicTypeChar(mt.returnType());
MethodType type = mt; // includes leading argument
type = type.changeParameterType(0, MethodHandle.class);
InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("LFI", name, type);
return g.loadMethod(g.generateLambdaFormInterpreterEntryPointBytes());
}
private byte[] generateLambdaFormInterpreterEntryPointBytes() {
final byte[] classFile = classFileSetup(new Consumer<>() {
@Override
public void accept(ClassBuilder clb) {
methodSetup(clb, new Consumer<>() {
@Override
public void accept(MethodBuilder mb) {
mb.with(RuntimeVisibleAnnotationsAttribute.of(List.of(
HIDDEN, // Suppress this method in backtraces displayed to the user.
DONTINLINE // Don't inline the interpreter entry.
)));
mb.withCode(new Consumer<>() {
@Override
public void accept(CodeBuilder cob) {
// create parameter array
cob.loadConstant(invokerType.parameterCount())
.anewarray(CD_Object);
// fill parameter array
for (int i = 0; i < invokerType.parameterCount(); i++) {
Class> ptype = invokerType.parameterType(i);
cob.dup()
.loadConstant(i);
emitLoadInsn(cob, basicType(ptype).basicTypeKind(), i);
// box if primitive type
if (ptype.isPrimitive()) {
emitBoxing(cob, TypeKind.from(ptype));
}
cob.aastore();
}
// invoke
cob.aload(0)
.getfield(CD_MethodHandle, "form", CD_LambdaForm)
.swap() // swap form and array; avoid local variable
.invokevirtual(CD_LambdaForm, "interpretWithArguments", MethodTypeDescImpl.ofValidated(CD_Object, CD_Object_array));
// maybe unbox
Class> rtype = invokerType.returnType();
TypeKind rtypeK = TypeKind.from(rtype);
if (rtype.isPrimitive() && rtype != void.class) {
emitUnboxing(cob, rtypeK);
}
// return statement
cob.return_(rtypeK);
}
});
}
});
clinit(clb, classEntry, classData);
bogusMethod(clb, invokerType);
}
});
return classFile;
}
/**
* Generate bytecode for a NamedFunction invoker.
*/
static MemberName generateNamedFunctionInvoker(MethodTypeForm typeForm) {
MethodType invokerType = NamedFunction.INVOKER_METHOD_TYPE;
String invokerName = "invoke_" + shortenSignature(basicTypeSignature(typeForm.erasedType()));
InvokerBytecodeGenerator g = new InvokerBytecodeGenerator("NFI", invokerName, invokerType);
return g.loadMethod(g.generateNamedFunctionInvokerImpl(typeForm));
}
private byte[] generateNamedFunctionInvokerImpl(MethodTypeForm typeForm) {
MethodType dstType = typeForm.erasedType();
final byte[] classFile = classFileSetup(new Consumer<>() {
@Override
public void accept(ClassBuilder clb) {
methodSetup(clb, new Consumer<>() {
@Override
public void accept(MethodBuilder mb) {
mb.with(RuntimeVisibleAnnotationsAttribute.of(List.of(
HIDDEN, // Suppress this method in backtraces displayed to the user.
FORCEINLINE // Force inlining of this invoker method.
)));
mb.withCode(new Consumer<>() {
@Override
public void accept(CodeBuilder cob) {
// Load receiver
cob.aload(0);
// Load arguments from array
for (int i = 0; i < dstType.parameterCount(); i++) {
cob.aload(1)
.loadConstant(i)
.aaload();
// Maybe unbox
Class> dptype = dstType.parameterType(i);
if (dptype.isPrimitive()) {
TypeKind dstTK = TypeKind.from(dptype);
TypeKind srcTK = dstTK.asLoadable();
emitUnboxing(cob, srcTK);
emitPrimCast(cob, srcTK, dstTK);
}
}
// Invoke
MethodTypeDesc targetDesc = methodDesc(dstType.basicType());
cob.invokevirtual(CD_MethodHandle, "invokeBasic", targetDesc);
// Box primitive types
Class> rtype = dstType.returnType();
if (rtype != void.class && rtype.isPrimitive()) {
TypeKind srcTK = TypeKind.from(rtype);
TypeKind dstTK = srcTK.asLoadable();
// boolean casts not allowed
emitPrimCast(cob, srcTK, dstTK);
emitBoxing(cob, dstTK);
}
// If the return type is void we return a null reference.
if (rtype == void.class) {
cob.aconst_null();
}
cob.areturn(); // NOTE: NamedFunction invokers always return a reference value.
}
});
}
});
clinit(clb, classEntry, classData);
bogusMethod(clb, dstType);
}
});
return classFile;
}
/**
* Emit a bogus method that just loads some string constants. This is to get the constants into the constant pool
* for debugging purposes.
*/
private void bogusMethod(ClassBuilder clb, Object os) {
if (dumper().isEnabled()) {
clb.withMethodBody("dummy", MTD_void, ACC_STATIC, new Consumer<>() {
@Override
public void accept(CodeBuilder cob) {
cob.ldc(os.toString())
.pop()
.return_();
}
});
}
}
static ClassDesc classDesc(Class> cls) {
// assert(VerifyAccess.isTypeVisible(cls, Object.class)) : cls.getName();
return cls == MethodHandle.class ? CD_MethodHandle
: cls == DirectMethodHandle.class ? CD_DirectMethodHandle
: cls == Object.class ? CD_Object
: cls == MemberName.class ? CD_MemberName
: cls == MethodType.class ? CD_MethodType
: cls.isPrimitive() ? Wrapper.forPrimitiveType(cls).basicClassDescriptor()
: ReferenceClassDescImpl.ofValidated(cls.descriptorString());
}
static MethodTypeDesc methodDesc(MethodType mt) {
var params = new ClassDesc[mt.parameterCount()];
for (int i = 0; i < params.length; i++) {
params[i] = classDesc(mt.parameterType(i));
}
return MethodTypeDescImpl.ofValidated(classDesc(mt.returnType()), params);
}
}
{@code
* LOOP_SEQ_x: ALOAD clauseDataIndex
* ICONST_1
* AALOAD // load the steps array
* ICONST x
* AALOAD // load the step handle for clause x
* load locals
* load args
* INVOKEVIRTUAL MethodHandle.invokeBasic
* store vx
* ALOAD clauseDataIndex
* ICONST_2
* AALOAD // load the preds array
* ICONST x
* AALOAD // load the pred handle for clause x
* load locals
* load args
* INVOKEVIRTUAL MethodHandle.invokeBasic
* IFNE LOOP_SEQ_x+1 // predicate returned false -> jump to next clause
* ALOAD clauseDataIndex
* ICONST_3
* AALOAD // load the finis array
* ICONST x
* AALOAD // load the fini handle for clause x
* load locals
* load args
* INVOKEVIRTUAL MethodHandle.invokeBasic
* GOTO DONE // jump beyond end of clauses to return from loop
* }