New JEP: Classfile Processing API
Per Bothner
per at bothner.com
Sun Jun 19 15:59:28 UTC 2022
Generally, this seems like a very good thing to do.
"For example, branch offsets can be short or long. If clients generate instructions
imperatively, they have to know how far the branch offset is at the time each branch
is generated, which is complex and error-prone. But if the client provides a lambda
that takes a builder, the library can optimistically try to generate the method with
short offsets, and if this fails, discard the generated state and re-invoke the lambda
with different code generation parameters.
An aside (and not telling you anything new I'm sure) but a "fixup" post-processing pass
is probably preferable to doing the code-generation twice: It's hard for the latter to use
a mix of short and long jumps as needed.
When gnu.bytecodes generates code the instructions are appended to a byte
array in optimistic form. In addition "fixup" operations are appended to the fixup
buffer (the arrays fixup_offset and fixup_labels). Then when done emitting instructions
we call processFixups, which iterates over the fixups (3 times!) to adjust the bytecode
and assign final offsets to the labels.
The processFixups method is complicated because it handles a number of issues at
the same time: various optimizations (including moving some code blocks around),
as well as assigning offsets to Labels.
Feel free to get inspiration from:
https://gitlab.com/kashell/Kawa/-/blob/master/gnu/bytecode/CodeAttr.java
The code is a bit convoluted, written more for performance then readability.
However, it is at least somewhat commented - and I'm happy to answer any questions.
--
--Per Bothner
per at bothner.com http://per.bothner.com/
More information about the discuss
mailing list