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 jdk.incubator.code.internal; 27 28 import jdk.incubator.code.*; 29 import jdk.incubator.code.dialect.core.CoreType; 30 import jdk.incubator.code.dialect.core.FunctionType; 31 import jdk.incubator.code.dialect.java.*; 32 import jdk.incubator.code.extern.*; 33 34 import java.util.*; 35 import java.util.function.Function; 36 import java.util.stream.Stream; 37 38 import static jdk.incubator.code.dialect.core.CoreOp.*; 39 import static jdk.incubator.code.dialect.core.CoreType.functionType; 40 import static jdk.incubator.code.dialect.java.JavaOp.*; 41 import static jdk.incubator.code.dialect.java.JavaType.*; 42 43 /** 44 * A transformer of code models to models that build them. 45 * <p> 46 * A building code model when executed will construct the same code model it was transformed from. 47 * Such a building code model could be transformed to bytecode and stored in class files. 48 */ 49 public class OpBuilder { 50 51 static final JavaType J_C_E_EXTERNALIZED_OP = type(ExternalizedOp.class); 52 53 static final MethodRef DIALECT_FACTORY_OP_FACTORY = MethodRef.method(DialectFactory.class, "opFactory", 54 OpFactory.class); 55 56 static final MethodRef DIALECT_FACTORY_TYPE_ELEMENT_FACTORY = MethodRef.method(DialectFactory.class, "typeElementFactory", 57 TypeElementFactory.class); 58 59 static final MethodRef OP_FACTORY_CONSTRUCT = MethodRef.method(OpFactory.class, "constructOp", 60 Op.class, ExternalizedOp.class); 61 62 static final MethodRef TYPE_ELEMENT_FACTORY_CONSTRUCT = MethodRef.method(TypeElementFactory.class, "constructType", 63 TypeElement.class, ExternalizedTypeElement.class); 64 65 static final MethodRef BODY_BUILDER_OF = MethodRef.method(Body.Builder.class, "of", 66 Body.Builder.class, Body.Builder.class, FunctionType.class); 67 68 static final MethodRef BODY_BUILDER_ENTRY_BLOCK = MethodRef.method(Body.Builder.class, "entryBlock", 69 Block.Builder.class); 70 71 // instance varargs 72 static final MethodRef BLOCK_BUILDER_SUCCESSOR = MethodRef.method(Block.Builder.class, "successor", 73 Block.Reference.class, Value[].class); 74 75 static final MethodRef BLOCK_BUILDER_OP = MethodRef.method(Block.Builder.class, "op", 76 Op.Result.class, Op.class); 77 78 // instance varargs 79 static final MethodRef BLOCK_BUILDER_BLOCK = MethodRef.method(Block.Builder.class, "block", 80 Block.Builder.class, TypeElement[].class); 81 82 static final MethodRef BLOCK_BUILDER_PARAMETER = MethodRef.method(Block.Builder.class, "parameter", 83 Block.Parameter.class, TypeElement.class); 84 85 // static varargs 86 static final MethodRef FUNCTION_TYPE_FUNCTION_TYPE = MethodRef.method(CoreType.class, "functionType", 87 FunctionType.class, TypeElement.class, TypeElement[].class); 88 89 90 static final JavaType J_U_LIST = type(List.class); 91 92 static final MethodRef LIST_OF_ARRAY = MethodRef.method(J_U_LIST, "of", 93 J_U_LIST, array(J_L_OBJECT, 1)); 94 95 static final JavaType J_U_MAP = type(Map.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_ARRAY = MethodRef.method(J_U_MAP, "of", 103 J_U_MAP, array(J_U_MAP_ENTRY, 1)); 104 105 106 static final JavaType EX_TYPE_ELEM = type(ExternalizedTypeElement.class); 107 108 static final MethodRef EX_TYPE_ELEM_OF_LIST = MethodRef.method(EX_TYPE_ELEM, "of", 109 EX_TYPE_ELEM, J_L_STRING, J_U_LIST); 110 111 112 static final JavaType J_C_LOCATION = type(Location.class); 113 114 static final MethodRef LOCATION_FROM_STRING = MethodRef.method(J_C_LOCATION, "fromString", 115 J_C_LOCATION, J_L_STRING); 116 117 static final FunctionType EXTERNALIZED_OP_F_TYPE = functionType( 118 J_C_E_EXTERNALIZED_OP, 119 J_L_STRING, 120 J_C_LOCATION, 121 J_U_LIST, 122 J_U_LIST, 123 type(TypeElement.class), 124 J_U_MAP, 125 J_U_LIST); 126 127 static final FunctionType BUILDER_F_TYPE = functionType(type(Op.class)); 128 129 130 final Map<Value, Value> valueMap; 131 132 final Map<Block, Value> blockMap; 133 134 final Map<ExternalizedTypeElement, Value> exTypeElementMap; 135 136 final Map<TypeElement, Value> typeElementMap; 137 138 final Block.Builder builder; 139 140 final Value dialectFactory; 141 142 final Value opFactory; 143 144 final Value typeElementFactory; 145 146 /** 147 * Transform the given code model to one that builds it. 148 * <p> 149 * This method initially applies the function {@code dialectFactoryF} to 150 * the block builder that is used to build resulting code model. The result 151 * is a dialect factory value which is subsequently used to build operations 152 * that construct type elements and operations present in the given code model. 153 * 154 * @param op the code model. 155 * @param dialectFactoryF a function that builds code items to produce a dialect factory value. 156 * @return the building code model. 157 */ 158 public static FuncOp createBuilderFunction(Op op, Function<Block.Builder, Value> dialectFactoryF) { 159 return new OpBuilder(dialectFactoryF).build(op); 160 } 161 162 OpBuilder(Function<Block.Builder, Value> dialectFactoryF) { 163 this.valueMap = new HashMap<>(); 164 this.blockMap = new HashMap<>(); 165 this.exTypeElementMap = new HashMap<>(); 166 this.typeElementMap = new HashMap<>(); 167 168 Body.Builder body = Body.Builder.of(null, BUILDER_F_TYPE); 169 this.builder = body.entryBlock(); 170 this.dialectFactory = dialectFactoryF.apply(builder); 171 this.opFactory = builder.op(invoke(DIALECT_FACTORY_OP_FACTORY, dialectFactory)); 172 this.typeElementFactory = builder.op(invoke(DIALECT_FACTORY_TYPE_ELEMENT_FACTORY, dialectFactory)); 173 } 174 175 FuncOp build(Op op) { 176 Value ancestorBody = builder.op(constant(type(Body.Builder.class), null)); 177 Value result = buildOp(ancestorBody, op); 178 // seal op 179 builder.op(invoke(MethodRef.method(Op.class, "seal", void.class), result)); 180 builder.op(return_(result)); 181 182 return func("builder." + op.opName(), builder.parentBody()); 183 } 184 185 186 Value buildOp(Value ancestorBody, Op inputOp) { 187 List<Value> bodies = new ArrayList<>(); 188 for (Body inputBody : inputOp.bodies()) { 189 Value body = buildBody(ancestorBody, inputBody); 190 bodies.add(body); 191 } 192 193 List<Value> operands = new ArrayList<>(); 194 for (Value inputOperand : inputOp.operands()) { 195 Value operand = valueMap.get(inputOperand); 196 operands.add(operand); 197 } 198 199 List<Value> successors = new ArrayList<>(); 200 for (Block.Reference inputSuccessor : inputOp.successors()) { 201 List<Value> successorArgs = new ArrayList<>(); 202 for (Value inputOperand : inputSuccessor.arguments()) { 203 Value operand = valueMap.get(inputOperand); 204 successorArgs.add(operand); 205 } 206 Value referencedBlock = blockMap.get(inputSuccessor.targetBlock()); 207 208 List<Value> args = new ArrayList<>(); 209 args.add(referencedBlock); 210 args.addAll(successorArgs); 211 Value successor = builder.op(invoke( 212 InvokeOp.InvokeKind.INSTANCE, true, 213 BLOCK_BUILDER_SUCCESSOR.type().returnType(), 214 BLOCK_BUILDER_SUCCESSOR, args)); 215 successors.add(successor); 216 } 217 218 Value opDef = buildOpDefinition( 219 inputOp, 220 inputOp.opName(), 221 inputOp.location(), 222 operands, 223 successors, 224 inputOp.resultType(), 225 inputOp.externalize(), 226 bodies); 227 return builder.op(invoke(OP_FACTORY_CONSTRUCT, opFactory, opDef)); 228 } 229 230 231 Value buildOpDefinition(Op inputOp, 232 String name, 233 Location location, 234 List<Value> operands, 235 List<Value> successors, 236 TypeElement resultType, 237 Map<String, Object> attributes, 238 List<Value> bodies) { 239 List<Value> args = List.of( 240 builder.op(constant(J_L_STRING, name)), 241 buildLocation(location), 242 buildList(type(Value.class), operands), 243 buildList(type(Block.Reference.class), successors), 244 buildType(resultType), 245 buildAttributeMap(inputOp, attributes), 246 buildList(type(Body.Builder.class), bodies)); 247 return builder.op(new_(ConstructorRef.constructor(EXTERNALIZED_OP_F_TYPE), args)); 248 } 249 250 Value buildLocation(Location l) { 251 if (l == null) { 252 return builder.op(constant(J_C_LOCATION, null)); 253 } else { 254 return builder.op(invoke(LOCATION_FROM_STRING, 255 builder.op(constant(J_L_STRING, l.toString())))); 256 } 257 } 258 259 Value buildBody(Value ancestorBodyValue, Body inputBody) { 260 Value yieldType = buildType(inputBody.yieldType()); 261 Value bodyType = builder.op(invoke( 262 InvokeOp.InvokeKind.STATIC, true, 263 FUNCTION_TYPE_FUNCTION_TYPE.type().returnType(), 264 FUNCTION_TYPE_FUNCTION_TYPE, List.of(yieldType))); 265 Value body = builder.op(invoke(BODY_BUILDER_OF, ancestorBodyValue, bodyType)); 266 267 Value entryBlock = null; 268 for (Block inputBlock : inputBody.blocks()) { 269 Value block; 270 if (inputBlock.isEntryBlock()) { 271 block = entryBlock = builder.op(invoke(BODY_BUILDER_ENTRY_BLOCK, body)); 272 } else { 273 assert entryBlock != null; 274 block = builder.op(invoke(InvokeOp.InvokeKind.INSTANCE, true, 275 BLOCK_BUILDER_BLOCK.type().returnType(), 276 BLOCK_BUILDER_BLOCK, List.of(entryBlock))); 277 } 278 blockMap.put(inputBlock, block); 279 280 for (Block.Parameter inputP : inputBlock.parameters()) { 281 Value type = buildType(inputP.type()); 282 Value blockParameter = builder.op(invoke(BLOCK_BUILDER_PARAMETER, block, type)); 283 valueMap.put(inputP, blockParameter); 284 } 285 } 286 287 for (Block inputBlock : inputBody.blocks()) { 288 Value block = blockMap.get(inputBlock); 289 for (Op inputOp : inputBlock.ops()) { 290 Value op = buildOp(body, inputOp); 291 Value result = builder.op(invoke(BLOCK_BUILDER_OP, block, op)); 292 valueMap.put(inputOp.result(), result); 293 } 294 } 295 296 return body; 297 } 298 299 Value buildType(TypeElement _t) { 300 return typeElementMap.computeIfAbsent(_t, t -> { 301 Value exTypeElem = buildExternalizedType(t.externalize()); 302 return builder.op(invoke(TYPE_ELEMENT_FACTORY_CONSTRUCT, typeElementFactory, exTypeElem)); 303 }); 304 } 305 306 Value buildExternalizedType(ExternalizedTypeElement e) { 307 // Cannot use computeIfAbsent due to recursion 308 if (exTypeElementMap.get(e) instanceof Value v) { 309 return v; 310 } 311 312 List<Value> arguments = new ArrayList<>(); 313 for (ExternalizedTypeElement a : e.arguments()) { 314 arguments.add(buildExternalizedType(a)); 315 } 316 317 Value identifier = builder.op(constant(J_L_STRING, e.identifier())); 318 Value ve; 319 if (e.arguments().size() < 5) { 320 MethodRef elemOf = MethodRef.method(EX_TYPE_ELEM, "of", 321 EX_TYPE_ELEM, Stream.concat(Stream.of(J_L_STRING), 322 Collections.nCopies(e.arguments().size(), EX_TYPE_ELEM).stream()).toList()); 323 arguments.addFirst(identifier); 324 ve = builder.op(invoke(elemOf, arguments)); 325 } else { 326 Value list = buildList(EX_TYPE_ELEM, arguments); 327 ve = builder.op(invoke(EX_TYPE_ELEM_OF_LIST, identifier, list)); 328 } 329 330 exTypeElementMap.put(e, ve); 331 return ve; 332 } 333 334 Value buildAttributeMap(Op inputOp, Map<String, Object> attributes) { 335 List<Value> keysAndValues = new ArrayList<>(); 336 for (Map.Entry<String, Object> entry : attributes.entrySet()) { 337 Value key = builder.op(constant(J_L_STRING, entry.getKey())); 338 Value value = buildAttributeValue(entry.getValue()); 339 keysAndValues.add(key); 340 keysAndValues.add(value); 341 } 342 return buildMap(J_L_STRING, J_L_OBJECT, keysAndValues); 343 } 344 345 Value buildAttributeValue(Object value) { 346 return switch (value) { 347 case Boolean v -> { 348 yield builder.op(constant(BOOLEAN, value)); 349 } 350 case Byte v -> { 351 yield builder.op(constant(BYTE, value)); 352 } 353 case Short v -> { 354 yield builder.op(constant(SHORT, value)); 355 } 356 case Character v -> { 357 yield builder.op(constant(CHAR, value)); 358 } 359 case Integer v -> { 360 yield builder.op(constant(INT, value)); 361 } 362 case Long v -> { 363 yield builder.op(constant(LONG, value)); 364 } 365 case Float v -> { 366 yield builder.op(constant(FLOAT, value)); 367 } 368 case Double v -> { 369 yield builder.op(constant(DOUBLE, value)); 370 } 371 case Class<?> v -> { 372 yield buildType(JavaType.type(v)); 373 } 374 case String s -> { 375 yield builder.op(constant(J_L_STRING, value)); 376 } 377 case TypeElement f -> { 378 yield buildType(f); 379 } 380 case InvokeOp.InvokeKind ik -> { 381 FieldRef enumValueRef = FieldRef.field(InvokeOp.InvokeKind.class, ik.name(), InvokeOp.InvokeKind.class); 382 yield builder.op(fieldLoad(enumValueRef)); 383 } 384 case Object o when value == ExternalizedOp.NULL_ATTRIBUTE_VALUE -> { 385 yield builder.op(fieldLoad(FieldRef.field(ExternalizedOp.class, 386 "NULL_ATTRIBUTE_VALUE", Object.class))); 387 } 388 default -> { 389 // @@@ use the result of value.toString()? 390 throw new UnsupportedOperationException("Unsupported attribute value: " + value); 391 } 392 }; 393 } 394 395 396 Value buildMap(JavaType keyType, JavaType valueType, List<Value> keysAndValues) { 397 JavaType mapType = parameterized(J_U_MAP, keyType, valueType); 398 if (keysAndValues.size() < 21) { 399 MethodRef mapOf = MethodRef.method(J_U_MAP, "of", 400 J_U_MAP, Collections.nCopies(keysAndValues.size(), J_L_OBJECT)); 401 return builder.op(invoke(mapType, mapOf, keysAndValues)); 402 } else { 403 JavaType mapEntryType = parameterized(J_U_MAP_ENTRY, keyType, valueType); 404 List<Value> elements = new ArrayList<>(keysAndValues.size() / 2); 405 for (int i = 0; i < keysAndValues.size(); i += 2) { 406 Value key = keysAndValues.get(i); 407 Value value = keysAndValues.get(i + 1); 408 Value entry = builder.op(invoke(mapEntryType, MAP_ENTRY, key, value)); 409 elements.add(entry); 410 } 411 Value array = buildArray(mapEntryType, elements); 412 return builder.op(invoke(mapType, MAP_OF_ARRAY, array)); 413 } 414 } 415 416 417 Value buildList(JavaType elementType, List<Value> elements) { 418 JavaType listType = parameterized(J_U_LIST, elementType); 419 if (elements.size() < 11) { 420 MethodRef listOf = MethodRef.method(J_U_LIST, "of", 421 J_U_LIST, Collections.nCopies(elements.size(), J_L_OBJECT)); 422 return builder.op(invoke(listType, listOf, elements)); 423 } else { 424 Value array = buildArray(elementType, elements); 425 return builder.op(invoke(listType, LIST_OF_ARRAY, array)); 426 } 427 } 428 429 430 Value buildArray(JavaType elementType, List<Value> elements) { 431 Value array = builder.op(newArray(JavaType.array(elementType), 432 builder.op(constant(INT, elements.size())))); 433 for (int i = 0; i < elements.size(); i++) { 434 builder.op(arrayStoreOp( 435 array, 436 builder.op(constant(INT, i)), 437 elements.get(i))); 438 } 439 return array; 440 } 441 }