Skip to content

UnusedStoreEliminator: Fix UnusedStoreEliminator removing stores that are still read - #17291

Draft
rodiazet wants to merge 9 commits into
developfrom
use-versioned-vars
Draft

rodiazet wants to merge 9 commits into
developfrom
use-versioned-vars

Conversation

@rodiazet

@rodiazet rodiazet commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

UnusedStoreEliminator recorded store locations as variable names and assumed their values never change. This does not hold for variables reassigned in a branch, nor for stores in a loop whose location differs between iterations. A later read of the original location then went unnoticed and the store was removed.

Store locations are now recorded as KnowledgeBase offsets relative to the value a variable had when the store was executed, so they stay valid after variables are reassigned. Each execution of a store keeps its own location, so the two walks of a loop body are tracked separately. The step no longer relies on SSAValueTracker.

It’s a draft because I haven’t added the bug to the bug list and updated the change log.

The first commit is the most important. The rest are tests and optimisations. It’s better to start reviewing from the first commit to get the idea of the change.

AI Disclosure

Claude Opus 5.5 assisted in preparing this PR.

This comment was marked as resolved.

This comment was marked as resolved.

@rodiazet
rodiazet force-pushed the use-versioned-vars branch 3 times, most recently from e8641b3 to 3cbd046 Compare November 26, 2026 14:09
@rodiazet
rodiazet requested a balanced review from Copilot November 27, 2026 10:54

This comment was marked as resolved.

@rodiazet

Copy link
Copy Markdown
Contributor Author
Baseline: 0.8.40-ci.2026.11.26+commit.1a85c6b9.Linux.g++ n=3
Target:   0.8.40-ci.2026.11.27+commit.f6235866.Linux.g++ n=3

Summary
=======

n          = number of benchmarks in the row
geomean Δ% = GM(target / base) - 1, GM over benchmarks; benchmarks weigh equally
total Δ%   = (Σ target - Σ base) / Σ base; large benchmarks dominate
min/max Δ% = best/worst single-benchmark Δ%
top lists  = changes passing a Welch t-test with |Δ%| ≥ 0.1%

Metric           Pipeline  n   geomean Δ%  total Δ%  min Δ%  max Δ%
---------------  --------  --  ----------  --------  ------  ------
cpu_time         ir        71  -1.05%      -0.68%    -2.38%  +0.52%
wall_time        ir        71  -1.01%      -0.68%    -2.39%  +2.67%
peak_rss         ir        71  +0.01%      +0.02%    -0.57%  +0.17%
cache_miss_rate  ir        71  +0.32%      +0.33%    -4.96%  +1.58%
creation_size    ir        70  0.0%        0.0%      0.0%    0.0%  
runtime_size     ir        70  0.0%        0.0%      0.0%    0.0%  
gas_used         ir        40  0.0%        0.0%      0.0%    0.0%  

=== cpu_time: largest regressions (1 of 1) ===

Benchmark        Pipeline  Base     Target   Δ%    
---------------  --------  -------  -------  ------
solidity-chains  ir        2.6282s  2.6419s  +0.52%

=== cpu_time: largest improvements (5 of 63) ===

Benchmark                    Pipeline  Base     Target   Δ%    
---------------------------  --------  -------  -------  ------
tether-usdt                  ir        0.4163s  0.4064s  -2.38%
usdc-fiattoken-v2-2          ir        3.0569s  3.0038s  -1.74%
uniswap-v4-position-manager  ir        1.4494s  1.4245s  -1.72%
poap                         ir        1.1799s  1.1598s  -1.71%
chainlink-link-token         ir        0.1337s  0.1314s  -1.68%

=== creation_size: no significant changes ===

=== gas_used: no significant changes ===


@blishko blishko 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.

This seems very promising!

Could we put the optimizations to a separate PR? Like the KnowledgeBase change map -> unordered_map, for example.
It would be easier to review just the core necessary for the fix.
I am not sure which commits are necessary for the fix and which are just performance improvements.

@rodiazet

rodiazet commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Ok. I will stack the PRs. The KB change does not change anything in develop branch though.

