Skip to content

yul: invalidate the cached constant when a variable is assigned - #346

Closed
AntonD3 wants to merge 3 commits into
mainfrom
fix/yul-invalidate-stale-constant-on-assignment
Closed

AntonD3 wants to merge 3 commits into
mainfrom
fix/yul-invalidate-stale-constant-on-assignment

Conversation

@AntonD3

@AntonD3 AntonD3 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Depends on matter-labs/era-compiler-llvm-context → Add YulData::remove_constant.
This PR does not compile until that one is merged, because the context crate is pinned by
branch = "main".

The defect

The partial constant propagation keeps a per-function map of constants saved to variables
(YulData, a flat HashMap<String, BigUint>):

  • written by variable_declaration.rs:36-45 — caches a literal initializer
  • read by expression/mod.rs — re-attaches the constant to a freshly loaded value
  • consumed by function_call/mod.rs → eravm/evm/call.rs:33, which selects an EraVM
    extension intrinsic from the constant annotated on a call destination

assignment.rs stored the new value but never refreshed the entry. The broken invariant: the
constant annotation attached to a Yul value must equal that value on every control-flow path.

Because the annotation has a real consumer, a stale entry is wrong code, not a stale label:

let m1 := staticcall(0, 0xFFFC, 0, 0xFFFF, 0, 0)  // literal -> meta intrinsic (intended)
let addr := 0xFFFC                                 // caches 0xFFFC against `addr`
addr := 0x8002                                     // reassigned; cache NOT invalidated
let m2 := staticcall(0, addr, 0, 0xFFFF, 0, 0)     // BUG

The unoptimised IR shows store i256 32770, ptr %addr (0x8002) followed by
call i256 @llvm.eravm.meta() — no @__staticcall/@__farcall to 0x8002 is emitted anywhere.
The call whose runtime destination is 0x8002 was compiled as the EraVM meta extension. The
reverse also holds: a genuine selector later reassigned to an ordinary address still dispatches
the extension.

Reachability

Requires --enable-eravm-extensions and a variable that first holds a recognised simulation
selector (0xFFEB–0xFFFF) and is then reassigned. Deterministic for that pattern.

  • Not reachable from ordinary Solidity — solc-generated Yul SSA-izes these values.
  • Not present in the current system contracts — all 45 0xffff occurrences across the 25
    .yul files are bit masks (and(shr(224, versionedCodeHash), 0xffff)) or wider constants. No
    variable holds a simulation selector as a call destination, and none is reassigned. The system
    contracts are built with the flag, so this is where it would bite, and today it does not.
  • Zero corpus impact — this fix changed none of 59,595 recompiled verified mainnet contracts.

A genuine wrong-code bug with no known reachable caller. Worth fixing because the consumer makes
a stale annotation semantic, and because an invalidation-free cache is a hazard for any future
reader of the map.

The change

Scalar path: replace the entry when the new value is itself a known constant, drop it otherwise.
Tuple path: always drop, since a tuple element is loaded from memory and is never a known
constant.

let constant = value.constant.clone();
context.build_store(pointer, value.to_llvm())?;
let function = context.current_function();
let mut function = function.borrow_mut();
match constant {
    Some(constant) => function
        .yul_mut()
        .insert_constant(identifier.inner, constant),
    None => function
        .yul_mut()
        .remove_constant(identifier.inner.as_str()),
}

Two things for the reviewer to decide

1. Insert-or-drop, or drop-only? The scalar path inserts when the new value is a known
constant, mirroring variable_declaration. That upholds the invariant exactly, but it is a
behaviour change beyond pure invalidation: let a := f(); a := 0xFFFC; now dispatches the
extension where it previously did not. Drop-only is strictly more conservative but silently loses
an intended dispatch in let a := 0xFFFC; a := 0xFFFC;. Neither is purely safe; insert-or-drop is
the semantically faithful one, which is why it is written this way.

2. The block-scoping gap is NOT closed. There are two independent invalidation failures. This
fixes assignment. The map is still keyed by bare variable name for the whole function with no
block scoping, so a shadowed name in an inner block still aliases the outer entry. Closing that
means scoping the map — a larger change, deliberately out of scope here.

Testing

cargo check and cargo fmt --all -- --check clean, against the context PR applied via a local
[patch] override.

