Skip to content

evmone parity and readability cleanup - #18

Merged
sbillig merged 87 commits into
mainfrom
readability/cleanup
Nov 10, 2026
Merged

sbillig merged 87 commits into
mainfrom
readability/cleanup

Conversation

@sbillig

@sbillig sbillig commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Brings fevm's native build close to evmone, then reshapes the interpreter to read as ordinary Fe.

  • Precompiles: SHA-256 compresses blocks with std::native::sha256_compress; RIPEMD-160 and BLAKE2f are unrolled; BLS12-381 and BN254 use lazy reduction in Fp2 and Fp4, GLV for G1 and KZG scalars, sliding-window square roots, precomputed KZG G2 lines and cofactor clearing through the |x| chain; precompile inputs are read a lane at a time.
  • Transactions and state: intrinsic gas is computed once, the sender is charged in one step, journal changes are typed and built and undone in place, a held state runs transactions in place, and transient storage reverts stay cheap.
  • Interpreter: handlers take a Cursor; PUSH, DUP, SWAP and the arithmetic opcodes are one generic handler each; the handlers and child frames move out of vm.fe; inline attributes the compiler doesn't need are gone.
  • Dependencies: keccak main 345d508 (Lane-wise absorption and double-buffered rounds keccak#2), swisstable main 2de44c1, and Fe master 4608e5fdf (Add std::native::sha256_compress argotorg/fe#1977: Sonatina 2547f707 and std::native::sha256_compress).

The identity precompile went through the generic ByteSource path, copying
eight bytes per ~10 instructions; test_identity ran 7x evmone. Calls from
the VM now copy the input span with one memmove (1.08x); an empty input
call drops from 2.45x to 1.06x.
apply validated the transaction, which computes its intrinsic gas, and then
computed it again. Validation now returns it with its verdict.
A transaction's nonce increment and gas purchase each looked up the sender
and pushed a journal entry. Transaction::charge does both with one lookup and
one SENDER entry, which undo restores and settlement counts as a touch.

Settlement looked up every journaled touch to delete empty accounts, though
a transfer journals its sender four times. It now skips an address among the
last four it checked; settling changes no balance, so the answer is the
same. A transfer runs 9% fewer instructions.
The portable rounds ran about 4x evmone, which uses the x86 SHA extensions.
Fe's std::native::sha256_compress uses them too where the host has them,
and scalar rounds elsewhere, so the precompile's own rounds go. The SHA-256
benchmark cases run 2.9x faster, about 1.4x evmone.
set_code copied code into the arena a checked byte at a time: a 24 KB
deposit was 24,576 indexed stores. It now writes 8-byte lanes and then the
tail. CREATE benchmark cases run 7% faster (deposits of a quarter to the
whole code size limit 12%).
RIPEMD-160 looped over its 80 steps per line, reading each step's message
word, rotation and constant from tables and choosing the boolean function by
round at run time. The steps are now written out with literal operands
(generated from the specification's tables) and renamed working words. The
RIPEMD-160 benchmark cases run 28% faster: 1.29x revm (was 1.78x), 0.46x
evmone.
Each BLAKE2f round looked its sixteen message words up through SIGMA, a
table load and a bounds-checked index per word. Ten rounds, one pass of the
schedule, now run with the indices written out, and the remaining rounds as
before. The 30M-gas blake2f case runs 42% faster (0.69x evmone); calls of 1
to 24 rounds run up to 13% slower, the larger compress taking more code per
call. Geomean over the nine cases: -1.7%.
`mark_jumpdests` read every byte. After an opcode that is neither a
JUMPDEST nor a PUSH, it now tests the next eight bytes at once and skips
them when none is in 0x5b..=0x7f. Code that is mostly JUMPDESTs and PUSHes
never pays for the test. jumpdest_analysis[00] (24 KB of STOPs per
CREATE) 2.11x -> 0.67x evmone; the other five cases are unchanged.
`Fp::pow` squared and multiplied bit by bit over all 384 bits: a square
root, a 379-bit exponent with 229 set bits, cost 613 multiplications. It
now uses a table of self^0..self^15 and four squarings per nonzero
window, from the top nonzero window: about 480. `sqrt_candidate` exposes
self^((p+1)/4) for roots of nonsquares' negations.
SSWU took a second square root, of gx2, whenever gx1 was not a square
(half the inputs), and inverted the constant a each call. In Fp, p = 3
mod 4, so the failed candidate y has y^2 = -gx1 and sqrt(-Z^3) u^3 y is
the root of gx2 = Z^3 u^6 gx1; -b/a and b/(Z a) are now constants.
`Fp2::sqrt` likewise derives (c0 - alpha)/2's root from the failed
candidate for (c0 + alpha)/2 instead of exponentiating again. A test
checks SSWU outputs on both curves for 20 inputs taking both paths.
MAP_FP_TO_G1 2.49x -> 1.67x evmone, MAP_FP2_TO_G2 1.80x -> 1.66x.
SAR shifted the value logically, then or-ed in a sign mask built by a
second variable shift. It now shifts the value as an i256, one
arithmetic shift, keeping the explicit case for shifts of 256 or more.
SAR's benchmark runs 24% fewer instructions (as many as evmone) and 7.5%
fewer cycles. A test covers signs, shifts 0 through 255, 256 and more.
A revert undid every TSTORE's journal entry with a transient-table
search and removal. A checkpoint now records whether transient storage
was empty; reverting to such a checkpoint skips those entries and
replaces the table with an empty one, as the entries' undo would have
left it. A transaction failing after many TSTOREs (the TSTORE benchmark)
runs 26% fewer instructions and 25% fewer cycles, as fast as evmone.
The last block, which holds the input's tail and the padding, was built
byte by byte: 64 iterations of two comparisons and a load. Its eight lanes
are now byte-swapped loads while within the input, zero past it, and byte
by byte only for the lane holding the input's last bytes and the 0x80
marker. An empty input runs 26% fewer instructions; SHA-256's cases go
from 1.42x to 1.28x evmone.
`expand_memory` was a call even when an expansion plan kept memory's size,
as for every access within memory already used; plans never shrink, so
an inlined size comparison now returns at once. `LogBuffer::append`
reserved and copied empty data and topics through calls. LOG0 of nothing
runs 19% fewer instructions (1.32x -> 1.13x evmone).
`move_within` took its source, destination and length as u256 and
narrowed them, so `op_mcopy` stored all twelve limbs to the stack to
pass them by pointer. Its caller has already checked that the ranges
lie within memory, so narrow there and pass usize.
Each CIOS row added `a * b` word by word, a widening multiply and two
128-bit additions per word. Add the products' low words in one carry
chain and their high words, a word up, in another, interleaved; the
compiler runs the two through CF and OF with ADX's `adcx` and `adox`.
The words above the chains are carry ops too, which stay where they
are written. The first row, with no accumulator, is a single chain.

BLS12-381 `Fp::mul` drops from 521 to 439 instructions; point
evaluation runs 12% faster, MAP_FP_TO_G1 10%, BN254 3-6%.
`try_push` returns its value back on failure, so a change went through a
result buffer and a copy even with room in the journal. With spare
capacity, push it unchecked: CREATE runs 3.6% fewer cycles.
op_jumpi loaded the destination word before testing the condition, so a fallthrough read four limbs it never used: 7% of the instructions of a JUMPI fallthrough loop.
Transaction::adjust recomputed the 256-bit overflow test that WorldState::adjust had just made. Replaced now says when the addition overflowed. A transfer runs 2% fewer instructions.
Each transaction started its transient storage, marks, warm storage and originals tables empty, so its first insertion into each allocated slots that finish freed again. The tables now live in Buffers, which the caller lends to every transaction, and finish clears them with swisstable's new clear, keeping their slots. A transfer runs 8% fewer instructions.
Block offsets within an input bounded by host memory cannot overflow, but every lane and byte of a block paid checked additions and multiplications. SHA-256 of 1 KiB inputs runs 13% fewer instructions.
keccak 51ccb4f absorbs a word's bytes a lane at a time instead of one at a time. A CREATE address hashes 22 bytes of RLP: CREATE runs 2% fewer cycles.
Callers built a Change before Journal::append chose between the in-place fast path and try_push, so the change went through a temporary and was copied into the slot. Journal::record takes the fields and builds the change on each path; with Sonatina ee9a4d0e the fast path builds it in the journal's slot. A transfer runs 1.8% fewer instructions.
A CREATE searched the account index 24 times, often for the same
address: `start_create` read the sender's nonce twice and its balance,
`deployable` read the new address's nonce, code and storage separately,
`deploy_code` checked code and existence before `set_code` looked the
address up twice, and undoing a change that created an account restored
it and then looked it up again to remove it. Each of these now takes one
lookup. CREATE 0 bytes with value: 7.52M -> 7.03M instructions per tx.
`sha256_block` built each block in an array it returned on two paths,
so the compression's block was a phi of two loads, copied through a
temporary. It now writes the words into the caller's array, which
`sha256_compress` reads in place with the state. SHA-256 of 1 KiB:
1.34x -> 1.04x evmone.
`undo_to` popped each change: `MemVec::pop` loaded the 128-byte entry,
wrapped it in an `Option` and `unwrap` took it out again, two whole
copies per change before reading three fields. Read the last change in
place and truncate the journal instead. CREATE 0 bytes with value:
6.94M -> 6.78M instructions per tx.
This reverts commit 960f565. Sonatina 1706a5a8 removes the assertion
`unwrap` left on the `Option` that `MemVec::pop` builds, so `pop` no
longer copies the change; the workaround gains nothing over it.
The isogeny divided by its x and y denominators with two inversions per
map. Return the Jacobian point with z = x_den y_den instead, at eight
multiplications. MAP_FP_TO_G1 -8% time, MAP_FP2_TO_G2 -2%.
swisstable bc26326 keeps tables at most half full, which shortens the
byte-by-byte probe runs of account, storage and mark lookups: CREATE
-8% and SELFDESTRUCT -10% cycles.
SAR branched on a count past 255 and then on the sign, which it computed
with a 256-bit signed comparison. A shift by 255 already fills every bit
with the sign, so the count is 255 or the low byte of the shift: one
select, and a shift whose count fits in a byte needs no range check.
Each CIOS row added the CF chain's carry to the top word after the OF
chain, then summed the two carries above it, which kept the OF carry in a
register (seto, movzx). A product's high word takes the CF carry without
carrying, so fold it there first and let the OF chain end the row, as
blst does: the Fp multiplication drops from 351 to 336 instructions with
the zero register lanes share, and fp_to_g1 runs 2.3% faster.
A transfer of no value debited and credited zero, each looking the account
up only to find the value unchanged and record a touch. Record the touch
directly: SELFDESTRUCT's initcode benchmark loses two lookups an
iteration (-2.6% instructions) and a zero-value transfer 4.8%.
SELFDESTRUCT looked the beneficiary up for the new-account charge before
testing the balance it depends on, and zeroed an already empty balance of
an account created in the transaction, which the transfer had touched.
Test the balance first and burn only a balance the transfer kept:
-3.3% instructions on the SELFDESTRUCT initcode benchmark.
push_next tested depth >= STACK_LIMIT, which Sonatina lowers to a
less-than with the push on the branch's true side, laying the fault
block out between the check and the push. Test depth > STACK_LIMIT - 1
so the fault is the side taken: PUSH0 runs straight through to its
dispatch in one cache line, and the JUMPI fallthrough benchmark (PUSH0
PUSH0 JUMPI) runs 20% faster.
swisstable eee63c1 hashes u256 keys with one folded multiplication instead
of three, which a lookup waits on before probing: CREATE -4.3%, transfers
-4.9%, the SELFDESTRUCT initcode benchmark -3.5% cycles.
Each pop of LOG, KECCAK256, the copies and CREATE checked the stack for
underflow and stored its length, and the next pop loaded the length again
across that check. Check the stack for all of an opcode's operands at once,
then take them unchecked: LOG0 runs 5.9% faster.
A balance or nonce journal record now keeps the position of the account it
wrote, in its unused slot word. Undoing in reverse finds each account where
its change left it, so `restore_at` writes it back without a hash lookup,
and falls back to `restore` if the record moved.
Code a CREATE deposits or an EIP-7702 delegation installs was hashed at
once, though most of it is never hashed by anyone (EXTCODEHASH, a client's
report), and code a SELFDESTRUCT removes in its creating transaction never
can be. `set_code_unhashed` leaves the hash at zero, and `code_hash`, now
`mut`, hashes the arena copy on first read and keeps the result. Hosts'
`set_code` still hashes at once. SELFDESTRUCT of created contracts: 890 to
445 keccak permutations a transaction, -22% cycles.
fe-lang/keccak d07807d permutes between two states a row at a time, which
cuts the spills of a round: KECCAK256 benchmark -6% cycles, -11%
instructions.
Deploying empty code to an account, which has none (EIP-684), changes
nothing, but looked the account up twice, journaled a CODE change, and
undid it with another lookup. Return before any of that. CREATE with empty
initcode: -3.6% instructions.
CREATE set the new account's nonce and credited its endowment separately:
two lookups, two journal entries, and two undos when the transaction
fails. `endow` sets the nonce to one and adds the value with one lookup,
under a CONTRACT entry that restores both by the account's position.
CREATE with value and empty initcode: -4.5% instructions.
A journal change is an address and a `ChangeKind` enum, in place of a
`u8` kind whose `slot` held a storage slot, an account position, a nonce
or a delegation flag. Marks are a `Mark` enum. `WorldState` writes take a
`Field` and return `Result<WriteError, Written>`, replacing the
`balance: bool` selectors, `Replaced` and its status flags, and the four
restore variants.

One `undo` reverses a change for revert and for a journal that cannot
grow: writes happen first and are journaled after, except code writes,
whose undo can allocate. Touches are marks, so `TOUCHED_ONCE` goes.

Remove the unchecked journal push, cached account positions, the settle
address cache, the whole-table transient clear, one-search TSTORE and the
zero-amount adjust shortcut.
The journal cleanup dropped three algorithmic shortcuts that no compiler
change wins back. A revert to a checkpoint whose transient storage was
empty empties the table again instead of undoing each write. `mark` and
TSTORE find or insert with one search. The transaction's own call and
writes that leave a value record a `ChangeKind::Touch`: as a mark, the
touch made the marks table nonempty, and `end` then cleared its whole
control array. TSTORE with varying keys took 2.3x the old time.
`op_push<N>`, `op_dup<N>` and `op_swap<N>` take the width or depth as a
const parameter, and each instantiation is a handler. They replace 32 DUP
and SWAP wrappers around `#[inline(always)]` helpers, and PUSH1, PUSH2,
PUSH4 and PUSH32's own handlers: `op_push` reads the smallest whole word
that holds its immediate, which for those widths is the immediate itself.
The handlers took the code pointer, pc, gas, stack depth and stack-top
pointer as separate arguments, because a struct of them was copied
through memory and broke tail-call dispatch. With Sonatina holding
five-part structs in registers through tail calls, they take one
`Cursor`, whose methods charge gas, check and move the stack, read
immediates and advance pc, with each invariant stated once. Faults go
through one out-of-line function per status, which passes no gas.
`dispatch` built its cursor itself, and a tail call's aggregate argument
must be one of the caller's own parameters, so its 126 arms became calls
instead of a jump through the handler table; it now takes the cursor its
callers build with `cursor`. Its stack-top offset wraps, as `depth` is
at most `STACK_LIMIT`, so it has no overflow check. `copy_padded` took
the cursor as a reference out of line; inlined, fixed-range CALLDATACOPY
is back to its old speed.
SWAP exchanged its words a 64-bit piece at a time to keep two pieces
live, and MLOAD, MSTORE and MSTORE8 grew memory within the buffer in
out-of-line `_grow` handlers to keep the common path's values live
fewer. With the cursor in registers neither pays: SWAP is as fast
swapping whole words, and the growth runs in each handler, leaving only
the hand-off to `mload`, `mstore` and `mstore8` out of line, where a
call needs a frame.
`op_binary`, `op_unary` and `op_modular` took the opcode and its cost as
runtime arguments, and were forced inline into 24 named wrappers so each
handler would fold its one operation. They now take the opcode as a const
parameter and charge `base_cost(OP)`, which folds to a constant; the
dispatch table names each instance, and `binary_result`, `unary_result`,
`sdiv` and `smod` inline unforced.
`spend`, `read_code`, `pushed`, `expand_memory` and `buffered_growth`
inline without `#[inline(always)]`. `calldata_tail` and `move_within`
stayed out of line to spare their handlers' registers and, for
`move_within`, a tail call its memory view blocked; inlined, CALLDATALOAD
and MCOPY keep their tail-call dispatch and run faster, so `move_within`
folds into `op_mcopy`. `hash_memory` stays out of line: inlined, its
hasher state is a local object the hashing calls take, and Sonatina then
makes none of the handler's calls tail calls.
Each instance folds its other widths' branches away, so the shift counts
those branches compute never reach generated code; the build is the same
without it.
TSTORE of zero found the entry, read its previous value and removed the
key, searching the transient table twice. swisstable's new `take`
removes it and returns the value in one search; swisstable is pinned to
32c49fe (feat/take, on perf/one-multiply-hash).
It stayed out of line because, inlined, its hasher state was a local
object passed to the hashing calls, and Sonatina counted that as an escape
that ruled out every tail call in the KECCAK256 handler. Sonatina now
ignores objects passed `nocapture` (fe-lang/sonatina#504), so the handler
keeps its tail-call dispatch with the hash inlined.
fe-lang/swisstable#4 merged clear, take, the half load and the one-multiply
hash into main; its source is the same as the feat/take commit pinned
before.
vm.fe held the VM's state and its stack, memory and state operations,
the interpreter loop, the opcode handlers and the child-frame machinery
in 2,260 lines. The handlers, with their cursor and opcode arithmetic,
move to vm/handlers.fe and calls, creations, precompiles and the child
frame loop to vm/frames.fe; as child modules they use the VM's private
fields and methods directly. The code is the same.
fe-lang/keccak#2 merged lane-wise absorption and the double-buffered
rounds into main; its source is the same as the
perf/double-buffer-permute commit pinned before.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T20:33:51.414136Z f72d376 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@sbillig
sbillig force-pushed the readability/cleanup branch from 0911308 to c860b44 Compare November 10, 2026 20:07
The SHA-256 precompile compresses each block with
`std::native::sha256_compress`, which argotorg/fe#1977 added along with
Sonatina 2547f707. Pin Fe master 4608e5fdf, its Cargo.lock and its
Sonatina revision.
@sbillig
sbillig force-pushed the readability/cleanup branch from c860b44 to f72d376 Compare November 10, 2026 20:30
@sbillig
sbillig merged commit 4d4452d into main Nov 10, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant