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/21 16:46:01 UTC
(groovy) branch GROOVY-12284 created (now 47bd7b0794)
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a change to branch GROOVY-12284
in repository https://gitbox.apache.org/repos/asf/groovy.git
at 47bd7b0794 GROOVY-12284: Specialize indy sameClasses guards for arity 1-4
This branch includes the following new commits:
new 47bd7b0794 GROOVY-12284: Specialize indy sameClasses guards for arity 1-4
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(groovy) 01/01: GROOVY-12284: Specialize indy sameClasses guards for arity 1-4
Posted by su...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch GROOVY-12284
in repository https://gitbox.apache.org/repos/asf/groovy.git
commit 47bd7b0794ce178b296dd3f35b7eb51b3717dfab
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 | 32 +++-
.../org/codehaus/groovy/vmplugin/v8/Selector.java | 48 +++++-
.../vmplugin/v8/IndySameClassesGuardTest.groovy | 80 ++++++++++
subprojects/performance/README.adoc | 19 +++
.../groovy/bench/SameClassesGuardBench.groovy | 163 +++++++++++++++++++
.../groovy/bench/SameClassesGuardMhBench.java | 175 +++++++++++++++++++++
6 files changed, 511 insertions(+), 6 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..3d2619c979 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,30 @@ 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.
+ */
+ 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..796fbd907a 100644
--- a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
+++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java
@@ -91,6 +91,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;
@@ -1314,11 +1317,8 @@ 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);
+ handle = MethodHandles.guardWithTest(
+ Selector.sameClassesGuard(args, pt), 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 +1533,42 @@ public abstract class Selector {
}
return sender;
}
+
+ /**
+ * Builds a same-class guard that avoids {@code asCollector(Object[].class, n)}
+ * for the common 1–4 argument shapes (receiver plus 0–3 parameters).
+ * The produced handle has type {@code (pt)boolean} and returns {@code false}
+ * if any argument is {@code null} or has a different runtime class.
+ */
+ static MethodHandle sameClassesGuard(final Object[] args, final Class<?>[] pt) {
+ int n = pt.length;
+ MethodType booleanType = MethodType.methodType(boolean.class, pt);
+ if (n == 0) {
+ return MethodHandles.constant(boolean.class, true);
+ }
+ if (n == 1) {
+ return SAME_CLASS.bindTo(args[0].getClass()).asType(booleanType);
+ }
+ if (n == 2) {
+ return SAME_CLASSES_2
+ .bindTo(args[0].getClass()).bindTo(args[1].getClass())
+ .asType(booleanType);
+ }
+ if (n == 3) {
+ return SAME_CLASSES_3
+ .bindTo(args[0].getClass()).bindTo(args[1].getClass()).bindTo(args[2].getClass())
+ .asType(booleanType);
+ }
+ if (n == 4) {
+ return SAME_CLASSES_4
+ .bindTo(args[0].getClass()).bindTo(args[1].getClass())
+ .bindTo(args[2].getClass()).bindTo(args[3].getClass())
+ .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..bf1a149bd2
--- /dev/null
+++ b/src/test/groovy/org/codehaus/groovy/vmplugin/v8/IndySameClassesGuardTest.groovy
@@ -0,0 +1,80 @@
+/*
+ * 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 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 'sameClasses overloads reject null and class change'() {
+ assertTrue IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, 'a', 1)
+ assertFalse IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, 'a', 1L)
+ assertFalse IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, 'a', null)
+ assertFalse IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, null, 1)
+
+ assertTrue IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, Long, 'a', 1, 2L)
+ assertFalse IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, Long, 'a', 1, 2)
+
+ assertTrue IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, Long, Double, 'a', 1, 2L, 3d)
+ assertFalse IndyGuardsFiltersAndSignatures.sameClasses(String, Integer, Long, Double, 'a', 1, 2L, 3f)
+ }
+
+ @Test
+ void 'sameClassesGuard arity 1 to 4 matches collector semantics'() {
+ def g1 = Selector.sameClassesGuard(['recv'] as Object[], [Object] as Class[])
+ assertTrue((boolean) g1.invokeWithArguments('recv'))
+ assertFalse((boolean) g1.invokeWithArguments(1))
+ assertFalse((boolean) g1.invokeWithArguments((Object) null))
+
+ def g2 = Selector.sameClassesGuard(['recv', 'arg'] as Object[], [Object, Object] as Class[])
+ assertTrue((boolean) g2.invokeWithArguments('recv', 'arg'))
+ assertFalse((boolean) g2.invokeWithArguments('recv', 1))
+ assertFalse((boolean) g2.invokeWithArguments('recv', null))
+
+ def g3 = Selector.sameClassesGuard(['r', 1, 2L] as Object[], [Object, Object, Object] as Class[])
+ assertTrue((boolean) g3.invokeWithArguments('r', 1, 2L))
+ assertFalse((boolean) g3.invokeWithArguments('r', 1, null))
+
+ def g4 = Selector.sameClassesGuard(['r', 1, 2L, 3d] as Object[], [Object, Object, Object, Object] as Class[])
+ assertTrue((boolean) g4.invokeWithArguments('r', 1, 2L, 3d))
+ assertFalse((boolean) g4.invokeWithArguments('r', 1, 2L, 'x'))
+ }
+
+ @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..fae0908713 100644
--- a/subprojects/performance/README.adoc
+++ b/subprojects/performance/README.adoc
@@ -148,6 +148,25 @@ 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. It needs the specialised overloads, so
+it compiles only on GROOVY-12284+. 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..77d5c2a5e6
--- /dev/null
+++ b/subprojects/performance/src/jmh/groovy/org/apache/groovy/bench/SameClassesGuardMhBench.java
@@ -0,0 +1,175 @@
+/*
+ * 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 {@code bindTo}, the HEAD shape for
+ * arities 1–4.</li>
+ * </ul>
+ * Requires the specialised overloads, so this class compiles only on
+ * 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>
+ * 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;
+
+ /**
+ * 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 = sameClass.bindTo(ca).asType(t1);
+
+ collector2 = arraySame.bindTo(new Class<?>[]{ca, cb}).asCollector(Object[].class, 2).asType(t2);
+ specialised2 = same2.bindTo(ca).bindTo(cb).asType(t2);
+
+ collector4 = arraySame.bindTo(new Class<?>[]{ca, cb, cc, cd}).asCollector(Object[].class, 4).asType(t4);
+ specialised4 = 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);
+ }
+
+ /** HEAD arity-1 guard: {@code sameClass} bound to 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);
+ }
+
+ /** HEAD arity-2 guard. */
+ @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);
+ }
+
+ /** HEAD arity-4 guard. */
+ @Benchmark
+ public boolean specialised_arity4() throws Throwable {
+ return (boolean) specialised4.invokeExact(a, b, c, d);
+ }
+}