Skip to content

Commit

Permalink
Overloading checkpoint
Browse files Browse the repository at this point in the history
- Improvements in Carrier, thanks @JornVernee
  • Loading branch information
biboudis committed Feb 28, 2024
1 parent ccaa1ec commit 646e8ae
Show file tree
Hide file tree
Showing 12 changed files with 402 additions and 78 deletions.
77 changes: 13 additions & 64 deletions src/java.base/share/classes/java/lang/runtime/Carriers.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

package java.lang.runtime;

import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
Expand All @@ -34,7 +36,6 @@
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import jdk.internal.misc.Unsafe;
import jdk.internal.util.ReferencedKeyMap;

import static java.lang.invoke.MethodType.methodType;
Expand Down Expand Up @@ -238,10 +239,6 @@ static List<MethodHandle> reshapeComponents(CarrierShape carrierShape,
* Factory for carriers that are backed by long[] and Object[].
*/
static final class CarrierObjectFactory {
/**
* Unsafe access.
*/
private static final Unsafe UNSAFE;

/*
* Constructor accessor MethodHandles.
Expand All @@ -256,7 +253,6 @@ static final class CarrierObjectFactory {

static {
try {
UNSAFE = Unsafe.getUnsafe();
Lookup lookup = MethodHandles.lookup();
CONSTRUCTOR = lookup.findConstructor(CarrierObject.class,
methodType(void.class, int.class, int.class));
Expand Down Expand Up @@ -404,7 +400,7 @@ static class CarrierObject {
/**
* Carrier for primitive values.
*/
private final long[] primitives;
private final MemorySegment primitives;

/**
* Carrier for objects;
Expand All @@ -429,8 +425,8 @@ protected CarrierObject(int primitiveCount, int objectCount) {
*
* @return primitives array of an appropriate length.
*/
private long[] createPrimitivesArray(int primitiveCount) {
return primitiveCount != 0 ? new long[(primitiveCount + 1) / LONG_SLOTS] : null;
private MemorySegment createPrimitivesArray(int primitiveCount) {
return primitiveCount != 0 ? MemorySegment.ofArray(new long[(primitiveCount + 1) / LONG_SLOTS]) : null;
}

/**
Expand All @@ -444,49 +440,13 @@ private Object[] createObjectsArray(int objectCount) {
return objectCount != 0 ? new Object[objectCount] : null;
}

/**
* Compute offset for unsafe access to long.
*
* @param i index in primitive[]
*
* @return offset for unsafe access
*/
private static long offsetToLong(int i) {
return Unsafe.ARRAY_LONG_BASE_OFFSET +
(long)i * Unsafe.ARRAY_LONG_INDEX_SCALE;
}

/**
* Compute offset for unsafe access to int.
*
* @param i index in primitive[]
*
* @return offset for unsafe access
*/
private static long offsetToInt(int i) {
return Unsafe.ARRAY_LONG_BASE_OFFSET +
(long)i * Unsafe.ARRAY_INT_INDEX_SCALE;
}

/**
* Compute offset for unsafe access to object.
*
* @param i index in objects[]
*
* @return offset for unsafe access
*/
private static long offsetToObject(int i) {
return Unsafe.ARRAY_OBJECT_BASE_OFFSET +
(long)i * Unsafe.ARRAY_OBJECT_INDEX_SCALE;
}

/**
* {@return long value at index}
*
* @param i array index
*/
private long getLong(int i) {
return CarrierObjectFactory.UNSAFE.getLong(primitives, offsetToLong(i));
return primitives.getAtIndex(ValueLayout.JAVA_LONG, i);
}

/**
Expand All @@ -498,7 +458,7 @@ private long getLong(int i) {
* @return this object
*/
private CarrierObject putLong(int i, long value) {
CarrierObjectFactory.UNSAFE.putLong(primitives, offsetToLong(i), value);
primitives.setAtIndex(ValueLayout.JAVA_LONG, i, value);

return this;
}
Expand All @@ -509,7 +469,7 @@ private CarrierObject putLong(int i, long value) {
* @param i array index
*/
private int getInteger(int i) {
return CarrierObjectFactory.UNSAFE.getInt(primitives, offsetToInt(i));
return primitives.getAtIndex(ValueLayout.JAVA_INT, i);
}

/**
Expand All @@ -521,7 +481,7 @@ private int getInteger(int i) {
* @return this object
*/
private CarrierObject putInteger(int i, int value) {
CarrierObjectFactory.UNSAFE.putInt(primitives, offsetToInt(i), value);
primitives.setAtIndex(ValueLayout.JAVA_INT, i, value);

return this;
}
Expand All @@ -532,7 +492,7 @@ private CarrierObject putInteger(int i, int value) {
* @param i array index
*/
private Object getObject(int i) {
return CarrierObjectFactory.UNSAFE.getReference(objects, offsetToObject(i));
return objects[i];
}

/**
Expand All @@ -544,7 +504,7 @@ private Object getObject(int i) {
* @return this object
*/
private CarrierObject putObject(int i, Object value) {
CarrierObjectFactory.UNSAFE.putReference(objects, offsetToObject(i), value);
objects[i] = value;

return this;
}
Expand Down Expand Up @@ -926,25 +886,14 @@ static Class<?> carrierClass(MethodType methodType) {
return CarrierFactory.of(methodType).carrierClass();
}

/**
* XXX
*
* @param methodType {@link MethodType} whose parameter types supply the shape of the
* carrier's components
* @return the factory for the carrier of the given shape
*/
public static MethodHandle factory(MethodType methodType) {
return initializingConstructor(methodType);
}

/**
* {@return the constructor {@link MethodHandle} for the carrier representing {@code
* methodType}. The carrier constructor will always have a return type of {@link Object} }
*
* @param methodType {@link MethodType} whose parameter types supply the shape of the
* carrier's components
*/
static MethodHandle constructor(MethodType methodType) {
public static MethodHandle constructor(MethodType methodType) {
MethodHandle constructor = CarrierFactory.of(methodType).constructor();
constructor = constructor.asType(constructor.type().changeReturnType(Object.class));
return constructor;
Expand Down Expand Up @@ -973,7 +922,7 @@ static MethodHandle initializer(MethodType methodType) {
* @param methodType {@link MethodType} whose parameter types supply the shape of the
* carrier's components
*/
static MethodHandle initializingConstructor(MethodType methodType) {
static public MethodHandle initializingConstructor(MethodType methodType) {
MethodHandle constructor = CarrierFactory.of(methodType).initializingConstructor();
constructor = constructor.asType(constructor.type().changeReturnType(Object.class));
return constructor;
Expand Down
74 changes: 67 additions & 7 deletions src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
Expand Down Expand Up @@ -28,7 +28,9 @@
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import javax.lang.model.element.ElementKind;
import javax.tools.JavaFileObject;
Expand Down Expand Up @@ -4250,14 +4252,72 @@ public void visitRecordPattern(JCRecordPattern tree) {

if (site.tsym.kind == Kind.TYP) {
int nestedPatternCount = tree.nested.size();
var matchers = site.tsym.members().getSymbols(sym -> (sym.flags() & MATCHER) != 0 && sym.type.getParameterTypes().size() == nestedPatternCount);
Iterator<Symbol> matchersIt = matchers.iterator();

if (matchersIt.hasNext()) {
MethodSymbol matcher = (MethodSymbol) matchers.iterator().next();
// precalculate types of pattern components (as in method invocation)
ListBuffer<Type> patternTypesBuffer = new ListBuffer<>();
for (JCTree arg : tree.nested.map(p -> p.getTree())) {
Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, resultInfo));
patternTypesBuffer.append(argtype);
}
List<Type> patternTypes = patternTypesBuffer.toList();

var matchersIt = site.tsym.members()
.getSymbols(sym -> (sym.flags() & MATCHER) != 0 && sym.type.getParameterTypes().size() == nestedPatternCount)
.iterator();
List<MethodSymbol> matchers = Stream.generate(() -> null)
.takeWhile(x -> matchersIt.hasNext())
.map(n -> (MethodSymbol) matchersIt.next())
.collect(List.collector());

if (matchers.size() >= 1) {
ListBuffer<Integer> score = new ListBuffer<Integer>();

// overload resolution of matcher
for (MethodSymbol matcher : matchers) {
int scoreForMatcher = 0;

List<Type> matcherComponentTypes = matcher.getParameters()
.stream()
.map(rc -> types.memberType(site, rc))
.map(t -> types.upward(t, types.captures(t)).baseType())
.collect(List.collector());

boolean applicable = true;
for (int i = 0; applicable && i < patternTypes.size(); i++) {
applicable &= types.isCastable(patternTypes.get(i), matcherComponentTypes.get(i));
}

if (applicable) {
// todo: need to separate scores for each parameter
for (int i = 0; i < patternTypes.size(); i++) {
if (types.isSameType(patternTypes.get(i), matcherComponentTypes.get(i))) {
scoreForMatcher += 2;
} else if (types.isCastable(patternTypes.get(i), matcherComponentTypes.get(i))) {
scoreForMatcher += 1;
}
}
score.add(scoreForMatcher);
} else {
score.add(-1);
}
}

tree.matcher = matcher;
expectedRecordTypes = types.memberType(site, matcher).getParameterTypes();
var maxScore = Collections.max(score);
List<Integer> scoreList = score.toList();
var indexOfMaxScore = scoreList.indexOf(maxScore);

if (maxScore == -1) {
log.error(tree.pos(),
Errors.NoCompatibleMatcherFound);
} else if (scoreList.stream().filter(s -> s == maxScore).count() > 1) {
log.error(tree.pos(),
Errors.MatcherOverloadingAmbiguity);
} else {
MethodSymbol matcher = matchers.get(indexOfMaxScore);
tree.matcher = matcher;

expectedRecordTypes = types.memberType(site, matcher).getParameterTypes();
}
} else if (((ClassSymbol) site.tsym).isRecord()) {
ClassSymbol record = (ClassSymbol) site.tsym;
expectedRecordTypes = record.getRecordComponents()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1248,27 +1248,29 @@ public void visitMethodDef(JCMethodDecl tree) {
if (tree.sym.isDeconstructor()) {
// Generate (without the bindings)
// 1. calculate the returnType MethodType as Constant_MethodType_info
// 2. generate factory code on carrier for the types we want (e.g., Object carrier = Carriers.factory(returnType);)
// 2. generate factory code on carrier for the types we want (e.g., Object carrier = Carriers.initializingConstructor(returnType);)
// 3. generate invoke call to pass the bindings (e.g, return carrier.invoke(x, y);)

List<Type> params = List.nil();
List<JCExpression> invokeMethodParam = List.nil();

for (int i = 0; i < tree.params.length(); i++) {
params = params.append(types.boxedTypeOrType(tree.params.get(i).type));
params = params.append(tree.params.get(i).type);
invokeMethodParam = invokeMethodParam.append(make.Ident(tree.params.get(i)));
}

MethodSymbol factoryMethodSym =
rs.resolveInternalMethod(tree.pos(),
env,
syms.carriersType,
names.fromString("factory"),
names.fromString("initializingConstructor"),
List.of(syms.methodTypeType),
List.nil());

DynamicVarSymbol factoryMethodDynamicVar =
(DynamicVarSymbol) invokeMethodWrapper(tree.pos(),
(DynamicVarSymbol) invokeMethodWrapper(
names.fromString("carrier"),
tree.pos(),
factoryMethodSym.asHandle(),
new MethodType(params, syms.objectType, List.nil(), syms.methodClass));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,12 @@ compiler.err.concrete.inheritance.conflict=\
compiler.err.default.allowed.in.intf.annotation.member=\
default value only allowed in an annotation interface declaration

compiler.err.matcher.overloading.ambiguity=\
matcher overloading ambiguity

compiler.err.no.compatible.matcher.found=\
no compatible matcher found

# 0: symbol
compiler.err.doesnt.exist=\
package {0} does not exist
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,10 @@ public void visitMethodDef(JCMethodDecl tree) {
printDocComment(tree);
printExpr(tree.mods);
printTypeParameters(tree.typarams);
if (tree.name == tree.name.table.names.init) {
if (tree.sym.isMatcher()) {
print("__matcher ");
}
if (tree.name == tree.name.table.names.init || tree.sym.isMatcher()) {
print(enclClassName != null ? enclClassName : tree.name);
} else {
printExpr(tree.restype);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

// key: compiler.err.matcher.overloading.ambiguity
// key: compiler.misc.feature.matchers
// key: compiler.warn.preview.feature.use.plural
// options: --enable-preview -source ${jdk.version} -Xlint:preview

public class MatcherOverloadingAmbiguity {
private static int test(D o) {
if (o instanceof D(String data, Integer out)) {
return out;
}
return -1;
}

public record D() {
public __matcher D(Object v, Integer out) {
out = 1;
}

public __matcher D(CharSequence v, Integer out) {
out = 2;
}
}
}
Loading

0 comments on commit 646e8ae

Please sign in to comment.