You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2026/08/22 10:57:00 UTC
(groovy) 01/03: GROOVY-12284: Specialize indy sameClasses guards for arity 1-4
This is an automated email from the ASF dual-hosted git repository.
daniellansun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit d470b2588c2c2ef9ad213cffe23f0dca2995ce55
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sat Aug 15 17:32:38 2026 +0900
GROOVY-12284: Specialize indy sameClasses guards for arity 1-4
---
.../v8/IndyGuardsFiltersAndSignatures.java | 33 +++-
.../org/codehaus/groovy/vmplugin/v8/Selector.java | 87 +++++++---
.../vmplugin/v8/IndySameClassesGuardTest.groovy | 147 ++++++++++++++++
subprojects/performance/README.adoc | 21 +++
.../groovy/bench/SameClassesGuardBench.groovy | 163 ++++++++++++++++++
.../groovy/bench/SameClassesGuardMhBench.java | 188 +++++++++++++++++++++
6 files changed, 618 insertions(+), 21 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyGuardsFiltersAndSignatures.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyGuardsFiltersAndSignatures.java
index 816210d3d5..2641d01660 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyGuardsFiltersAndSignatures.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/IndyGuardsFiltersAndSignatures.java
@@ -62,7 +62,8 @@ public class IndyGuardsFiltersAndSignatures {
* Shared guards, filters, constructors, and invokers used when assembling indy call paths.
*/
protected static final MethodHandle
- SAME_CLASS, SAME_CLASSES, SAME_MC, IS_NULL, NON_NULL,
+ SAME_CLASS, SAME_CLASSES, SAME_CLASSES_2, SAME_CLASSES_3, SAME_CLASSES_4,
+ SAME_MC, IS_NULL, NON_NULL,
UNWRAP_METHOD, UNWRAP_EXCEPTION,
HAS_CATEGORY_IN_CURRENT_THREAD_GUARD,
GROOVY_OBJECT_INVOKER, GROOVY_OBJECT_GET_PROPERTY, GROOVY_OBJECT_SET_PROPERTY, META_METHOD_INVOKER,
@@ -82,6 +83,9 @@ public class IndyGuardsFiltersAndSignatures {
try {
SAME_CLASS = LOOKUP.findStatic (IndyGuardsFiltersAndSignatures.class, "sameClass", MethodType.methodType(boolean.class, Class.class, Object.class));
SAME_CLASSES = LOOKUP.findStatic (IndyGuardsFiltersAndSignatures.class, "sameClasses", MethodType.methodType(boolean.class, Class[].class, Object[].class));
+ SAME_CLASSES_2 = LOOKUP.findStatic (IndyGuardsFiltersAndSignatures.class, "sameClasses", MethodType.methodType(boolean.class, Class.class, Class.class, Object.class, Object.class));
+ SAME_CLASSES_3 = LOOKUP.findStatic (IndyGuardsFiltersAndSignatures.class, "sameClasses", MethodType.methodType(boolean.class, Class.class, Class.class, Class.class, Object.class, Object.class, Object.class));
+ SAME_CLASSES_4 = LOOKUP.findStatic (IndyGuardsFiltersAndSignatures.class, "sameClasses", MethodType.methodType(boolean.class, Class.class, Class.class, Class.class, Class.class, Object.class, Object.class, Object.class, Object.class));
SAME_MC = LOOKUP.findStatic (IndyGuardsFiltersAndSignatures.class, "isSameMetaClass", MethodType.methodType(boolean.class, MetaClass.class, Object.class));
IS_NULL = LOOKUP.findStatic (IndyGuardsFiltersAndSignatures.class, "isNull", OBJECT_GUARD);
NON_NULL = LOOKUP.findStatic (Objects.class, "nonNull", MethodType.methodType(boolean.class, Object.class));
@@ -239,4 +243,31 @@ public class IndyGuardsFiltersAndSignatures {
}
return true;
}
+
+ /**
+ * Two-argument same-class guard used by hot indy sites so
+ * {@code asCollector(Object[].class, n)} does not allocate an {@code Object[]}
+ * on every invocation. {@code Selector} binds the expected classes with a
+ * single {@link MethodHandles#insertArguments} call.
+ */
+ public static boolean sameClasses(Class<?> c0, Class<?> c1, Object o0, Object o1) {
+ return o0 != null && o1 != null && o0.getClass() == c0 && o1.getClass() == c1;
+ }
+
+ /**
+ * Three-argument same-class guard; see {@link #sameClasses(Class, Class, Object, Object)}.
+ */
+ public static boolean sameClasses(Class<?> c0, Class<?> c1, Class<?> c2, Object o0, Object o1, Object o2) {
+ return o0 != null && o1 != null && o2 != null
+ && o0.getClass() == c0 && o1.getClass() == c1 && o2.getClass() == c2;
+ }
+
+ /**
+ * Four-argument same-class guard; see {@link #sameClasses(Class, Class, Object, Object)}.
+ */
+ public static boolean sameClasses(Class<?> c0, Class<?> c1, Class<?> c2, Class<?> c3,
+ Object o0, Object o1, Object o2, Object o3) {
+ return o0 != null && o1 != null && o2 != null && o3 != null
+ && o0.getClass() == c0 && o1.getClass() == c1 && o2.getClass() == c2 && o3.getClass() == c3;
+ }
}
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
index 9a717fd814..dfe8c9e490 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
@@ -22,29 +22,17 @@ import groovy.lang.Closure;
import groovy.lang.ExpandoMetaClass;
import groovy.lang.GroovyInterceptable;
import groovy.lang.GroovyObject;
-import groovy.lang.MetaBeanProperty;
-import groovy.lang.MetaProperty;
import groovy.lang.GroovyRuntimeException;
import groovy.lang.GroovySystem;
+import groovy.lang.MetaBeanProperty;
import groovy.lang.MetaClass;
import groovy.lang.MetaClassImpl;
import groovy.lang.MetaClassImpl.MetaConstructor;
import groovy.lang.MetaMethod;
+import groovy.lang.MetaProperty;
import groovy.lang.MissingMethodException;
import groovy.lang.ProxyMetaClass;
import groovy.transform.Internal;
-import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodHandles;
-import java.lang.invoke.MethodType;
-import java.lang.reflect.Array;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Objects;
import org.codehaus.groovy.GroovyBugError;
import org.codehaus.groovy.reflection.CachedField;
import org.codehaus.groovy.reflection.CachedMethod;
@@ -68,6 +56,20 @@ import org.codehaus.groovy.runtime.wrappers.Wrapper;
import org.codehaus.groovy.vmplugin.VMPlugin;
import org.codehaus.groovy.vmplugin.VMPluginFactory;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Objects;
+import java.util.function.Predicate;
+
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.ARRAYLIST_CONSTRUCTOR;
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.BEAN_CONSTRUCTOR_PROPERTY_SETTER;
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.CLASS_FOR_NAME;
@@ -91,6 +93,9 @@ import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.NON
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.NULL_REF;
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SAME_CLASS;
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SAME_CLASSES;
+import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SAME_CLASSES_2;
+import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SAME_CLASSES_3;
+import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SAME_CLASSES_4;
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SAME_MC;
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SAM_CONVERSION;
import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.SET_PROPERTY;
@@ -1289,7 +1294,7 @@ public abstract class Selector {
handle = applyMopSwitchPoints(handle, fallback, receiver);
if (LOG_ENABLED) LOG.info("added class switch point guard");
- java.util.function.Predicate<Class<?>> nonFinalOrNullUnsafe = (t) -> {
+ Predicate<Class<?>> nonFinalOrNullUnsafe = (t) -> {
return !Modifier.isFinal(t.getModifiers())
|| TypeHelper.getUnboxedType(t).isPrimitive(); // GROOVY-11782
};
@@ -1314,11 +1319,11 @@ public abstract class Selector {
handle = MethodHandles.guardWithTest(test, handle, fallback);
}
} else if (Arrays.stream(pt).anyMatch(nonFinalOrNullUnsafe)) {
- MethodHandle test = SAME_CLASSES
- .bindTo(Arrays.stream(args).map(Object::getClass).toArray(Class[]::new))
- .asCollector(Object[].class, pt.length)
- .asType(MethodType.methodType(boolean.class, pt));
- handle = MethodHandles.guardWithTest(test, handle, fallback);
+ // Arity 0 never reaches here: anyMatch on an empty pt is false,
+ // and a receiver is always present. No same-class combinator is
+ // installed for a parameterless handle.
+ handle = MethodHandles.guardWithTest(
+ Selector.sameClassesGuard(args, handle.type()), handle, fallback);
if (LOG_ENABLED) LOG.info("added same-class argument check");
} else if (safeNavigationOrig) { // GROOVY-11126
MethodHandle test = NON_NULL.asType(MethodType.methodType(boolean.class, pt[0]));
@@ -1533,4 +1538,46 @@ public abstract class Selector {
}
return sender;
}
+
+ /**
+ * Specialised same-class guards for arities 1–4, stored at {@code [n - 1]}.
+ */
+ private static final MethodHandle[] SAME_CLASS_GUARDS = {
+ SAME_CLASS,
+ SAME_CLASSES_2,
+ SAME_CLASSES_3,
+ SAME_CLASSES_4
+ };
+
+ /**
+ * Builds a same-class guard that avoids {@code asCollector(Object[].class, n)}
+ * for the common 1–4 argument shapes (receiver plus 0–3 parameters).
+ * Expected classes are bound with a single {@link MethodHandles#insertArguments}
+ * (one adapter, not a chain of {@code bindTo}). The produced handle has type
+ * {@code callType.changeReturnType(boolean.class)} and returns {@code false}
+ * if any argument is {@code null} or has a different runtime class.
+ * <p>
+ * Arity 0 is not specialised; the caller does not install a guard in that
+ * case. If this helper is invoked with no parameters it falls through to
+ * the collector of an empty array, which returns {@code true}.
+ *
+ * @param args non-null arguments captured at link time; length matches {@code callType}
+ * @param callType the invocation handle type whose parameters the guard must accept
+ */
+ static MethodHandle sameClassesGuard(final Object[] args, final MethodType callType) {
+ int n = callType.parameterCount();
+ MethodType booleanType = callType.changeReturnType(boolean.class);
+ if (n >= 1 && n <= SAME_CLASS_GUARDS.length) {
+ Object[] classes = new Object[n];
+ for (int i = 0; i < n; i++) {
+ classes[i] = args[i].getClass();
+ }
+ return MethodHandles.insertArguments(SAME_CLASS_GUARDS[n - 1], 0, classes).asType(booleanType);
+ }
+ Class<?>[] classes = new Class<?>[n];
+ for (int i = 0; i < n; i++) {
+ classes[i] = args[i].getClass();
+ }
+ return SAME_CLASSES.bindTo(classes).asCollector(Object[].class, n).asType(booleanType);
+ }
}
diff --git a/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndySameClassesGuardTest.groovy b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndySameClassesGuardTest.groovy
new file mode 100644
index 0000000000..f1386fdbf5
--- /dev/null
+++ b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndySameClassesGuardTest.groovy
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.codehaus.groovy.vmplugin.v8
+
+import org.junit.jupiter.api.Test
+
+import java.lang.invoke.MethodType
+
+import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.sameClass
+import static org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures.sameClasses
+import static org.junit.jupiter.api.Assertions.assertEquals
+import static org.junit.jupiter.api.Assertions.assertFalse
+import static org.junit.jupiter.api.Assertions.assertTrue
+
+/**
+ * Guards produced for monomorphic indy sites must reject a changed argument
+ * class or a newly-null argument without allocating an {@code Object[]} collector
+ * on the 1–4 arity hot path.
+ */
+final class IndySameClassesGuardTest {
+
+ @Test
+ void 'sameClass rejects null and class change'() {
+ assertTrue sameClass(String, 'a')
+ assertFalse sameClass(String, 1)
+ assertFalse sameClass(String, null)
+ }
+
+ @Test
+ void 'array sameClasses covers empty match null and mismatch'() {
+ assertTrue sameClasses(new Class[0], new Object[0])
+ assertTrue sameClasses([String, Integer] as Class[], ['a', 1] as Object[])
+ assertFalse sameClasses([String, Integer] as Class[], ['a', null] as Object[])
+ assertFalse sameClasses([String, Integer] as Class[], [null, 1] as Object[])
+ assertFalse sameClasses([String, Integer] as Class[], ['a', 1L] as Object[])
+ assertFalse sameClasses([String, Integer] as Class[], [1, 1] as Object[])
+ }
+
+ @Test
+ void 'arity-2 sameClasses covers each conjunct'() {
+ assertTrue sameClasses(String, Integer, 'a', 1)
+ assertFalse sameClasses(String, Integer, null, 1)
+ assertFalse sameClasses(String, Integer, 'a', null)
+ assertFalse sameClasses(String, Integer, 1, 1)
+ assertFalse sameClasses(String, Integer, 'a', 1L)
+ }
+
+ @Test
+ void 'arity-3 sameClasses covers each conjunct'() {
+ assertTrue sameClasses(String, Integer, Long, 'a', 1, 2L)
+ assertFalse sameClasses(String, Integer, Long, null, 1, 2L)
+ assertFalse sameClasses(String, Integer, Long, 'a', null, 2L)
+ assertFalse sameClasses(String, Integer, Long, 'a', 1, null)
+ assertFalse sameClasses(String, Integer, Long, 1, 1, 2L)
+ assertFalse sameClasses(String, Integer, Long, 'a', 1L, 2L)
+ assertFalse sameClasses(String, Integer, Long, 'a', 1, 2)
+ }
+
+ @Test
+ void 'arity-4 sameClasses covers each conjunct'() {
+ assertTrue sameClasses(String, Integer, Long, Double, 'a', 1, 2L, 3d)
+ assertFalse sameClasses(String, Integer, Long, Double, null, 1, 2L, 3d)
+ assertFalse sameClasses(String, Integer, Long, Double, 'a', null, 2L, 3d)
+ assertFalse sameClasses(String, Integer, Long, Double, 'a', 1, null, 3d)
+ assertFalse sameClasses(String, Integer, Long, Double, 'a', 1, 2L, null)
+ assertFalse sameClasses(String, Integer, Long, Double, 1, 1, 2L, 3d)
+ assertFalse sameClasses(String, Integer, Long, Double, 'a', 1L, 2L, 3d)
+ assertFalse sameClasses(String, Integer, Long, Double, 'a', 1, 2, 3d)
+ assertFalse sameClasses(String, Integer, Long, Double, 'a', 1, 2L, 3f)
+ }
+
+ @Test
+ void 'sameClassesGuard arity 0 to 5 matches collector semantics'() {
+ def g0 = Selector.sameClassesGuard(new Object[0], MethodType.methodType(Object))
+ assertEquals(MethodType.methodType(boolean), g0.type())
+ assertTrue((boolean) g0.invokeWithArguments())
+
+ def g1 = Selector.sameClassesGuard(['recv'] as Object[], MethodType.methodType(Object, Object))
+ assertEquals(MethodType.methodType(boolean, Object), g1.type())
+ assertTrue((boolean) g1.invokeWithArguments('recv'))
+ assertFalse((boolean) g1.invokeWithArguments(1))
+ assertFalse((boolean) g1.invokeWithArguments((Object) null))
+
+ def g2 = Selector.sameClassesGuard(['recv', 'arg'] as Object[], MethodType.methodType(Object, Object, Object))
+ assertEquals(MethodType.methodType(boolean, Object, Object), g2.type())
+ assertTrue((boolean) g2.invokeWithArguments('recv', 'arg'))
+ assertFalse((boolean) g2.invokeWithArguments('recv', 1))
+ assertFalse((boolean) g2.invokeWithArguments('recv', null))
+ assertFalse((boolean) g2.invokeWithArguments(1, 'arg'))
+
+ def g3 = Selector.sameClassesGuard(['r', 1, 2L] as Object[], MethodType.methodType(Object, Object, Object, Object))
+ assertTrue((boolean) g3.invokeWithArguments('r', 1, 2L))
+ assertFalse((boolean) g3.invokeWithArguments('r', 1, null))
+ assertFalse((boolean) g3.invokeWithArguments('r', null, 2L))
+
+ def g4 = Selector.sameClassesGuard(['r', 1, 2L, 3d] as Object[], MethodType.methodType(Object, Object, Object, Object, Object))
+ assertTrue((boolean) g4.invokeWithArguments('r', 1, 2L, 3d))
+ assertFalse((boolean) g4.invokeWithArguments('r', 1, 2L, 'x'))
+ assertFalse((boolean) g4.invokeWithArguments(null, 1, 2L, 3d))
+
+ def g5 = Selector.sameClassesGuard(['r', 1, 2L, 3d, 'z'] as Object[],
+ MethodType.methodType(Object, Object, Object, Object, Object, Object))
+ assertTrue((boolean) g5.invokeWithArguments('r', 1, 2L, 3d, 'z'))
+ assertFalse((boolean) g5.invokeWithArguments('r', 1, 2L, 3d, 0))
+ assertFalse((boolean) g5.invokeWithArguments('r', 1, 2L, 3d, null))
+ }
+
+ @Test
+ void 'sameClassesGuard asTypes primitive parameters the way indy sites do'() {
+ def g = Selector.sameClassesGuard(['r', 1] as Object[], MethodType.methodType(Object, Object, int))
+ assertEquals(MethodType.methodType(boolean, Object, int), g.type())
+ // Object[] form hits MethodHandle.invokeWithArguments(Object[]), which
+ // asTypes/unboxes; the Groovy (Object...) call would go through the MOP.
+ assertTrue((boolean) g.invokeWithArguments(['r', 1] as Object[]))
+ assertFalse((boolean) g.invokeWithArguments([1, 1] as Object[]))
+ assertFalse((boolean) g.invokeWithArguments([null, 1] as Object[]))
+ }
+
+ @Test
+ void 'dynamic call site relinks when an argument class changes'() {
+ def adder = new Adder()
+ def acc = 0
+ 20.times { acc += adder.add(it, it + 1) }
+ acc += adder.add(100L, 3L)
+ assert acc == (0..19).sum { it + it + 1 } + 103L
+ }
+
+ static class Adder {
+ def add(a, b) { a + b }
+ }
+}
diff --git a/subprojects/performance/README.adoc b/subprojects/performance/README.adoc
index 5c545989a2..23ba43f0f9 100644
--- a/subprojects/performance/README.adoc
+++ b/subprojects/performance/README.adoc
@@ -148,6 +148,27 @@ exact-class policy — no hierarchy fan-out). Steady-state monomorphic sites
carry a single SwitchPoint guard. Complements the Grails-oriented
`CallSiteInvalidationBench` under `org.apache.groovy.perf.grails`.
+== Same-class guards (GROOVY-12284)
+
+`SameClassesGuardBench` measures the invokedynamic same-class guard that
+linked monomorphic sites install when every argument is non-null.
+Arities 1–4 (receiver plus 0–3 parameters) are specialised on HEAD;
+arity 5 keeps `asCollector(Object[].class, n)` and is the negative
+control. `@CompileStatic` rows (`cs_arity2`, `cs_arity5`) emit
+`invokevirtual` and must stay at parity. Each benchmark method is a
+single call so `-PjmhProfilers=gc` reports bytes per invocation.
+
+`SameClassesGuardMhBench` reconstructs the collector vs specialised
+MethodHandle combinators and invokes them with `invokeExact`, isolating
+the adapter from MOP selection. Specialised handles are bound with a
+single `insertArguments` (the production shape). Compiles on any tree
+that has the public overloads; `@Setup` fails on a pre-GROOVY-12284
+runtime. Run with:
+
+ ./gradlew :perf:jmh -PbenchInclude=SameClassesGuardBench
+ ./gradlew :perf:jmh -PbenchInclude=SameClassesGuardMhBench
+ ./gradlew :perf:jmh -PbenchInclude=SameClassesGuardBench -PjmhProfilers=gc
+
== Dashboard pages
The `dashboard/` directory is the source of truth for the hand-crafted pages
diff --git a/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/SameClassesGuardBench.groovy b/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/SameClassesGuardBench.groovy
new file mode 100644
index 0000000000..4bac1da4a2
--- /dev/null
+++ b/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/SameClassesGuardBench.groovy
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.bench
+
+import groovy.transform.CompileStatic
+import org.openjdk.jmh.annotations.Benchmark
+import org.openjdk.jmh.annotations.BenchmarkMode
+import org.openjdk.jmh.annotations.Fork
+import org.openjdk.jmh.annotations.Level
+import org.openjdk.jmh.annotations.Measurement
+import org.openjdk.jmh.annotations.Mode
+import org.openjdk.jmh.annotations.OutputTimeUnit
+import org.openjdk.jmh.annotations.Scope
+import org.openjdk.jmh.annotations.Setup
+import org.openjdk.jmh.annotations.State
+import org.openjdk.jmh.annotations.Warmup
+import org.openjdk.jmh.infra.Blackhole
+
+import java.util.concurrent.TimeUnit
+
+/**
+ * End-to-end cost of the invokedynamic same-class guard (GROOVY-12284).
+ * <p>
+ * Linked monomorphic sites with all-non-null arguments install a same-class
+ * guard. Before GROOVY-12284 that guard was always
+ * {@code SAME_CLASSES.bindTo(classes).asCollector(Object[].class, n)}, which
+ * allocates a fresh {@code Object[]} on every invocation. After the change,
+ * arities 1–4 (receiver plus 0–3 parameters) bind specialised handles and
+ * arity 5+ keeps the collector.
+ * <p>
+ * Each {@code @Benchmark} method is a single call so {@code gc.alloc.rate.norm}
+ * (run with {@code -PjmhProfilers=gc}) is bytes per invocation, not per inner
+ * loop. Arguments are pre-allocated heap objects: boxing must not be part of
+ * the signal. Receivers and arguments are non-final Groovy types; dynamic
+ * indy sites have {@code Object} parameter types, so the same-class guard is
+ * installed on every {@code dynamic_*} row.
+ * <p>
+ * How to read the rows:
+ * <ul>
+ * <li>{@code dynamic_arity1}–{@code dynamic_arity4} — treatment: specialised
+ * on HEAD, collector on the parent. Expect HEAD faster and/or fewer
+ * bytes/op.</li>
+ * <li>{@code dynamic_arity5} — negative control: collector on both sides.
+ * Expect parity. A HEAD win here is not GROOVY-12284.</li>
+ * <li>{@code cs_arity2} / {@code cs_arity5} — negative control:
+ * {@code @CompileStatic} emits {@code invokevirtual}, no MOP
+ * same-class guard. Expect parity at both arities.</li>
+ * </ul>
+ * Pair with {@link SameClassesGuardMhBench} for an isolated MethodHandle
+ * combinator comparison (collector vs specialised) that does not go through
+ * MOP selection.
+ *
+ * @see <a href="https://issues.apache.org/jira/browse/GROOVY-12284">GROOVY-12284</a>
+ */
+@Warmup(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
+@Fork(2)
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@State(Scope.Thread)
+class SameClassesGuardBench {
+
+ /**
+ * Receiver whose methods are selected through the MOP on the dynamic rows.
+ * Bodies are constant so remaining cost is dispatch plus the same-class
+ * guard, not arithmetic.
+ */
+ static class Target {
+ int zero() { 1 }
+ int one(Object a) { 1 }
+ int two(Object a, Object b) { 1 }
+ int three(Object a, Object b, Object c) { 1 }
+ int four(Object a, Object b, Object c, Object d) { 1 }
+ }
+
+ /** Non-final argument type so a class-identity guard is meaningful. */
+ static class Arg {
+ int n = 1
+ }
+
+ Target target
+ Arg a
+ Arg b
+ Arg c
+ Arg d
+
+ /**
+ * Allocates one receiver and four arguments for the trial. Fresh instances
+ * per trial keep the linked site monomorphic without MetaClass churn.
+ */
+ @Setup(Level.Trial)
+ void setup() {
+ target = new Target()
+ a = new Arg()
+ b = new Arg()
+ c = new Arg()
+ d = new Arg()
+ }
+
+ /** Receiver-only dynamic call: arity 1, specialised on HEAD. */
+ @Benchmark
+ void dynamic_arity1(Blackhole bh) {
+ bh.consume(target.zero())
+ }
+
+ /** Receiver plus one argument: arity 2, specialised on HEAD. */
+ @Benchmark
+ void dynamic_arity2(Blackhole bh) {
+ bh.consume(target.one(a))
+ }
+
+ /** Receiver plus two arguments: arity 3, specialised on HEAD. */
+ @Benchmark
+ void dynamic_arity3(Blackhole bh) {
+ bh.consume(target.two(a, b))
+ }
+
+ /** Receiver plus three arguments: arity 4, specialised on HEAD. */
+ @Benchmark
+ void dynamic_arity4(Blackhole bh) {
+ bh.consume(target.three(a, b, c))
+ }
+
+ /** Receiver plus four arguments: arity 5, collector on both sides. */
+ @Benchmark
+ void dynamic_arity5(Blackhole bh) {
+ bh.consume(target.four(a, b, c, d))
+ }
+
+ /**
+ * {@code @CompileStatic} arity 2: {@code invokevirtual}, no same-class guard.
+ */
+ @CompileStatic
+ @Benchmark
+ void cs_arity2(Blackhole bh) {
+ bh.consume(target.one(a))
+ }
+
+ /**
+ * {@code @CompileStatic} arity 5: {@code invokevirtual}, no same-class guard.
+ */
+ @CompileStatic
+ @Benchmark
+ void cs_arity5(Blackhole bh) {
+ bh.consume(target.four(a, b, c, d))
+ }
+}
diff --git a/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/SameClassesGuardMhBench.java b/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/SameClassesGuardMhBench.java
new file mode 100644
index 0000000000..eb422e1f0e
--- /dev/null
+++ b/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/SameClassesGuardMhBench.java
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.groovy.bench;
+
+import org.codehaus.groovy.vmplugin.v8.IndyGuardsFiltersAndSignatures;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Isolated MethodHandle combinator cost of GROOVY-12284.
+ * <p>
+ * Reconstructs the two guard shapes {@link org.codehaus.groovy.vmplugin.v8.Selector}
+ * actually installs, then invokes them with {@code invokeExact} so MOP
+ * selection, method bodies, and Groovy call-site infrastructure are not in
+ * the picture:
+ * <ul>
+ * <li><b>collector</b> — {@code sameClasses(Class[], Object[])} bound to
+ * the expected classes and adapted with
+ * {@code asCollector(Object[].class, n)}, the pre-GROOVY-12284 shape
+ * for every arity;</li>
+ * <li><b>specialised</b> — {@code sameClass}/{@code sameClasses} overloads
+ * with expected classes bound by a single
+ * {@code MethodHandles.insertArguments}, the production GROOVY-12284
+ * shape for arities 1–4.</li>
+ * </ul>
+ * Compiles against any Groovy that has the public {@code sameClasses}
+ * overloads; {@code @Setup} fails with {@code NoSuchMethodException} on a
+ * tree that predates GROOVY-12284. Compare collector vs specialised on the
+ * <em>same</em> JVM (intra-HEAD), then confirm the end-to-end effect with
+ * {@link SameClassesGuardBench} against the parent commit.
+ * <p>
+ * {@code specialised_bindTo_arity4} is the previous chained-{@code bindTo}
+ * combinator, kept so a regression back to four adapters is visible.
+ * <p>
+ * Arity 1 / 2 / 4 cover receiver-only, the common {@code recv.foo(x)} shape,
+ * and the largest specialised shape. There is no specialised arity-5
+ * overload; that path stays on the collector in production.
+ *
+ * @see <a href="https://issues.apache.org/jira/browse/GROOVY-12284">GROOVY-12284</a>
+ */
+@Warmup(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS)
+@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
+@Fork(2)
+@BenchmarkMode(Mode.Throughput)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@State(Scope.Thread)
+public class SameClassesGuardMhBench {
+
+ private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
+
+ Object a;
+ Object b;
+ Object c;
+ Object d;
+
+ MethodHandle collector1;
+ MethodHandle specialised1;
+ MethodHandle collector2;
+ MethodHandle specialised2;
+ MethodHandle collector4;
+ MethodHandle specialised4;
+ MethodHandle specialisedBindTo4;
+
+ /**
+ * Builds collector and specialised handles that match {@code Selector.sameClassesGuard}
+ * for arities 1, 2 and 4, using the public {@link IndyGuardsFiltersAndSignatures}
+ * methods the runtime binds.
+ *
+ * @throws ReflectiveOperationException if a handle cannot be resolved
+ */
+ @Setup(Level.Trial)
+ public void setup() throws ReflectiveOperationException {
+ a = new Object();
+ b = new Object();
+ c = new Object();
+ d = new Object();
+
+ MethodHandle arraySame = LOOKUP.findStatic(
+ IndyGuardsFiltersAndSignatures.class,
+ "sameClasses",
+ MethodType.methodType(boolean.class, Class[].class, Object[].class));
+ MethodHandle sameClass = LOOKUP.findStatic(
+ IndyGuardsFiltersAndSignatures.class,
+ "sameClass",
+ MethodType.methodType(boolean.class, Class.class, Object.class));
+ MethodHandle same2 = LOOKUP.findStatic(
+ IndyGuardsFiltersAndSignatures.class,
+ "sameClasses",
+ MethodType.methodType(boolean.class, Class.class, Class.class, Object.class, Object.class));
+ MethodHandle same4 = LOOKUP.findStatic(
+ IndyGuardsFiltersAndSignatures.class,
+ "sameClasses",
+ MethodType.methodType(boolean.class,
+ Class.class, Class.class, Class.class, Class.class,
+ Object.class, Object.class, Object.class, Object.class));
+
+ Class<?> ca = a.getClass();
+ Class<?> cb = b.getClass();
+ Class<?> cc = c.getClass();
+ Class<?> cd = d.getClass();
+
+ MethodType t1 = MethodType.methodType(boolean.class, Object.class);
+ MethodType t2 = MethodType.methodType(boolean.class, Object.class, Object.class);
+ MethodType t4 = MethodType.methodType(boolean.class, Object.class, Object.class, Object.class, Object.class);
+
+ collector1 = arraySame.bindTo(new Class<?>[]{ca}).asCollector(Object[].class, 1).asType(t1);
+ specialised1 = MethodHandles.insertArguments(sameClass, 0, ca).asType(t1);
+
+ collector2 = arraySame.bindTo(new Class<?>[]{ca, cb}).asCollector(Object[].class, 2).asType(t2);
+ specialised2 = MethodHandles.insertArguments(same2, 0, ca, cb).asType(t2);
+
+ collector4 = arraySame.bindTo(new Class<?>[]{ca, cb, cc, cd}).asCollector(Object[].class, 4).asType(t4);
+ specialised4 = MethodHandles.insertArguments(same4, 0, ca, cb, cc, cd).asType(t4);
+ specialisedBindTo4 = same4.bindTo(ca).bindTo(cb).bindTo(cc).bindTo(cd).asType(t4);
+ }
+
+ /** Pre-GROOVY-12284 arity-1 guard: collector of a one-element array. */
+ @Benchmark
+ public boolean collector_arity1() throws Throwable {
+ return (boolean) collector1.invokeExact(a);
+ }
+
+ /** Production arity-1 guard: {@code insertArguments} of the receiver class. */
+ @Benchmark
+ public boolean specialised_arity1() throws Throwable {
+ return (boolean) specialised1.invokeExact(a);
+ }
+
+ /** Pre-GROOVY-12284 arity-2 guard. */
+ @Benchmark
+ public boolean collector_arity2() throws Throwable {
+ return (boolean) collector2.invokeExact(a, b);
+ }
+
+ /** Production arity-2 guard: one {@code insertArguments}. */
+ @Benchmark
+ public boolean specialised_arity2() throws Throwable {
+ return (boolean) specialised2.invokeExact(a, b);
+ }
+
+ /** Pre-GROOVY-12284 arity-4 guard. */
+ @Benchmark
+ public boolean collector_arity4() throws Throwable {
+ return (boolean) collector4.invokeExact(a, b, c, d);
+ }
+
+ /** Production arity-4 guard: one {@code insertArguments}. */
+ @Benchmark
+ public boolean specialised_arity4() throws Throwable {
+ return (boolean) specialised4.invokeExact(a, b, c, d);
+ }
+
+ /** Pre-review arity-4 guard: four chained {@code bindTo} adapters. */
+ @Benchmark
+ public boolean specialised_bindTo_arity4() throws Throwable {
+ return (boolean) specialisedBindTo4.invokeExact(a, b, c, d);
+ }
+}