1 /*
  2  * Copyright (c) 2025, 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.*;
 25 import jdk.incubator.code.Reflect;
 26 import jdk.incubator.code.analysis.NormalizeBlocksTransformer;
 27 import jdk.incubator.code.analysis.SSA;
 28 import jdk.incubator.code.dialect.core.CoreOp;
 29 import jdk.incubator.code.dialect.java.JavaOp;
 30 import jdk.incubator.code.extern.OpParser;
 31 import jdk.incubator.code.extern.OpWriter;
 32 
 33 import java.io.StringWriter;
 34 import java.lang.invoke.MethodHandles;
 35 import java.lang.reflect.Member;
 36 import java.lang.reflect.Method;
 37 import java.util.HashSet;
 38 import java.util.function.Predicate;
 39 
 40 public class CodeReflectionTester {
 41 
 42     public static void main(String[] args) throws ReflectiveOperationException {
 43         if (args.length != 1) {
 44             System.err.println("Usage: CodeReflectionTester <classname>");
 45             System.exit(1);
 46         }
 47         Class<?> clazz = Class.forName(args[0]);
 48 
 49         Method lookupMethod = clazz.getMethod("lookup");
 50         MethodHandles.Lookup lookup = (MethodHandles.Lookup) lookupMethod.invoke(null);
 51 
 52         Method opConstantsMethod = clazz.getMethod("opConstants");
 53         @SuppressWarnings("unchecked")
 54         Predicate<Op> opConstants = (Predicate<Op>) opConstantsMethod.invoke(null);
 55 
 56         for (Method m : clazz.getDeclaredMethods()) {
 57             check(lookup, opConstants, m);
 58         }
 59     }
 60 
 61     static void check(MethodHandles.Lookup l, Predicate<Op> opConstants, Method method) throws ReflectiveOperationException {
 62         if (!method.isAnnotationPresent(Reflect.class)) {
 63             return;
 64         }
 65 
 66         for (EvaluatedModel em : getModels(method)) {
 67             CoreOp.FuncOp f = Op.ofMethod(method).orElseThrow(() ->
 68                     new AssertionError("No code model for reflective method"));
 69             f = evaluate(l, opConstants, f, em.ssa());
 70 
 71             String actual = canonicalizeModel(method, f);
 72             System.out.println(actual);
 73             String expected = canonicalizeModel(method, em.value());
 74             if (!actual.equals(expected)) {
 75                 throw new AssertionError(String.format("Bad code model\nFound:\n%s\n\nExpected:\n%s", actual, expected));
 76             }
 77         }
 78     }
 79 
 80     static EvaluatedModel[] getModels(Method method) {
 81         EvaluatedModels ems = method.getAnnotation(EvaluatedModels.class);
 82         if (ems != null) {
 83             return ems.value();
 84         }
 85 
 86         EvaluatedModel em = method.getAnnotation(EvaluatedModel.class);
 87         if (em != null) {
 88             return new EvaluatedModel[] { em };
 89         }
 90 
 91         throw new AssertionError("No @EvaluatedModel annotation found on reflective method");
 92     }
 93 
 94     static CoreOp.FuncOp evaluate(MethodHandles.Lookup l, Predicate<Op> opConstants, CoreOp.FuncOp f, boolean ssa) {
 95         f = f.transform(CodeTransformer.LOWERING_TRANSFORMER);
 96 
 97         if (ssa) {
 98             f = SSA.transform(f);
 99         }
100 
101         f = PartialEvaluator.evaluate(l, opConstants, new HashSet<>(), f);
102 
103         return cleanUp(f);
104     }
105 
106     static CoreOp.FuncOp cleanUp(CoreOp.FuncOp f) {
107         return removeUnusedOps(NormalizeBlocksTransformer.transform(f));
108     }
109 
110     static CoreOp.FuncOp removeUnusedOps(CoreOp.FuncOp f) {
111         Predicate<Op> unused = op -> (op instanceof Op.Pure || op instanceof CoreOp.VarOp) &&
112                 op.result().uses().isEmpty();
113         while (f.elements().skip(1).anyMatch(ce -> ce instanceof Op op && unused.test(op))) {
114             f = f.transform((block, op) -> {
115                 if (!unused.test(op)) {
116                     block.op(op);
117                 }
118                 return block;
119             });
120         }
121         return f;
122     }
123 
124     // serializes dropping location information, parses, and then serializes, dropping location information
125     static String canonicalizeModel(Member m, Op o) {
126         return canonicalizeModel(m, serialize(o));
127     }
128 
129     // parses, and then serializes, dropping location information
130     static String canonicalizeModel(Member m, String d) {
131         Op o;
132         try {
133             o = OpParser.fromString(JavaOp.JAVA_DIALECT_FACTORY, d).get(0);
134         } catch (Exception e) {
135             throw new IllegalStateException(m.toString(), e);
136         }
137         return serialize(o);
138     }
139 
140     // serializes, dropping location information
141     static String serialize(Op o) {
142         StringWriter w = new StringWriter();
143         OpWriter.writeTo(w, o, OpWriter.LocationOption.DROP_LOCATION);
144         return w.toString();
145     }
146 }