# 摘要

Currently, SWAP and DUP instructions are limited to a stack depth of 16. Introduce two new instructions, SWAPn and DUPn, which lift this limitation and allow accessing the stack up to its full depth of 1024 items.

# 动机

Implementing higher level constructs, such as functions, on top of EVM will result in a list of input and output parameters as well as an instruction offset to return to.

The number of these arguments (or stack items) can easily exceed 16 and thus will require extra care from a compiler to lay them out in a way that all of them are still accessible.

Introducing SWAPn and DUPn will provide an option to compilers to simplify accessing deep stack items at the price of possibly increased gas costs.

# 规范

# Option A

Instructions DUPn (0xb0) and SWAPn (0xb1) are introduced, which take the top item from stack (referred to as n).

If n exceeds 1024 or the current stack depth is less than n, then a stack underflow exception is issued. If the current stack depth is at the limit, a stack overflow exception is issued. In both of these cases the EVM stops and all gas is consumed.

Otherwise

  • for DUPn the stack item at depth n is duplicated at the top of the stack
  • for SWAPn the top stack item is swapped with the item at depth n

The gas cost for both instructions is set at 3. In reality the cost for such an operation is 6 including the required PUSH.

Since both of these instructions require the top stack item to contain the position, it is still only possible to reach more than 16 stack items if there is at least one free stack slot.

This option has no effect no static analyzers, given no immediate value is introduced.

# Option A+

The difference to Option A is that DUPn and SWAPn must be preceded by a PUSHn opcode. Encountering DUPn and SWAPn without a preceding PUSHn results in out of gas.

# Option B

The difference to Option A is that DUPn and SWAPn do not take the value of n from the top stack item, but instead encode it as a 16-bit big endian immediate value following the opcode.

This results in wasting a byte in the cases of only referring to the top 255 stack items.

# Option C

This option extends Option B with two new instructions, DUPSn (0xb2) and SWAPSn (0xb3), where the value of n is encoded as an 8-bit immediate value following the opcode.

The value n has a range of 0 to 255, but otherwise the same rules apply as in Option A.

# 原理阐述

TBA

# 向后兼容

This has no effect on backwards compatibility.

# 测试用例

  • executing 602a600160026003600460056006600760086009600a600b600c600d600e600f60106011b0 should have 42 as the top stack item
  • executing 602a600160026003600460056006600760086009600a600b600c600d600e600f60106011b1 should have 42 as the top stack item

# 实现

TBA

# 参考引用

A similar proposal was made with EIP-174. Read the thread for some detailed discussion.

Rootstock RSKIP26 also introduced SWAPN and DUPN with Option A described above.

# 版权

Copyright and related rights waived via CC0.