vector-handle
A high level API to express vectorized operations on primitive arrays in Java allowing to specify the vectorized operations as a simple lambda.
example
private static final VH = VectorHandle.of(lookup(), int.class, int.class, int.class);
...
var dest = new int[4];
var a = new int[] { 1, 2, 3, 4 };
var b = new int[] { 4, 4, 4, 4 };
VH.apply(dest, a, b, (x, y) -> x + y * 2);
System.out.println(Arrays.toString(dest)); // [9, 10, 11, 12]
available operations
The lambda used by the variations of the method apply()
only accept the following operator
- constants (any static final fields): Foo.A_CONSTANT
- literals: 1, 1L, 1.0f, 1.0
- parameters (any lambda parameters): x, y, etc
- Unary operator: -
- Binary operators: +, -, *, /, Math.min(), Math.max()
how to build it
This project requires the JDK 16, it uses internally the Vector API (jdk.incubator.vector
)
mvn packages
how it works ?
Lambdas in Java are desugared as static method where there are declared.
To find the corresponding class and method name to the lambda, the lambda is first serialized by explicitly
calling writeReplace()
(all serialized lambda proxies have that method) to get the resulting
java.lang.invoke.SerializedLambda
.
Then using ASM, the bytecode lambda method is read and transformed to a tree of expressions (AST)
using a simple abstract interpretation.
From the AST, a new bytecode using the vector API (jdk.incubator.vector
) is generated with ASM and
loaded using Lookup.defineHiddenClass
.
When calling apply
, a mutable call site is used to do all the operations above and see the generated bytecode
as a method handle.