argotorg / argotorg/solidity

Optimization possibility of memory usage for loops

Open
#9,046 3 comments 0 reactions 0 assignees View on GitHub
epic effort high impact needs design optimizer selected for development
Dominant language
C++
Stars
25.7k
Forks
6.2k
Avg merge
2d 19h
Merged PRs (30d)
29

Description

_[This issue has been discussed with @axic, and reported here to be tracked and further discussed.]_

## Description

In the current code generation (even with the optimization enabled with the flags `--optimize --optimize-runs 5000000`), there is still room for improvement of the memory usage for loops.

Specifically, if we have `sha256(abi.encodePacked(arg1, arg2))` in a loop, every iteration consumes new memory entries to store the arguments `arg1` and `arg2`, even if the same memory entries can be reused over the whole iterations.

For example, for [this loop](https://github.com/axic/eth2-deposit-contract/blob/r1/deposit_contract.sol#L78-L84), the first iteration consumes the following entries to store the arguments:
```
memory[128:159] := 64 // the size of arguments
memory[160:191] :=
memory[192:223] :=
```
and then the second iteration consumes the following:
```
memory[224:255] := 64 // the size of arguments
memory[256:287] :=
memory[288:319] :=
```
and so on.

In the end, the total 3072 (= 32 iterations * 96 bytes per iteration) bytes of memory are consumed to compute the `sha256` function, while the optimized behavior would consume only the 96 bytes for the whole iterations. This ended up wasting ~300 gas unit.

## Environment

- Compiler version: `0.6.8+commit.0bbfe453.Linux.g++`
- Command line flags: `--optimize --optimize-runs 5000000`

## Steps to Reproduce

Compile `https://github.com/axic/eth2-deposit-contract/blob/r1/deposit_contract.sol` with the following command line flags:
```
$ solc deposit_contract.sol --asm --optimize --optimize-runs 5000000
```
Then see the generated assembly code for the aforementioned loop (i.e., code blocks between `tag_123` and `tag_124`).

(I'll provide a minimal example later.)

Contributor guide

Open the contributing guide

Research direction

Compile deposit_contract.sol with solc using --asm --optimize --optimize-runs 5000000, then inspect the assembly between tag_123 and tag_124. Compare the loop's memory allocation across iterations; done means the argument storage is reused rather than growing by 96 bytes per iteration, with the resulting memory and gas usage improved.

Written by the indexing model from the issue text.

Assessment

Tech stack
solidity
Domain
blockchain, compilers, performance
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.