1 /*
  2  * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 package jdk.incubator.code.runtime;
 25 
 26 import java.lang.invoke.CallSite;
 27 import java.lang.invoke.ConstantCallSite;
 28 import java.lang.invoke.LambdaConversionException;
 29 import java.lang.invoke.MethodHandle;
 30 import java.lang.invoke.MethodHandles;
 31 import java.lang.invoke.MethodHandles.Lookup;
 32 import java.lang.invoke.MethodType;
 33 import java.lang.reflect.Member;
 34 import java.lang.reflect.Method;
 35 import java.util.List;
 36 import java.util.Objects;
 37 import java.util.stream.Stream;
 38 import jdk.incubator.code.Op;
 39 import jdk.incubator.code.bytecode.BytecodeGenerator;
 40 import jdk.incubator.code.dialect.core.CoreOp;
 41 import jdk.incubator.code.dialect.core.CoreType;
 42 import jdk.incubator.code.dialect.java.JavaOp;
 43 
 44 /**
 45  * Bootstrap methods for linking {@code invokedynamic} call sites that execute
 46  * method code models or create lambda instances implemented by code models.
 47  *
 48  * @see ReflectableLambdaMetafactory
 49  */
 50 public final class CodeModelBootstraps {
 51 
 52     private CodeModelBootstraps() {
 53     }
 54 
 55     /**
 56      * Bootstrap method for linking an {@code invokedynamic} call site that
 57      * implements execution of a method's code model.
 58      * <p>
 59      * The method's code model is obtained for the method referenced by the
 60      * given method handle. If the method does not have a code model then an
 61      * {@code IllegalArgumentException} is thrown.
 62      * <p>
 63      * Execution of the code model is implemented by transforming the code model
 64      * to bytecode and linking it as the target method handle of the returned
 65      * {@code CallSite}.
 66      * <p>
 67      * If model retrieval or transformation fails, the resulting exception or
 68      * error is propagated.
 69      *
 70      * @param lookup   Represents a lookup context with the accessibility
 71      *                 privileges of the caller. Specifically, the lookup
 72      *                 context must have
 73      *                 {@linkplain MethodHandles.Lookup#hasFullPrivilegeAccess()
 74      *                 full privilege access}.
 75      *                 When used with {@code invokedynamic}, this is stacked
 76      *                 automatically by the VM.
 77      * @param name     The name of the method to implement. This name is
 78      *                 arbitrary, and has no meaning for this linkage method.
 79      *                 When used with {@code invokedynamic}, this is provided by
 80      *                 the {@code NameAndType} of the {@code InvokeDynamic}
 81      *                 structure and is stacked automatically by the VM.
 82      * @param methodType The expected signature of the {@code CallSite}. When
 83      *                   used with {@code invokedynamic}, this is provided by the
 84      *                   {@code NameAndType} of the {@code InvokeDynamic}
 85      *                   structure and is stacked automatically by the VM.
 86      * @param method a direct method handle referencing the original method
 87      * @return a constant call site whose target implements the behavior
 88      *         represented by the stored code model
 89      * @throws NullPointerException If any of the incoming arguments is null.
 90      *                              This will never happen when a bootstrap method
 91      *                              is called with {@code invokedynamic}.
 92      * @throws IllegalArgumentException if the handle cannot be revealed by
 93      *         {@code lookup}, does not reference an accessible method, the
 94      *         method has no code model, or the generated target type differs
 95      *         from {@code methodType}
 96      */
 97     public static CallSite codeModelExecutor(MethodHandles.Lookup lookup,
 98                                              String name,
 99                                              MethodType methodType,
100                                              MethodHandle method) {
101         Objects.requireNonNull(name);
102         Objects.requireNonNull(methodType);
103         Member member = lookup.revealDirect(method).reflectAs(Member.class, lookup);
104         if (!(member instanceof Method m)) {
105             throw new IllegalArgumentException("Handle does not reference a method");
106         }
107         CoreOp.FuncOp model = Op.ofMethod(m).orElseThrow(() ->
108                 new IllegalArgumentException("Method has no code model: " + m));
109         MethodHandle target = BytecodeGenerator.generate(lookup, model);
110         if (!target.type().equals(methodType)) {
111             throw new IllegalArgumentException("Code model target type " + target.type()
112                     + " differs from call-site type " + methodType);
113         }
114         return new ConstantCallSite(target);
115     }
116 
117     /**
118      * Bootstrap method for linking an {@code invokedynamic} call site whose
119      * target creates reflectable lambda instances, using the lambda's stored
120      * code model as its implementation.
121      *
122      * @param caller the lookup
123      * @param interfaceMethodName The name of the method to implement.
124      * @param factoryType The expected signature of the {@code CallSite}.
125      * @param interfaceMethodType Signature and return type of method to be
126      *                            implemented by the function object.
127      * @param implementation A direct method handle describing the original
128      *                       implementation method.
129      * @param dynamicMethodType The signature and return type that should
130      *                          be enforced dynamically at invocation time.
131      * @return a call site whose target creates reflectable lambda instances of
132      *         the functional interface specified by the return type of
133      *         {@code factoryType}; each instance can be inspected using
134      *         {@link Op#ofLambda(Object)}
135      *
136      * @throws LambdaConversionException if the implementation cannot be linked
137      *         from its stored code model, or the parameters of the call are invalid for
138      *         {@link ReflectableLambdaMetafactory#metafactory(Lookup, String,
139      *                MethodType, MethodType, MethodHandle, MethodType)}
140      * @throws NullPointerException if any argument is {@code null}
141      *
142      * @see ReflectableLambdaMetafactory#metafactory(Lookup, String, MethodType,
143      *      MethodType, MethodHandle, MethodType)
144      * @see Op#ofLambda(Object)
145      */
146     public static CallSite lambdaMetafactory(MethodHandles.Lookup caller,
147                                              String interfaceMethodName,
148                                              MethodType factoryType,
149                                              MethodType interfaceMethodType,
150                                              MethodHandle implementation,
151                                              MethodType dynamicMethodType) throws LambdaConversionException {
152         MethodHandle opHandle = ReflectableLambdaMetafactory.findReflectableOpGetter(caller, implementation);
153         MethodHandle generatedImpl = linkLambdaImplementation(caller, opHandle);
154         MethodType generatedFactoryType = generatedFactoryType(factoryType, generatedImpl);
155         var finisher = new ReflectableLambdaMetafactory.LambdaFinisher(caller.lookupClass(),
156                 generatedFactoryType.parameterList(), opHandle);
157         CallSite site = ReflectableLambdaMetafactory.JLI_ACCESS.metafactoryInternal(caller, interfaceMethodName,
158                 generatedFactoryType, interfaceMethodType, generatedImpl, dynamicMethodType, finisher);
159         return new ConstantCallSite(site.getTarget().asType(factoryType));
160     }
161 
162     /**
163      * Bootstrap method for linking an {@code invokedynamic} call site whose
164      * target creates reflectable lambda instances, using the lambda's stored
165      * code model as its implementation.
166      *
167      * @param caller the lookup
168      * @param interfaceMethodName The name of the method to implement.
169      * @param factoryType The expected signature of the {@code CallSite}.
170      * @param args An array of {@code Object} containing the required
171      *              arguments {@code interfaceMethodType}, {@code implementation},
172      *              {@code dynamicMethodType}, {@code flags}, and any
173      *              optional arguments, as required by
174      *              {@link ReflectableLambdaMetafactory#altMetafactory(Lookup,
175      *                     String, MethodType, Object...)}
176      * @return a CallSite whose target can be used to perform capture, generating
177      *         a reflectable lambda instance implementing the functional
178      *         interface specified by the return type of {@code factoryType}.
179      *         The code model for such instance can be inspected using
180      *         {@link Op#ofLambda(Object)}.
181      *
182      * @throws LambdaConversionException if the implementation cannot be linked
183      *         from its stored code model, or the parameters of the call are invalid for
184      *         {@link ReflectableLambdaMetafactory#altMetafactory(Lookup, String,
185      *                MethodType, Object...)}
186      * @throws NullPointerException if {@code caller}, {@code interfaceMethodName},
187      *         {@code factoryType}, or {@code args} is {@code null}, or if a
188      *         required component of {@code args} other than
189      *         {@code implementation} is {@code null}
190      * @throws IllegalArgumentException if the {@code implementation} component is
191      *         {@code null}, or {@code args} are invalid for
192      *         {@link ReflectableLambdaMetafactory#altMetafactory(Lookup, String,
193      *                MethodType, Object...)}
194      *
195      * @see ReflectableLambdaMetafactory#altMetafactory(Lookup, String, MethodType,
196      *      Object...)
197      * @see Op#ofLambda(Object)
198      */
199     public static CallSite lambdaAltMetafactory(MethodHandles.Lookup caller,
200                                                 String interfaceMethodName,
201                                                 MethodType factoryType,
202                                                 Object... args) throws LambdaConversionException {
203         if (args.length < 2) {
204             throw new IllegalArgumentException("missing argument");
205         }
206         if (!(args[1] instanceof MethodHandle impl)) {
207             throw new IllegalArgumentException("argument has wrong type");
208         }
209         MethodHandle opHandle = ReflectableLambdaMetafactory.findReflectableOpGetter(caller, impl);
210         MethodHandle generatedImpl = linkLambdaImplementation(caller, opHandle);
211         args[1] = generatedImpl;
212         MethodType generatedFactoryType = generatedFactoryType(factoryType, generatedImpl);
213         var finisher = new ReflectableLambdaMetafactory.LambdaFinisher(caller.lookupClass(),
214                 generatedFactoryType.parameterList(), opHandle);
215         CallSite site = ReflectableLambdaMetafactory.JLI_ACCESS.altMetafactoryInternal(caller, interfaceMethodName,
216                 generatedFactoryType, finisher, args);
217         return new ConstantCallSite(site.getTarget().asType(factoryType));
218     }
219 
220     private static MethodType generatedFactoryType(MethodType factoryType, MethodHandle implementation) {
221         MethodType implementationType = implementation.type();
222         return implementationType.dropParameterTypes(factoryType.parameterCount(), implementationType.parameterCount())
223                                  .changeReturnType(factoryType.returnType());
224     }
225 
226     private static MethodHandle linkLambdaImplementation(MethodHandles.Lookup caller,
227                                                          MethodHandle opHandle)
228             throws LambdaConversionException {
229         try {
230             MethodHandle methodHandle = BytecodeGenerator.generate(caller,
231                                                                    unquoteLambda((CoreOp.FuncOp)opHandle.invoke()));
232             return methodHandle;
233         } catch (Throwable t) {
234             throw new LambdaConversionException(t);
235         }
236     }
237 
238     // flatten the quoted lambda into the enclosing function model
239     private static CoreOp.FuncOp unquoteLambda(CoreOp.FuncOp funcOp) {
240         int capturedValues = funcOp.parameters().size();
241         List<Op> ops = funcOp.body().entryBlock().ops();
242         JavaOp.LambdaOp lambda = (JavaOp.LambdaOp)((CoreOp.QuotedOp)ops.get(ops.size() - 2)).quotedOp();
243         return CoreOp.func(funcOp.funcName(), CoreType.functionType(
244                 lambda.body().yieldType(),
245                 Stream.of(funcOp.invokableSignature().parameterTypes(),
246                           lambda.invokableSignature().parameterTypes()).flatMap(List::stream).toList())).body(bb -> {
247             bb.context().mapValues(funcOp.parameters(), bb.parameters().subList(0, capturedValues));
248             for (int i = 0; i < ops.size() - 2; i++) {
249                 Op o = ops.get(i);
250                 bb.add(o);
251             }
252             bb.transformBody(lambda.body(),
253                              bb.parameters().subList(capturedValues, bb.parameters().size()));
254         });
255     }
256 }