@rodiazet
rodiazet force-pushed the use-versioned-vars branch 3 times, most recently from 980304c to 551dd67 Compare December 1, 2026 10:18
@rodiazet
rodiazet added this pull request to stack #17346 December 1, 2026 10:27

@clonker clonker left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I just have a few comments but in general it seems like the fix (for the sake of fixing the bug) is perhaps too much and could be separated out (by removing the change to knowledge base, @blishko probably has some ideas there, or doing it as i suggest below and first just fix the bug as cheaply as possible and do performance stuff later).

For example, you could just keep locations as variable names and the KnowledgeBase in SSA mode, as on develop. Then remove every variable from the SSA value map whose value refers to a variable not in the map, repeating until nothing changes and before the second walk of a loop body, mark every active store whose location's base variable is declared inside the loop as used. That should be relatively small and self-contained at the expense of a few more stores remaining.

Comment thread libyul/optimiser/KnowledgeBase.h Outdated
Comment on lines +182 to +185
std::unordered_map<VersionedVariable, CachedOffset, VersionedVariableHash> m_offsets;

/// Current version of each variable that changed at least once.
std::map<YulName, std::size_t> m_currentVersions;
std::unordered_map<YulName, std::size_t> m_currentVersions;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this change doesn't really belong in a bugfix pr, can we extract it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Comment on lines +49 to +50
* UnusedStoreEliminator is an optimizer component that removes sstore and memory store statements if conditions are met
* for their removal.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this seems unnecessary to change, it is the UnusedStoreEliminator header after all

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I added this because this PR moves some structures before the UnusedStoreEliminator. I wanted to make sure that we are talking about this class but not the structure right below. I can revert it if think it’s still unnecessary.

Comment on lines +60 to +74
* To decide whether two operations can touch the same location, the step keeps track of the values of variables
* while it walks the code. Each location is recorded as a constant offset from the value a variable had at that
* point in the code. For example, in `let q := add(p, 32) mstore(q, 1)` the location of the store is recorded
* as 32 more than the value `p` had when the store was executed. When a variable is reassigned, it is treated
* as a new variable, so a location recorded earlier keeps referring to the old value. This is what allows a store
* to be compared correctly with reads and writes that happen later, after some of the variables have changed.
* Where control flow joins, the values of variables assigned inside a branch or loop are forgotten.
*
* A store whose result might still be read is remembered together with the location it wrote to. A store inside
* a loop can write to a different location in each iteration, as `mstore(p, 1)` does in a loop body like
* `let p := sload(0) mstore(p, 1) sstore(0, add(p, 32))`. Loop bodies are walked twice, so such a store is
* remembered twice, once with the location from each walk. The store is only removed if neither of these
* locations is read later. Each walk starts by forgetting the values of the variables assigned in the loop,
* because a store might be read any number of iterations later. Without that, the second walk would treat
* a location from the first walk as if it was always read in the very next iteration.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I found this very hard to parse. What do you think about this?

Suggested change
* To decide whether two operations can touch the same location, the step keeps track of the values of variables
* while it walks the code. Each location is recorded as a constant offset from the value a variable had at that
* point in the code. For example, in `let q := add(p, 32) mstore(q, 1)` the location of the store is recorded
* as 32 more than the value `p` had when the store was executed. When a variable is reassigned, it is treated
* as a new variable, so a location recorded earlier keeps referring to the old value. This is what allows a store
* to be compared correctly with reads and writes that happen later, after some of the variables have changed.
* Where control flow joins, the values of variables assigned inside a branch or loop are forgotten.
*
* A store whose result might still be read is remembered together with the location it wrote to. A store inside
* a loop can write to a different location in each iteration, as `mstore(p, 1)` does in a loop body like
* `let p := sload(0) mstore(p, 1) sstore(0, add(p, 32))`. Loop bodies are walked twice, so such a store is
* remembered twice, once with the location from each walk. The store is only removed if neither of these
* locations is read later. Each walk starts by forgetting the values of the variables assigned in the loop,
* because a store might be read any number of iterations later. Without that, the second walk would treat
* a location from the first walk as if it was always read in the very next iteration.
* Locations are regoraded as constant offsets from a variable, e.g., `add(p, 32)` as `p + 32`.
* Every assignment or declaration gives the variable a new version and a recorded location keeps the version it was recorded with.
* Therefore, reassigning `p` later does not move it.
* Two locations are only known to be equal or different if they are offsets from the same version of a variable.
* After a branch or a loop, the variables assigned inside it get a new version.
*
* Loop bodies are walked twice.
* A store in a loop is recorded once per walk, each time with the location from that walk, and is kept if either location may be read later.
* Each walk starts by giving the variables assigned in the loop a new version.
* Therefore, a location that depends on them cannot be compared with one from the other walk.
* This matters because a value stored in one iteration may be read in any later iteration, not only in the next.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied

