EIP-663 · Stagnant · Core · 2017-07-03
EIP-663: SWAPN, DUPN and EXCHANGE instructions
Proposed DUPN, SWAPN and EXCHANGE opcodes for EOF code, so compilers can reach stack items deeper than the current 16-slot limit of DUP and SWAP.
What problem does it solve?
The EVM stack holds up to 1,024 items, but DUP1–DUP16 and SWAP1–SWAP16 can only reach the top 16. When a function has many local variables, parameters and return values, compilers run out of reachable slots. This is Solidity's familiar "stack too deep" error. Today compilers work around it by moving values to memory, which makes code larger, slower and harder to optimize.
How it works
The proposal adds three instructions. Each takes a 1-byte immediate argument imm written into the code right after the opcode:
| Opcode | Name | Effect (1-based depth) |
|---|---|---|
0xe6 |
DUPN imm |
n = imm + 1; copy the n-th item to the top |
0xe7 |
SWAPN imm |
n = imm + 1; swap the top with the (n+1)-th item |
0xe8 |
EXCHANGE imm |
n = (imm >> 4) + 1, m = (imm & 0x0F) + 1; swap items n+1 and n+m+1 |
So DUPN and SWAPN reach up to 256 items deep. EXCHANGE swaps two items below the top without touching the top. Normally that takes three instructions (for example SWAP2 SWAP3 SWAP2), and stack-scheduling compilers need it often. All three cost 3 gas, the same as DUP/SWAP, because they are just pointer swaps.
The instructions are valid only in EOF code (EIP-3540). In legacy bytecode they remain undefined and halt. EOF's validation makes them safe:
- Relative jumps (EIP-4200) may not land on an immediate byte.
- Stack validation (EIP-5450) checks at deploy time that the stack is deep enough for each use.
The argument is a fixed immediate, not a value taken from the stack, so static analysis and auditing tools can still follow the stack.
Sample code
Illustrative EOF assembly (each line is shown on its own, starting from the same stack):
// stack (top first): a b c d ... x(20th) ...
DUPN 0x13 // n = 20 -> copies x to the top
SWAPN 0x13 // n = 20 -> swaps top with the 21st item
EXCHANGE 0x12 // n = 2, m = 3 -> swaps the 3rd and 6th items
Encoded bytes: e6 13 e7 13 e8 12.
Things to know
- This proposal is Stagnant. It depends on EOF, and EOF (EIP-7692) has not been activated on Ethereum mainnet.
- EIP-8024 is a follow-up that brings
SWAPN,DUPNandEXCHANGEto legacy bytecode, with an encoding designed not to break existing jump destinations. Look there for the current direction. - For Solidity users, the practical fix for "stack too deep" today is still the IR-based pipeline (
--via-ir), or restructuring code into structs or smaller functions.