1 /*
  2  * Copyright (c) 2024, 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.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package jdk.incubator.code;
 27 
 28 import jdk.incubator.code.dialect.core.CoreOp;
 29 import jdk.incubator.code.dialect.core.CoreType;
 30 import jdk.incubator.code.dialect.core.FunctionType;
 31 import jdk.incubator.code.dialect.core.VarType;
 32 import jdk.incubator.code.dialect.java.JavaType;
 33 import jdk.incubator.code.dialect.java.PrimitiveType;
 34 
 35 import java.util.*;
 36 import java.util.function.Predicate;
 37 
 38 /**
 39  * An operation and a mapping from the operation's {@link Op#operands() operands} and
 40  * {@link Op#capturedValues() captured values} to runtime values. This pair is referred
 41  * to as the quoted form of an operation, and represents an operation in a runtime context
 42  * independent of its surrounding code model.
 43  *
 44  * @param <T> the type of operation that is quoted
 45  */
 46 public final class Quoted<T extends Op> {
 47     private final T op;
 48     private final SequencedMap<Value, Object> operandsAndCapturedValues;
 49 
 50     /**
 51      * Constructs the quoted form of a given operation.
 52      *
 53      * @param op                        the operation.
 54      * @param operandsAndCapturedValues map containing the operation's operands and captured values to runtime values
 55      * @throws IllegalArgumentException if the map's key set does not contain set consisting of operation's operands
 56      *                                  and the captured values
 57      * @see Op#capturedValues()
 58      * @see Op#operands()
 59      */
 60     public Quoted(T op, Map<Value, Object> operandsAndCapturedValues) {
 61         SequencedMap<Value, Object> m = new LinkedHashMap<>();
 62         for (Value value : op.operands()) {
 63             m.put(value, runtimeValue(operandsAndCapturedValues, value));
 64         }
 65         for (Value value : op.capturedValues()) {
 66             m.put(value, runtimeValue(operandsAndCapturedValues, value));
 67         }
 68 
 69         this.op = op;
 70         this.operandsAndCapturedValues = Collections.unmodifiableSequencedMap(m);
 71     }
 72 
 73     static Object runtimeValue(Map<Value, Object> operandsAndCapturedValues, Value value) {
 74         if (!operandsAndCapturedValues.containsKey(value)) {
 75             throw new IllegalArgumentException("Value is not present as a key in the map of values");
 76         }
 77         return operandsAndCapturedValues.get(value);
 78     }
 79 
 80     /**
 81      * Returns the operation.
 82      *
 83      * @return the operation.
 84      */
 85     public T op() {
 86         return op;
 87     }
 88 
 89     /**
 90      * Returns the map of captured values to runtime values.
 91      * <p>
 92      * The captured values key set has the same elements and same encounter order as
 93      * operation's captured values, specifically the following expression evaluates to true:
 94      * {@snippet lang=java :
 95      * op().capturedValues().equals(new ArrayList<>(capturedValues().keySet()));
 96      * }
 97      *
 98      * @return the mapping of captured values.
 99      */
100     public SequencedMap<Value, Object> capturedValues() {
101         SequencedMap<Value, Object> m = new LinkedHashMap<>();
102         for (Value cv : op.capturedValues()) {
103             m.put(cv, operandsAndCapturedValues.get(cv));
104         }
105         return m;
106     }
107 
108     /**
109      * Returns the map of operands to runtime values.
110      * <p>
111      * The  key set has the same elements and same encounter order as the sequenced set of operation's operands,
112      * specifically the following expression evaluates to true:
113      * {@snippet lang = java:
114      * op.operands().equals(new ArrayList<>(operands().keySet()))
115      *}
116      *
117      * @return the map of operands.
118      */
119     public SequencedMap<Value, Object> operands() {
120         SequencedMap<Value, Object> m = new LinkedHashMap<>();
121         for (Value operand : op.operands()) {
122             // putIfAbsent is used because a value may be used as operand more than once
123             m.putIfAbsent(operand, operandsAndCapturedValues.get(operand));
124         }
125         return m;
126     }
127 
128     /**
129      * Returns the map of operands and captured values to runtime values.
130      * <p>
131      * The map's key set is equal to the sequenced set of the quoted operation's
132      * operands and captured values.
133      *
134      * @return the map of operands and captured values, as an unmodifiable map.
135      */
136     public SequencedMap<Value, Object> operandsAndCapturedValues() {
137         return operandsAndCapturedValues;
138     }
139 
140     /**
141      * Returns a quoting code model whose behavior quotes the given source operation.
142      * <p>
143      * This method behaves as if it returns the result of invoking {@link #embedOp(Op, Map)} with the source operation
144      * and an empty map as the arguments.
145      *
146      * @param op the source operation to quote
147      * @return the quoting code model
148      * @throws IllegalArgumentException if {@code op} is not placed in a block
149      * @see #embedOp(Op, Map)
150      */
151     public static CoreOp.FuncOp embedOp(Op op) {
152         return embedOp(op, Map.of());
153     }
154 
155     /**
156      * Returns a quoting code model whose behavior quotes the given source operation.
157      * <p>
158      * A quoting code model is a {@link jdk.incubator.code.dialect.core.CoreOp.FuncOp function operation} that has one
159      * body with one block, <i>fblock</i>, and whose behavior returns an instance of {@link Quoted} that contains a copy
160      * of the source operation.
161      * <p>
162      * The source operation has a sequence of values, <i>source values</i>, that is the operation's
163      * {@link Op#operands() operands} followed by the operation's {@link Op#capturedValues() captured values}.
164      * The quoting function operation has a sequence of values, <i>quoting values</i>, mapped from the source values.
165      * Each quoting value is a block parameter of <i>fblock</i>, the result of variable operation in <i>fblock</i>
166      * initialized with a block parameter of <i>fblock</i>, or the result of constant operation in <i>fblock</i>.
167      * <p>
168      * For each source value, if the value has an entry in the captured constants, then <i>fblock</i> will contain a
169      * constant operation whose constant value is the entry's value. The source value is mapped to a quoting value that
170      * is the result of the constant operation. Otherwise, if the value has no entry in the captured constants,
171      * <i>fblock</i> has a block parameter in the same order as the source value. If the source value is the result of a
172      * {@link jdk.incubator.code.dialect.core.CoreOp.VarOp variable operation} then the block parameter's code type is
173      * the same as variable operation's value type, and <i>fblock</i> has a variable operation whose operand is the
174      * block parameter. The source value is mapped to a quoting value that is the result of the variable operation.
175      * Otherwise, the block parameter's code type is the same as the source value's code type. The source value is
176      * mapped to a quoting value that is the block parameter.
177      * <p>
178      * <i>fblock</i> has a {@link jdk.incubator.code.dialect.core.CoreOp.QuotedOp quoted operation} that has one body
179      * with one block (<i>qblock</i>). <i>qblock</i> has a copy of the source operation, that is copied using a code
180      * context containing the mappings of source values to quoting values.
181      * <p>
182      * <i>fblock</i> terminates with a {@link jdk.incubator.code.dialect.core.CoreOp.ReturnOp return operation}, whose
183      * operand is the operation result of the quoted operation.
184      *
185      * @param op the source operation to quote
186      * @param capturedConstants the captured constants to embed in the quoting code model
187      * @return the quoting code model
188      * @throws IllegalArgumentException if source operation is not placed in a block
189      */
190     public static CoreOp.FuncOp embedOp(Op op, Map<Value, Object> capturedConstants) {
191         if (op.result() == null) {
192             throw new IllegalArgumentException("Operation is not placed in a block");
193         }
194 
195         // if we don't remove duplicate operands we will have unused params in the new model
196         // if we don't remove captured values that are operands we will have unused params in the new model
197         SequencedSet<Value> s = new LinkedHashSet<>(op.operands());
198         s.addAll(op.capturedValues());
199         List<Value> inputOperandsAndCaptures = s.stream().toList();
200 
201         // Build the function type
202         List<CodeType> params = inputOperandsAndCaptures.stream()
203                 .filter(Predicate.not(capturedConstants::containsKey))
204                 .map(v -> v.type() instanceof VarType vt ? vt.valueType() : v.type())
205                 .toList();
206         FunctionType ft = CoreType.functionType(CoreOp.QuotedOp.QUOTED_OP_TYPE, params);
207 
208         // Build the function that quotes the lambda
209         return CoreOp.func("q", ft).body(b -> {
210             // Create variables as needed and obtain the operands and captured values for the copied lambda
211             List<Value> outputOperandsAndCaptures = new ArrayList<>();
212             int i = 0;
213             for (Value inputValue : inputOperandsAndCaptures) {
214                 Value outputValue;
215                 if (capturedConstants.containsKey(inputValue)) {
216                     outputValue = b.add(CoreOp.constant(inputValue.type(), capturedConstants.get(inputValue)));
217                 } else {
218                     outputValue = b.parameters().get(i++);
219                     if (inputValue.type() instanceof VarType) {
220                         outputValue = b.add(CoreOp.var(String.valueOf(i), outputValue));
221                     }
222                 }
223                 outputOperandsAndCaptures.add(outputValue);
224             }
225 
226             // Quoted the lambda expression
227             Value q = b.add(CoreOp.quoted(b.parentBody(), qb -> {
228                 // Map the entry block of the op's ancestor body to the quoted block
229                 // We are copying op in the context of the quoted block, the block mapping
230                 // ensures the use of operands and captured values are reachable when building
231                 qb.context().mapBlock(op.ancestorBody().entryBlock(), qb);
232                 // Map the op's operands and captured values
233                 qb.context().mapValues(inputOperandsAndCaptures, outputOperandsAndCaptures);
234                 // Return the op to be copied in the quoted operation
235                 return op;
236             }));
237             b.add(CoreOp.return_(q));
238         });
239     }
240 
241     private static IllegalArgumentException invalidQuotedModel(CoreOp.FuncOp model) {
242         return new IllegalArgumentException("Invalid code model for quoted operation : " + model);
243     }
244 
245     /**
246      * Extracts the quoted operation from a quoting code model with the given runtime arguments.
247      * <p>
248      * This method behaves as if the quoting code model is executed with the runtime arguments by interpreting the
249      * behavior of the code elements, as specified, in the code model, but it may be implemented more efficiently.
250      *
251      * @param funcOp the quoting code model
252      * @param args   the runtime arguments
253      * @return quoted form of the extracted operation
254      * @throws IllegalArgumentException if the quoting code model is invalid and does not conform to that specified
255      * the method {@link #embedOp(Op)}.
256      * @throws IllegalArgumentException if the quoting code model's parameters differ in arity from the
257      * runtime arguments.
258      */
259     public static Quoted<Op> extractOp(CoreOp.FuncOp funcOp, List<Object> args) {
260         if (funcOp.body().blocks().size() != 1) {
261             throw invalidQuotedModel(funcOp);
262         }
263         Block fblock = funcOp.body().entryBlock();
264         List<Op> ops = fblock.ops();
265         if (ops.size() < 2
266                 || !(ops.get(ops.size() - 2) instanceof CoreOp.QuotedOp qop)
267                 || !(ops.getLast() instanceof CoreOp.ReturnOp returnOp)
268                 || returnOp.returnValue() == null
269                 || !returnOp.returnValue().equals(qop.result())) {
270 
271             throw invalidQuotedModel(funcOp);
272         }
273 
274         Op op = qop.quotedOp();
275 
276         SequencedSet<Value> operandsAndCaptures = new LinkedHashSet<>();
277         operandsAndCaptures.addAll(op.operands());
278         operandsAndCaptures.addAll(op.capturedValues());
279 
280         // each parameter supplies one quoted value, directly or through an outer VarOp
281         // @@@ unused receiver is hard to identify and must be accepted
282         for (Block.Parameter p : fblock.parameters()) {
283             if (!operandsAndCaptures.contains(p)
284                     && !p.uses().stream().allMatch(u -> u.op() instanceof CoreOp.VarOp varOp
285                     && varOp.ancestorBlock() == fblock
286                     && operandsAndCaptures.contains(varOp.result()))) {
287                 throw invalidQuotedModel(funcOp);
288             }
289         }
290 
291         for (int i = 0; i < ops.size() - 2; i++) {
292             if (ops.get(i) instanceof CoreOp.ConstantOp constantOp
293                     && (constantOp.resultType() instanceof PrimitiveType
294                         && !constantOp.resultType().equals(JavaType.VOID)
295                         || constantOp.resultType().equals(JavaType.J_L_STRING))
296                     && operandsAndCaptures.contains(constantOp.result())) {
297                 continue;
298             } else if (!(ops.get(i) instanceof CoreOp.VarOp varOp)
299                     || varOp.isUninitialized()
300                     || !(varOp.initOperand() instanceof Block.Parameter p)
301                     || p.declaringBlock() != fblock
302                     || !operandsAndCaptures.contains(varOp.result())) {
303                 throw invalidQuotedModel(funcOp);
304             }
305         }
306 
307         // map operands and captures to their corresponding runtime values
308         // operand and capture can be:
309         // 1- block param of this function
310         // 2- result of VarOp whose initial value is a block param of this function
311         // 3- result of a primitive or String ConstantOp in this function's entry block
312         List<Block.Parameter> params = funcOp.parameters();
313         if (params.size() != args.size()) {
314             throw invalidQuotedModel(funcOp);
315         }
316         SequencedMap<Value, Object> m = new LinkedHashMap<>();
317         for (Value v : operandsAndCaptures) {
318             switch (v) {
319                 // reject captures from another block
320                 case Block.Parameter p when p.declaringBlock() == fblock -> {
321                     Object rv = args.get(p.index());
322                     m.put(v, rv);
323                 }
324                 case Op.Result opr when opr.op() instanceof CoreOp.VarOp varOp
325                                      && varOp.ancestorBlock() == fblock
326                                      && varOp.initOperand() instanceof Block.Parameter p -> {
327                     Object rv = args.get(p.index());
328                     m.put(v, CoreOp.Var.of(rv));
329                 }
330                 case Op.Result opr when opr.op() instanceof CoreOp.ConstantOp constantOp
331                                      && constantOp.ancestorBlock() == fblock ->
332                         m.put(v, constantOp.value());
333                 default -> throw invalidQuotedModel(funcOp);
334             }
335         }
336 
337         return new Quoted<>(op, m);
338     }
339 
340     /**
341      * Extracts the quoted operation from {@code funcOp}
342      * and map its operands and captured values to the runtime values in {@code args}.
343      * <p>
344      * {@code funcOp} must have the same structure as if it's produced by {@link #embedOp(Op)}.
345      *
346      * @param funcOp Model to extract the quoted op from
347      * @param args   Runtime values for {@code funcOp} parameters
348      * @return Quoted instance that wraps the quoted operation,
349      * plus the mapping of its operands and captured values to the given runtime values
350      * @throws RuntimeException If {@code funcOp} isn't a valid code model
351      * @throws RuntimeException If {@code funcOp} parameters size is different from {@code args} length
352      * @see Quoted#extractOp(CoreOp.FuncOp, List)
353      */
354     public static Quoted<Op> extractOp(CoreOp.FuncOp funcOp, Object... args) {
355         return extractOp(funcOp, Arrays.asList(args));
356     }
357 }