Comment thread libyul/optimiser/KnowledgeBase.h Outdated
{
std::size_t operator()(VersionedVariable const& _variable) const
{
std::size_t hash = static_cast<std::size_t>(_variable.name.hash());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

is this actually sane? emscripten targets 32 bits.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moved to the separated PR. Comment also referenced there. https://github.com/argotorg/solidity/pull/17349/changes#r4754254444

Comment thread libyul/optimiser/KnowledgeBase.h Outdated
Comment on lines +127 to +131
bool operator==(VariableOffset const&) const = default;
bool operator<(VariableOffset const& _other) const
{
return std::tie(reference, offset) < std::tie(_other.reference, _other.offset);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
bool operator==(VariableOffset const&) const = default;
bool operator<(VariableOffset const& _other) const
{
return std::tie(reference, offset) < std::tie(_other.reference, _other.offset);
}
std::strong_ordering operator<=>(VariableOffset const&) const = default;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

Comment on lines +99 to +110
bool operator<(UnusedStoreEliminatorActiveStore const& _other) const
{
return
std::tie(statement, operation.location, operation.effect, operation.start, operation.length) <
std::tie(
_other.statement,
_other.operation.location,
_other.operation.effect,
_other.operation.start,
_other.operation.length
);
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this should use a defaulted spaceship operator

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

if (
_value &&
_variables.size() == 1 &&
!VariableReferencesCounter::countReferences(*_value).count(_variables.front())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this should use contains

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

@rodiazet
rodiazet force-pushed the use-versioned-vars branch 2 times, most recently from cf6c185 to fb3eeb1 Compare December 1, 2026 12:59
@rodiazet

rodiazet commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed the comments. Regarding the general comment I lean towards some general solution and don’t wanna leave other improvements for later because we know that it will probably never happen. Let’s wait for Matrin comments.

I have to analyse your proposal deeper but if I get it right it will have this property.

let a, b := f() // SSAValueTracker skips multi variable declaration.
let q := add(a, 32) // Because of the above this will be pruned from the map with no reason. 
mstore(q, x) // This won’t be removed. Right?
mstore(q, y)

@clonker

clonker commented Dec 1, 2026

Copy link
Copy Markdown
Member

I don't think that is the right approach for a bugfix pr.

@rodiazet

rodiazet commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

It addressed concerns from the previous version. #16459 (comment)
#16459 (comment)

@blishko

blishko commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

It addressed concerns from the previous version. #16459 (comment) #16459 (comment)

That was my opinion back then. Feel free to push back against my opinion :)
My opinion has also evolved since then.
Given recent events I think it's good to establish the practice of separating the bug fixes from optimizations and refactoring.
Bug fixes should ideally be minimal changes, since understandability for review is a very important factor.

blishko and others added 9 commits December 3, 2026 17:36
…nd loop iterations

The knowledge base evaluates the values of SSA variables lazily. A value that
references a reassigned variable was evaluated with the value that variable has
at the point of use, not the one it had at the declaration. So copies of the same
variable taken at different points were considered equal. Such values are now
treated as unknown.

Variables declared inside a loop have the same name but a different value in each
iteration. A store that is still active when the next iteration starts and whose
location refers to such a variable cannot be compared with the operations of the
following iterations, so it is now marked as used.

See #17274.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants