1 /*
  2  * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.reflect.code.writer;
 27 
 28 import java.lang.reflect.code.*;
 29 import java.lang.reflect.code.op.OpFactory;
 30 import java.lang.reflect.code.op.ExternalizableOp;
 31 import java.lang.reflect.code.type.*;
 32 import java.util.*;
 33 
 34 import static java.lang.reflect.code.op.CoreOp.*;
 35 import static java.lang.reflect.code.type.FunctionType.functionType;
 36 import static java.lang.reflect.code.type.JavaType.*;
 37 
 38 /**
 39  * A transformer of code models to models that build them.
 40  * <p>
 41  * A building code model when executed will construct the same code model it was transformed from.
 42  * Such a building code model could be transformed to bytecode and stored in class files.
 43  */
 44 public class OpBuilder {
 45 
 46     static final JavaType J_C_O_EXTERNALIZED_OP = type(ExternalizableOp.ExternalizedOp.class);
 47 
 48     static final MethodRef OP_FACTORY_CONSTRUCT = MethodRef.method(OpFactory.class, "constructOp",
 49             Op.class, ExternalizableOp.ExternalizedOp.class);
 50 
 51     static final MethodRef TYPE_ELEMENT_FACTORY_CONSTRUCT = MethodRef.method(TypeElementFactory.class, "constructType",
 52             TypeElement.class, ExternalizedTypeElement.class);
 53 
 54     static final MethodRef EX_TYPE_ELEMENT_OF_STRING = MethodRef.method(ExternalizedTypeElement.class, "ofString",
 55             ExternalizedTypeElement.class, String.class);
 56 
 57     static final MethodRef BODY_BUILDER_OF = MethodRef.method(Body.Builder.class, "of",
 58             Body.Builder.class, Body.Builder.class, FunctionType.class);
 59 
 60     static final MethodRef BODY_BUILDER_ENTRY_BLOCK = MethodRef.method(Body.Builder.class, "entryBlock",
 61             Block.Builder.class);
 62 
 63     static final MethodRef BLOCK_BUILDER_SUCCESSOR = MethodRef.method(Block.Builder.class, "successor",
 64             Block.Reference.class, Value[].class);
 65 
 66     static final MethodRef BLOCK_BUILDER_OP = MethodRef.method(Block.Builder.class, "op",
 67             Op.Result.class, Op.class);
 68 
 69     static final MethodRef BLOCK_BUILDER_BLOCK = MethodRef.method(Block.Builder.class, "block",
 70             Block.Builder.class, TypeElement[].class);
 71 
 72     static final MethodRef BLOCK_BUILDER_PARAMETER = MethodRef.method(Block.Builder.class, "parameter",
 73             Block.Parameter.class, TypeElement.class);
 74 
 75     static final MethodRef FUNCTION_TYPE_FUNCTION_TYPE = MethodRef.method(FunctionType.class, "functionType",
 76             FunctionType.class, TypeElement.class, TypeElement[].class);
 77 
 78     static final MethodRef METHOD_REF_OF_STRING = MethodRef.method(MethodRef.class, "ofString",
 79             MethodRef.class, String.class);
 80 
 81     static final MethodRef FIELD_REF_OF_STRING = MethodRef.method(FieldRef.class, "ofString",
 82             FieldRef.class, String.class);
 83 
 84     static final MethodRef RECORD_TYPE_REF_OF_STRING = MethodRef.method(RecordTypeRef.class, "ofString",
 85             RecordTypeRef.class, String.class);
 86 
 87 
 88     static final JavaType J_U_LIST = type(List.class);
 89 
 90     static final MethodRef LIST_OF_ARRAY = MethodRef.method(J_U_LIST, "of",
 91             J_U_LIST, array(J_L_OBJECT, 1));
 92 
 93     static final JavaType J_U_MAP = type(Map.class);
 94 
 95     static final JavaType J_U_HASH_MAP = type(HashMap.class);
 96 
 97     static final JavaType J_U_MAP_ENTRY = type(Map.Entry.class);
 98 
 99     static final MethodRef MAP_ENTRY = MethodRef.method(J_U_MAP, "entry",
100             J_U_MAP, J_L_OBJECT, J_L_OBJECT);
101 
102     static final MethodRef MAP_OF = MethodRef.method(J_U_MAP, "of",
103             J_U_MAP);
104 
105     static final MethodRef MAP_OF_ARRAY = MethodRef.method(J_U_MAP, "of",
106             J_U_MAP, array(J_U_MAP_ENTRY, 1));
107 
108     static final MethodRef MAP_PUT = MethodRef.method(J_U_MAP, "put",
109             J_L_OBJECT, J_L_OBJECT, J_L_OBJECT);
110 
111 
112     static final FunctionType EXTERNALIZED_OP_F_TYPE = functionType(
113             J_C_O_EXTERNALIZED_OP,
114             J_L_STRING,
115             J_U_LIST,
116             J_U_LIST,
117             type(TypeElement.class),
118             J_U_MAP,
119             J_U_LIST);
120 
121     static final FunctionType BUILDER_F_TYPE = functionType(type(Op.class),
122             type(OpFactory.class),
123             type(TypeElementFactory.class));
124 
125 
126     Map<Value, Value> valueMap;
127 
128     Map<Block, Value> blockMap;
129 
130     Block.Builder builder;
131 
132     Value opFactory;
133 
134     Value typeElementFactory;
135 
136     /**
137      * Transform the given code model to one that builds it.
138      *
139      * @param op the code model
140      * @return the building code model.
141      */
142     public static FuncOp createBuilderFunction(Op op) {
143         return new OpBuilder().build(op);
144     }
145 
146     OpBuilder() {
147         this.valueMap = new HashMap<>();
148         this.blockMap = new HashMap<>();
149     }
150 
151     FuncOp build(Op op) {
152         Body.Builder body = Body.Builder.of(null, BUILDER_F_TYPE);
153 
154         builder = body.entryBlock();
155         opFactory = builder.parameters().get(0);
156         typeElementFactory = builder.parameters().get(1);
157 
158         Value ancestorBody = builder.op(constant(type(Body.Builder.class), null));
159         Value result = buildOp(ancestorBody, op);
160         builder.op(_return(result));
161 
162         return func("builder." + op.opName(), body);
163     }
164 
165 
166     Value buildOp(Value ancestorBody, Op inputOp) {
167         List<Value> bodies = new ArrayList<>();
168         for (Body inputBody : inputOp.bodies()) {
169             Value body = buildBody(ancestorBody, inputBody);
170             bodies.add(body);
171         }
172 
173         List<Value> operands = new ArrayList<>();
174         for (Value inputOperand : inputOp.operands()) {
175             Value operand = valueMap.get(inputOperand);
176             operands.add(operand);
177         }
178 
179         List<Value> successors = new ArrayList<>();
180         for (Block.Reference inputSuccessor : inputOp.successors()) {
181             List<Value> successorArgs = new ArrayList<>();
182             for (Value inputOperand : inputSuccessor.arguments()) {
183                 Value operand = valueMap.get(inputOperand);
184                 successorArgs.add(operand);
185             }
186             Value referencedBlock = blockMap.get(inputSuccessor.targetBlock());
187 
188             List<Value> args = new ArrayList<>();
189             args.add(referencedBlock);
190             args.addAll(successorArgs);
191             Value successor = builder.op(invoke(BLOCK_BUILDER_SUCCESSOR, args));
192             successors.add(successor);
193         }
194 
195         Value opDef = buildOpDefinition(
196                 inputOp.opName(),
197                 operands,
198                 successors,
199                 inputOp.resultType(),
200                 inputOp instanceof ExternalizableOp exop ? exop.attributes() : Map.of(),
201                 bodies);
202         return builder.op(invoke(OP_FACTORY_CONSTRUCT, opFactory, opDef));
203     }
204 
205 
206     Value buildOpDefinition(String name,
207                             List<Value> operands,
208                             List<Value> successors,
209                             TypeElement resultType,
210                             Map<String, Object> attributes,
211                             List<Value> bodies) {
212         List<Value> args = List.of(
213                 builder.op(constant(J_L_STRING, name)),
214                 buildList(type(Value.class), operands),
215                 buildList(type(Block.Reference.class), successors),
216                 buildType(resultType),
217                 buildAttributeMap(attributes),
218                 buildList(type(Body.Builder.class), bodies));
219         return builder.op(_new(EXTERNALIZED_OP_F_TYPE, args));
220     }
221 
222     Value buildBody(Value ancestorBodyValue, Body inputBody) {
223         Value yieldType = buildType(inputBody.yieldType());
224         Value bodyType = builder.op(invoke(FUNCTION_TYPE_FUNCTION_TYPE, yieldType));
225         Value body = builder.op(invoke(BODY_BUILDER_OF, ancestorBodyValue, bodyType));
226 
227         Value entryBlock = null;
228         for (Block inputBlock : inputBody.blocks()) {
229             Value block;
230             if (inputBlock.isEntryBlock()) {
231                 block = entryBlock = builder.op(invoke(BODY_BUILDER_ENTRY_BLOCK, body));
232             } else {
233                 assert entryBlock != null;
234                 block = builder.op(invoke(BLOCK_BUILDER_BLOCK, entryBlock));
235             }
236             blockMap.put(inputBlock, block);
237 
238             for (Block.Parameter inputP : inputBlock.parameters()) {
239                 Value type = buildType(inputP.type());
240                 Value blockParameter = builder.op(invoke(BLOCK_BUILDER_PARAMETER, block, type));
241                 valueMap.put(inputP, blockParameter);
242             }
243         }
244 
245         for (Block inputBlock : inputBody.blocks()) {
246             Value block = blockMap.get(inputBlock);
247             for (Op inputOp : inputBlock.ops()) {
248                 Value op = buildOp(body, inputOp);
249                 Value result = builder.op(invoke(BLOCK_BUILDER_OP, block, op));
250                 valueMap.put(inputOp.result(), result);
251             }
252         }
253 
254         return body;
255     }
256 
257     Value buildType(TypeElement t) {
258         Value typeString = builder.op(constant(J_L_STRING, t.toString()));
259         Value exTypeElem = builder.op(invoke(EX_TYPE_ELEMENT_OF_STRING, typeString));
260         return builder.op(invoke(TYPE_ELEMENT_FACTORY_CONSTRUCT, typeElementFactory, exTypeElem));
261     }
262 
263     Value buildAttributeMap(Map<String, Object> attributes) {
264         List<Value> keysAndValues = new ArrayList<>();
265         for (Map.Entry<String, Object> entry : attributes.entrySet()) {
266             Value key = builder.op(constant(J_L_STRING, entry.getKey()));
267             Value value = buildAttributeValue(entry.getValue());
268             keysAndValues.add(key);
269             keysAndValues.add(value);
270         }
271         return buildMap(J_L_STRING, J_L_OBJECT, keysAndValues);
272     }
273 
274     Value buildAttributeValue(Object value) {
275         return switch (value) {
276             case Boolean v -> {
277                 yield builder.op(constant(BOOLEAN, value));
278             }
279             case Byte v -> {
280                 yield builder.op(constant(BYTE, value));
281             }
282             case Short v -> {
283                 yield builder.op(constant(SHORT, value));
284             }
285             case Character v -> {
286                 yield builder.op(constant(CHAR, value));
287             }
288             case Integer v -> {
289                 yield builder.op(constant(INT, value));
290             }
291             case Long v -> {
292                 yield builder.op(constant(LONG, value));
293             }
294             case Float v -> {
295                 yield builder.op(constant(FLOAT, value));
296             }
297             case Double v -> {
298                 yield builder.op(constant(DOUBLE, value));
299             }
300             case Class<?> v -> {
301                 yield buildType(JavaType.type(v));
302             }
303             case String s -> {
304                 yield builder.op(constant(J_L_STRING, value));
305             }
306             case MethodRef r -> {
307                 Value string = builder.op(constant(J_L_STRING, value.toString()));
308                 yield builder.op(invoke(METHOD_REF_OF_STRING, string));
309             }
310             case FieldRef r -> {
311                 Value string = builder.op(constant(J_L_STRING, value.toString()));
312                 yield builder.op(invoke(FIELD_REF_OF_STRING, string));
313             }
314             case RecordTypeRef r -> {
315                 Value string = builder.op(constant(J_L_STRING, value.toString()));
316                 yield builder.op(invoke(RECORD_TYPE_REF_OF_STRING, string));
317             }
318             case TypeElement f -> {
319                 yield buildType(f);
320             }
321             case Location l -> {
322                 // @@@ Construct location explicitly
323                 yield builder.op(constant(J_L_STRING, l.toString()));
324             }
325             case Object o when value == ExternalizableOp.NULL_ATTRIBUTE_VALUE -> {
326                 yield builder.op(fieldLoad(FieldRef.field(ExternalizableOp.class,
327                         "NULL_ATTRIBUTE_VALUE", Object.class)));
328             }
329             default -> {
330                 // @@@ use the result of value.toString()?
331                 throw new UnsupportedOperationException("Unsupported attribute value: " + value);
332             }
333         };
334     }
335 
336 
337     Value buildMap(JavaType keyType, JavaType valueType, List<Value> keysAndValues) {
338         JavaType mapType = parameterized(J_U_MAP, keyType, valueType);
339         if (keysAndValues.isEmpty()) {
340             return builder.op(invoke(MAP_OF));
341         } else {
342             Value map = builder.op(_new(mapType, functionType(J_U_HASH_MAP)));
343             for (int i = 0; i < keysAndValues.size(); i += 2) {
344                 Value key = keysAndValues.get(i);
345                 Value value = keysAndValues.get(i + 1);
346                 builder.op(invoke(MAP_PUT, map, key, value));
347             }
348             return map;
349         }
350     }
351 
352 
353     Value buildList(JavaType elementType, List<Value> elements) {
354         JavaType listType = parameterized(J_U_LIST, elementType);
355         if (elements.size() < 11) {
356             MethodRef listOf = MethodRef.method(J_U_LIST, "of",
357                     J_U_LIST, Collections.nCopies(elements.size(), J_L_OBJECT));
358             return builder.op(invoke(listType, listOf, elements));
359         } else {
360             Value array = buildArray(elementType, elements);
361             return builder.op(invoke(listType, LIST_OF_ARRAY, array));
362         }
363     }
364 
365 
366     Value buildArray(JavaType elementType, List<Value> elements) {
367         Value array = builder.op(newArray(elementType,
368                 builder.op(constant(INT, elements.size()))));
369         for (int i = 0; i < elements.size(); i++) {
370             builder.op(arrayStoreOp(array, elements.get(i),
371                     builder.op(constant(INT, i))));
372         }
373         return array;
374     }
375 }