One gap, stated plainly: the regression gate I wanted — build the system contracts with and
without the fix and confirm byte-identical output — was not run. A release build of zksolc
fails on my machine with a libffi linker error in LLVM's Interpreter (_ffi_type_* symbols),
unrelated to this change and absent from the type check. The reachability argument above is
static only. Running that comparison before merging is the one outstanding item.

🤖 Generated with Claude Code

The partial constant propagation caches a literal initializer against a
variable name in the per-function Yul constant map. Assignment stored a new
value but never refreshed that entry, so a later read of the variable
re-attached the stale constant to the new value.

That annotation has a real consumer: with `--enable-eravm-extensions`, the
external-call lowering selects an EraVM extension intrinsic from the constant
annotated on the destination argument. A variable that first holds a simulation
selector and is then reassigned to an ordinary address therefore still dispatches
the extension -- an intended external call is compiled as an unrelated
instruction, with no diagnostic.

Both binding paths are covered: the scalar path now replaces the entry when the
new value is itself a known constant and drops it otherwise; the tuple path
always drops it, since a tuple element is loaded from memory and is never a
known constant.

Requires `YulData::remove_constant` from the companion era-compiler-llvm-context
change.

Known gap, not addressed here: the map is keyed by bare variable name for the
whole function, with no block scoping, so a shadowed name in an inner block
still aliases the outer entry. That is a second, independent invalidation
failure.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@AntonD3

AntonD3 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor Author

@hedgar2017 thank you for the reviews, they've been really helpful. If you have time, could I also ask you to take a look at this one(it's tied with matter-labs/era-compiler-llvm-context#95)? You have the most context on this code.

AntonD3 and others added 2 commits October 26, 2026 12:07
A Yul variable first holds the `meta` simulation selector (0xFFFC) and is
then reassigned to an ordinary address. With the cached constant left
stale, the following staticcall is compiled as the `meta` extension and no
call is emitted at all:

      meta  r1

instead of a call to 0x8002:

      add   32770, r0, r2
      call  r0, @__staticcall, @DEFAULT_UNWIND

The test asserts the call is present and that no `meta` instruction is
emitted. It fails against an unpatched compiler.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This crate does not compile against era-compiler-llvm-context main until
matter-labs/era-compiler-llvm-context#95 adds `YulData::remove_constant`.
Pinning the branch lets CI run here in the meantime.

Revert this commit once that PR has merged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@codecov

codecov Bot commented Oct 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 66.66667% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.53%. Comparing base (bdd4826) to head (8481145).

Files with missing lines Patch % Lines
...er-solidity/src/yul/parser/statement/assignment.rs 66.66% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #346      +/-   ##
==========================================
- Coverage   75.54%   75.53%   -0.02%     
==========================================
  Files         124      124              
  Lines       11308    11323      +15     
==========================================
+ Hits         8543     8553      +10     
- Misses       2765     2770       +5     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@akiramenai akiramenai left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AntonD3 could you give me more context on how these simulations are supposed to behave?

My understanding is that missing a simulation is acceptable. The detection only handles specific patterns, so a statically known 0xFFFC can still be compiled as a regular call, e.g.:

    let a := add(0xFFFB, 1)
    mstore(0, staticcall(0, a, 0, 0, 0, 0))   // regular call, not meta

The feature is poorly designed in that respect, but I don't think that needs fixing. The real problem is the opposite case: a != 0xFFFC at runtime, but the call is still compiled to meta.

The PR fixes the straight-line case, but three such cases remain:

  1. A variable left over from a sibling block (not fixed by the PR):
    { let a := 0xFFFC }
    {
        let a := calldataload(0)
        mstore(0, staticcall(0, a, 0, 0, 0, 0))   // meta
    }
  1. A loop, where the call comes before the reassignment (not fixed by the PR):
    let a := 0xFFFC
    for { let i := 0 } lt(i, 2) { i := add(i, 1) } {
        mstore(0, staticcall(0, a, 0, 0, 0, 0))   // meta on both iterations
        a := 0x8002
    }
  1. A conditional assignment of a literal (introduced by the PR; main emits a regular call here):
    let a := calldataload(0)
    if calldataload(32) { a := 0xFFFC }
    mstore(0, staticcall(0, a, 0, 0, 0, 0))   // meta even if the condition is false

while cases 1-2 are present in main even before the patch, 3 is introduced by the patch and need to be fixed.

@AntonD3

AntonD3 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

#349 is going to replace it

@AntonD3 AntonD3 closed this Nov 6, 2026
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.

2 participants