---
eip: 3337
label: EIP-3337
title: Frame pointer support for memory load and store operations
status: Stagnant
type: Standards Track
category: Core
created: 2021-03-06
requires: 3336
official: https://eips.ethereum.org/EIPS/eip-3337
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3337.md
canonical: https://eips.huatuo.xyz/zh/eip-3337/
lang: zh
tldr: 提议了四个用于帧指针的 EVM 操作码（`SETFP`、`GETFP`、`MLOADFP`、`MSTOREFP`），让编译器能够低成本地把局部变量放在内存中，摆脱“stack too deep”的限制。
tags: [evm, opcodes, memory, compilers, core]
---

# EIP-3337: Frame pointer support for memory load and store operations

> Introduces four new opcodes for loading data from and storing data to memory offset by a frame pointer.

**TL;DR:** 提议了四个用于帧指针的 EVM 操作码（`SETFP`、`GETFP`、`MLOADFP`、`MSTOREFP`），让编译器能够低成本地把局部变量放在内存中，摆脱“stack too deep”的限制。

## 它解决什么问题？

大多数 CPU 和虚拟机把局部变量、参数和返回地址放在内存中一块可随机访问的"调用栈"区域，并相对于**帧指针**寻址。而 EVM 则把它们放在求值栈上，用 `DUPn`/`SWAPn` 只能访问栈顶的 16 个元素。局部变量很多的函数会碰到 Solidity 中常见的 *stack too deep* 错误。

编译器本可以改用内存，但没有专用的帧指针，这样做代价很高。目前加载一个相对于帧的值需要五个操作：

| 之前 | Gas |
| --- | --- |
| `PUSHn x`、`PUSH1 0`、`MLOAD`（读取 FP）、`ADD`、`MLOAD` | 15 gas，≥ 7 字节 |
| **采用本 EIP：** `PUSH1 x`、`MLOADFP` | 6 gas，≥ 3 字节 |

这样一来，内存中的局部变量的成本只有 `DUPn` 的约两倍，而不是五倍，相对于帧的存储也会变得和 `SWAPn POP` 一样便宜。

## 它如何运作

EVM 新增一个内部的**帧指针**，这是一个有符号整数，在每次执行开始时为 0，并新增四个操作码：

| 操作码 | 字节 | Gas | 作用 |
| --- | --- | --- | --- |
| `SETFP` | `0x5c` | 3 | 弹出一个值并把帧指针设为该值 |
| `GETFP` | `0x5d` | 3 | 压入当前帧指针 |
| `MLOADFP` | `0x5e` | 3* | 类似 `MLOAD`，但地址 = 操作数 + FP |
| `MSTOREFP` | `0x5f` | 3* | 类似 `MSTORE`，但地址 = 操作数 + FP |

\* 与 `MLOAD`/`MSTORE` 成本相同，包括内存扩展。

如果 `operand + FP` 为负数，该指令会像无效操作码一样失败（消耗所有 gas，上下文被回滚）。为节省操作码空间，刻意没有设置 `MSTORE8FP`。

它与 [EIP-3336](/eip-3336/) 一同设计，后者提议了分页内存，使得对内存的稀疏使用（例如从高地址向下增长的栈）不会被按一整块巨大的线性内存计价。

## 示例代码

编译器可能如何为函数帧使用它（示意性汇编）：

```text
; 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
```

## 需要注意

- 状态为 **Stagnant**；它从未被排入任何网络升级，`FORK_BLOCK` 一直是 TBD。
- 它提议的操作码字节后来已被分配给其他指令：`0x5c` `TLOAD` 和 `0x5d` `TSTORE`（[EIP-1153](/eip-1153/)）、`0x5e` `MCOPY`（[EIP-5656](/eip-5656/)）以及 `0x5f` `PUSH0`（[EIP-3855](/eip-3855/)）。任何复活该提案的尝试都需要新的编号。
- 底层的"stack too deep"问题已大多通过其他方式解决，例如编译器自动把变量移到内存中，以及像 [EIP-663](/eip-663/) 这样提议提供更深栈访问的方案。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-3337
