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.
  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 /*
 25  * @test
 26  * @modules jdk.incubator.code
 27  * @run junit CoreBinaryOpsTest
 28  * @run junit/othervm -Dbabylon.ssa=cytron CoreBinaryOpsTest
 29  */
 30 
 31 import jdk.incubator.code.Op;
 32 import jdk.incubator.code.dialect.core.CoreType;
 33 import org.junit.jupiter.api.Named;
 34 import org.junit.jupiter.api.extension.ExtensionContext;
 35 import org.junit.jupiter.api.function.ThrowingSupplier;
 36 import org.junit.jupiter.params.ParameterizedTest;
 37 import org.junit.jupiter.params.provider.Arguments;
 38 import org.junit.jupiter.params.provider.ArgumentsProvider;
 39 import org.junit.jupiter.params.provider.ArgumentsSource;
 40 
 41 import java.lang.annotation.ElementType;
 42 import java.lang.annotation.Retention;
 43 import java.lang.annotation.RetentionPolicy;
 44 import java.lang.annotation.Target;
 45 import java.lang.invoke.MethodHandle;
 46 import java.lang.invoke.MethodHandles;
 47 import java.lang.invoke.MethodType;
 48 import java.lang.reflect.AccessFlag;
 49 import java.lang.reflect.Method;
 50 import java.lang.reflect.Parameter;
 51 import jdk.incubator.code.OpTransformer;
 52 import jdk.incubator.code.TypeElement;
 53 import jdk.incubator.code.analysis.SSA;
 54 import jdk.incubator.code.bytecode.BytecodeGenerator;
 55 import jdk.incubator.code.interpreter.Interpreter;
 56 import jdk.incubator.code.dialect.core.CoreOp;
 57 import jdk.incubator.code.dialect.core.FunctionType;
 58 import jdk.incubator.code.dialect.java.JavaType;
 59 import jdk.incubator.code.CodeReflection;
 60 import java.util.*;
 61 import java.util.stream.Stream;
 62 
 63 import static org.junit.jupiter.api.Assertions.*;
 64 
 65 public class CoreBinaryOpsTest {
 66 
 67     @CodeReflection
 68     @SupportedTypes(TypeList.INTEGRAL_BOOLEAN)
 69     static int and(int left, int right) {
 70         return left & right;
 71     }
 72 
 73     @CodeReflection
 74     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
 75     static int add(int left, int right) {
 76         return left + right;
 77     }
 78 
 79     @CodeReflection
 80     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
 81     static int div(int left, int right) {
 82         return left / right;
 83     }
 84 
 85     @CodeReflection
 86     @SupportedTypes(TypeList.INT_LONG)
 87     static int leftShift(int left, int right) {
 88         return left << right;
 89     }
 90 
 91     @CodeReflection
 92     @Direct
 93     static int leftShiftIL(int left, long right) {
 94         return left << right;
 95     }
 96 
 97     @CodeReflection
 98     @Direct
 99     static long leftShiftLI(long left, int right) {
100         return left << right;
101     }
102 
103     @CodeReflection
104     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
105     static int mod(int left, int right) {
106         return left % right;
107     }
108 
109     @CodeReflection
110     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
111     static int mul(int left, int right) {
112         return left * right;
113     }
114 
115     @CodeReflection
116     @SupportedTypes(TypeList.INTEGRAL_BOOLEAN)
117     static int or(int left, int right) {
118         return left | right;
119     }
120 
121     @CodeReflection
122     @SupportedTypes(TypeList.INT_LONG)
123     static int signedRightShift(int left, int right) {
124         return left >> right;
125     }
126 
127     @CodeReflection
128     @Direct
129     static int signedRightShiftIL(int left, long right) {
130         return left >> right;
131     }
132 
133     @CodeReflection
134     @Direct
135     static long signedRightShiftLI(long left, int right) {
136         return left >> right;
137     }
138 
139     @CodeReflection
140     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
141     static int sub(int left, int right) {
142         return left - right;
143     }
144 
145     @CodeReflection
146     @SupportedTypes(TypeList.INT_LONG)
147     static int unsignedRightShift(int left, int right) {
148         return left >>> right;
149     }
150 
151     @CodeReflection
152     @Direct
153     static int unsignedRightShiftIL(int left, long right) {
154         return left >>> right;
155     }
156 
157     @CodeReflection
158     @Direct
159     static long unsignedRightShiftLI(long left, int right) {
160         return left >>> right;
161     }
162 
163     @CodeReflection
164     @SupportedTypes(TypeList.INTEGRAL_BOOLEAN)
165     static int xor(int left, int right) {
166         return left ^ right;
167     }
168 
169     @ParameterizedTest
170     @CodeReflectionExecutionSource
171     void test(CoreOp.FuncOp funcOp, Object left, Object right) {
172         Result interpret = runCatching(() -> interpret(left, right, funcOp));
173         Result bytecode = runCatching(() -> bytecode(left, right, funcOp));
174         assertResults(interpret, bytecode);
175     }
176 
177     @Retention(RetentionPolicy.RUNTIME)
178     @Target(ElementType.METHOD)
179     @interface SupportedTypes {
180         TypeList value();
181     }
182 
183     enum TypeList {
184         INT_LONG(int.class, long.class),
185         INTEGRAL_BOOLEAN(int.class, long.class, byte.class, short.class, char.class, boolean.class),
186         INTEGRAL_FLOATING_POINT(int.class, long.class, byte.class, short.class, char.class, float.class, double.class);
187 
188         private final Class<?>[] types;
189 
190         TypeList(Class<?>... types) {
191             this.types = types;
192         }
193 
194         public Class<?>[] types() {
195             return types;
196         }
197     }
198 
199     // mark as "do not transform"
200     @Retention(RetentionPolicy.RUNTIME)
201     @Target(ElementType.METHOD)
202     @interface Direct {
203     }
204 
205     @Retention(RetentionPolicy.RUNTIME)
206     @Target(ElementType.METHOD)
207     @ArgumentsSource(CodeReflectionSourceProvider.class)
208     @interface CodeReflectionExecutionSource {
209     }
210 
211     static class CodeReflectionSourceProvider implements ArgumentsProvider {
212         private static final Map<JavaType, List<?>> INTERESTING_INPUTS = Map.of(
213                 // explicit type parameters to ensure boxing results in the expected type
214                 JavaType.INT, List.<Integer>of(Integer.MIN_VALUE, Integer.MAX_VALUE, 1, 0, -1),
215                 JavaType.LONG, List.<Long>of(Long.MIN_VALUE, Long.MAX_VALUE, 1L, 0L, -1L),
216                 JavaType.BYTE, List.<Byte>of(Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 1, (byte) 0, (byte) -1),
217                 JavaType.SHORT, List.<Short>of(Short.MIN_VALUE, Short.MAX_VALUE, (short) 1, (short) 0, (short) -1),
218                 JavaType.CHAR, List.<Character>of(Character.MIN_VALUE, Character.MAX_VALUE, (char) 1, (char) 0, (char) -1),
219                 JavaType.DOUBLE, List.<Double>of(Double.MIN_VALUE, Double.MAX_VALUE, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.MIN_NORMAL, 1d, 0d, -1d),
220                 JavaType.FLOAT, List.<Float>of(Float.MIN_VALUE, Float.MAX_VALUE, Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Float.MIN_NORMAL, 1f, 0f, -1f),
221                 JavaType.BOOLEAN, List.<Boolean>of(true, false)
222         );
223 
224         @Override
225         public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) {
226             Method testMethod = extensionContext.getRequiredTestMethod();
227             return codeReflectionMethods(extensionContext.getRequiredTestClass())
228                     .flatMap(method -> {
229                         CoreOp.FuncOp funcOp = Op.ofMethod(method).orElseThrow(
230                                 () -> new IllegalStateException("Expected code model to be present for method " + method)
231                         );
232                         SupportedTypes supportedTypes = method.getAnnotation(SupportedTypes.class);
233                         if (method.isAnnotationPresent(Direct.class)) {
234                             if (supportedTypes != null) {
235                                 throw new IllegalArgumentException("Direct should not be combined with SupportedTypes");
236                             }
237                             return Stream.of(funcOp);
238                         }
239                         if (supportedTypes == null || supportedTypes.value().types().length == 0) {
240                             throw new IllegalArgumentException("Missing supported types");
241                         }
242                         return Arrays.stream(supportedTypes.value().types())
243                                 .map(type -> retype(funcOp, type));
244                     })
245                     .flatMap(transformedFunc -> argumentsForMethod(transformedFunc, testMethod));
246         }
247 
248         private static <T> Stream<List<T>> cartesianProduct(List<List<? extends T>> source) {
249             if (source.isEmpty()) {
250                 return Stream.of(new ArrayList<>());
251             }
252             return source.getFirst().stream()
253                     .flatMap(e -> cartesianProduct(source.subList(1, source.size())).map(l -> {
254                         ArrayList<T> newList = new ArrayList<>(l);
255                         newList.add(e);
256                         return newList;
257                     }));
258         }
259 
260         private static CoreOp.FuncOp retype(CoreOp.FuncOp original, Class<?> newType) {
261             JavaType type = JavaType.type(newType);
262             FunctionType functionType = original.invokableType();
263             if (functionType.parameterTypes().stream().allMatch(t -> t.equals(type))) {
264                 return original; // already expected type
265             }
266             if (functionType.parameterTypes().stream().distinct().count() != 1) {
267                 original.writeTo(System.err);
268                 throw new IllegalArgumentException("Only FuncOps with exactly one distinct parameter type are supported");
269             }
270             // if the return type does not match the input types, we keep it
271             TypeElement retType = functionType.returnType().equals(functionType.parameterTypes().getFirst())
272                     ? type
273                     : functionType.returnType();
274             return CoreOp.func(original.funcName(), CoreType.functionType(retType, type, type))
275                     .body(builder -> builder.transformBody(original.body(), builder.parameters(), OpTransformer.COPYING_TRANSFORMER)
276                     );
277         }
278 
279         private static Stream<Arguments> argumentsForMethod(CoreOp.FuncOp funcOp, Method testMethod) {
280             Parameter[] testMethodParameters = testMethod.getParameters();
281             List<TypeElement> funcParameters = funcOp.invokableType().parameterTypes();
282             if (testMethodParameters.length - 1 != funcParameters.size()) {
283                 throw new IllegalArgumentException("method " + testMethod + " does not take the correct number of parameters");
284             }
285             if (testMethodParameters[0].getType() != CoreOp.FuncOp.class) {
286                 throw new IllegalArgumentException("method " + testMethod + " does not take a leading FuncOp argument");
287             }
288             Named<CoreOp.FuncOp> opNamed = Named.of(funcOp.funcName() + "{" + funcOp.invokableType() + "}", funcOp);
289             MethodHandles.Lookup lookup = MethodHandles.lookup();
290             for (int i = 1; i < testMethodParameters.length; i++) {
291                 Class<?> resolved = resolveParameter(funcParameters.get(i - 1), lookup);
292                 if (!isCompatible(resolved, testMethodParameters[i].getType())) {
293                     System.out.println(testMethod + " does not accept inputs of type " + resolved + " at index " + i);
294                     return Stream.empty();
295                 }
296             }
297             List<List<?>> allInputs = new ArrayList<>();
298             for (TypeElement parameterType : funcParameters) {
299                 allInputs.add(INTERESTING_INPUTS.get((JavaType) parameterType));
300             }
301             return cartesianProduct(allInputs)
302                     .map(objects -> {
303                         objects.add(opNamed);
304                         return objects.reversed().toArray(); // reverse so FuncOp is at the beginning
305                     })
306                     .map(Arguments::of);
307         }
308 
309         private static Class<?> resolveParameter(TypeElement typeElement, MethodHandles.Lookup lookup) {
310             try {
311                 return (Class<?>)((JavaType) typeElement).erasure().resolve(lookup);
312             } catch (ReflectiveOperationException e) {
313                 throw new RuntimeException(e);
314             }
315         }
316 
317         // check whether elements of type sourceType can be passed to a parameter of parameterType
318         private static boolean isCompatible(Class<?> sourceType, Class<?> parameterType) {
319             return wrapped(parameterType).isAssignableFrom(wrapped(sourceType));
320         }
321 
322         private static Class<?> wrapped(Class<?> target) {
323             return MethodType.methodType(target).wrap().returnType();
324         }
325 
326         private static Stream<Method> codeReflectionMethods(Class<?> testClass) {
327             return Arrays.stream(testClass.getDeclaredMethods())
328                     .filter(method -> method.accessFlags().contains(AccessFlag.STATIC))
329                     .filter(method -> method.isAnnotationPresent(CodeReflection.class));
330         }
331 
332     }
333 
334     private static Object interpret(Object left, Object right, CoreOp.FuncOp op) {
335         return Interpreter.invoke(MethodHandles.lookup(), op, left, right);
336     }
337 
338     private static Object bytecode(Object left, Object right, CoreOp.FuncOp op) throws Throwable {
339         CoreOp.FuncOp func = SSA.transform(op.transform(OpTransformer.LOWERING_TRANSFORMER));
340         MethodHandle handle = BytecodeGenerator.generate(MethodHandles.lookup(), func);
341         return handle.invoke(left, right);
342     }
343 
344     private static void assertResults(Result first, Result second) {
345         System.out.println("first: " + first);
346         System.out.println("second: " + second);
347         // either the same error occurred on both or no error occurred
348         if (first.throwable != null || second.throwable != null) {
349             assertNotNull(first.throwable, () -> "only second threw an exception: " + second.throwable);
350             assertNotNull(second.throwable, () -> "only first threw an exception: " + first.throwable);
351             if (first.throwable.getClass() != second.throwable.getClass()) {
352                 first.throwable.printStackTrace();
353                 second.throwable.printStackTrace();
354                 fail("Different exceptions were thrown");
355             }
356             return;
357         }
358         // otherwise, both results should be non-null and equals
359         assertNotNull(first.onSuccess);
360         assertEquals(first.onSuccess, second.onSuccess);
361     }
362 
363     private static <T> Result runCatching(ThrowingSupplier<T> supplier) {
364         Object value = null;
365         Throwable interpretThrowable = null;
366         try {
367             value = supplier.get();
368         } catch (Throwable t) {
369             interpretThrowable = t;
370         }
371         return new Result(value, interpretThrowable);
372     }
373 
374     record Result(Object onSuccess, Throwable throwable) {
375     }
376 
377 }