EIP-3337 · Stagnant · Core · 2021-03-06
EIP-3337: Frame pointer support for memory load and store operations
Proposed four EVM opcodes for a frame pointer (`SETFP`, `GETFP`, `MLOADFP`, `MSTOREFP`) so compilers could keep local variables in memory cheaply and escape the "stack too deep" limit.
What problem does it solve?
Most CPUs and VMs keep local variables, arguments and return addresses in a randomly accessible "call stack" region of memory, addressed relative to a frame pointer. The EVM instead keeps them on its evaluation stack, which can only reach the top 16 items with DUPn/SWAPn. Functions with many locals hit Solidity's familiar stack too deep error.
Compilers could use memory instead, but without a dedicated frame pointer that is expensive. Loading a frame-relative value today takes five operations:
| Before | Gas |
|---|---|
PUSHn x, PUSH1 0, MLOAD (read FP), ADD, MLOAD |
15 gas, ≥ 7 bytes |
With this EIP: PUSH1 x, MLOADFP |
6 gas, ≥ 3 bytes |
That makes memory locals only about twice as costly as a DUPn, rather than five times, and a frame-relative store becomes as cheap as SWAPn POP.
How it works
The EVM gains an internal frame pointer, a signed integer that starts at 0 in each execution, and four opcodes:
| Opcode | Byte | Gas | Effect |
|---|---|---|---|
SETFP |
0x5c |
3 | Pop a value and set the frame pointer to it |
GETFP |
0x5d |
3 | Push the current frame pointer |
MLOADFP |
0x5e |
3* | Like MLOAD, but address = operand + FP |
MSTOREFP |
0x5f |
3* | Like MSTORE, but address = operand + FP |
* Same cost as MLOAD/MSTORE, including memory expansion.
If operand + FP is negative, the instruction fails like an invalid opcode (all gas consumed, context reverted). There is deliberately no MSTORE8FP to save opcode space.
It is designed alongside EIP-3336, which proposed paged memory so that sparse use of memory (such as a stack growing downward from a high address) would not be priced as one huge linear block.
Sample code
How a compiler might use it for a function frame (illustrative assembly):
; prologue: allocate a 0x60-byte frame below the caller's frame
GETFP ; [old_fp]
DUP1 ; [old_fp, old_fp]
PUSH1 0x60
SWAP1
SUB ; [old_fp, old_fp - 0x60]
SETFP ; fp = old_fp - 0x60 (old_fp kept on stack to restore)
; local a = 42 (slot at fp + 0x00)
PUSH1 0x2a
PUSH1 0x00
MSTOREFP
; b = a + 1 (slot at fp + 0x20)
PUSH1 0x00
MLOADFP ; [old_fp, a]
PUSH1 0x01
ADD
PUSH1 0x20
MSTOREFP
; epilogue
SETFP ; restore fp = old_fp
Things to know
- Status is Stagnant; it was never scheduled for a network upgrade, and
FORK_BLOCKwas left TBD. - The opcode bytes it proposed have since been assigned to other instructions:
0x5cTLOADand0x5dTSTORE(EIP-1153),0x5eMCOPY(EIP-5656) and0x5fPUSH0(EIP-3855). Any revival would need new numbers. - The underlying "stack too deep" problem has mostly been tackled in other ways, such as compilers moving variables to memory automatically and proposals for deeper stack access like EIP-663.