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 import jdk.incubator.code.Reflect;
25 import jdk.incubator.code.CodeTransformer;
26 import jdk.incubator.code.Op;
27 import jdk.incubator.code.dialect.core.CoreOp;
28 import jdk.incubator.code.interpreter.Interpreter;
29 import org.junit.jupiter.api.Assertions;
30 import org.junit.jupiter.api.Test;
31
32 import java.lang.invoke.MethodHandles;
33 import java.lang.reflect.Method;
34 import java.util.List;
35 import java.util.Optional;
36 import java.util.stream.Stream;
37
38 /*
39 * @test
40 * @modules jdk.incubator.code
41 * @run junit TestEnhancedForOp
42 * @run main Unreflect TestEnhancedForOp
43 * @run junit TestEnhancedForOp
44 */
45
46 public class TestEnhancedForOp {
47
48 @Reflect
49 public static int f() {
50 int j = 0;
51 for (int i : List.of(1, 2, 3, 4)) {
52 j += i;
53 }
54 return j;
55 }
56
57 static CoreOp.FuncOp getFuncOp(String name) {
58 Optional<Method> om = Stream.of(TestEnhancedForOp.class.getDeclaredMethods())
59 .filter(m -> m.getName().equals(name))
60 .findFirst();
61
62 Method m = om.get();
63 return Op.ofMethod(m).get();
64 }
65
66 @Test
67 public void testf() {
68 CoreOp.FuncOp f = getFuncOp("f");
69
70 System.out.println(f.toText());
71
72 CoreOp.FuncOp lf = f.transform(CodeTransformer.LOWERING_TRANSFORMER);
73
74 System.out.println(lf.toText());
75
76 Assertions.assertEquals(f(), Interpreter.invoke(MethodHandles.lookup(), lf));
77 }
78
79
80 @Reflect
81 public static int array(int[] a) {
82 int j = 0;
83 for (int i : a) {
84 j += i;
85 }
86 return j;
87 }
88
89 @Test
90 public void testArray() {
91 CoreOp.FuncOp f = getFuncOp("array");
92
93 System.out.println(f.toText());
94
95 CoreOp.FuncOp lf = f.transform(CodeTransformer.LOWERING_TRANSFORMER);
96
97 System.out.println(lf.toText());
98
99 int[] ia = new int[] {1, 2, 3, 4};
100 Assertions.assertEquals(array(ia), Interpreter.invoke(MethodHandles.lookup(), lf, ia));
101 }
102 }