Safety properties equivalent to [EIP-615](https://eips.ethereum.org/EIPS/eip-615) — including valid jump destinations — are ensured by following a few simple rules, which are validated at contract creation time — not runtime — by the provided algorithm, and without imposing syntactic constraints.
The EVM does not provide subroutines as a primitive. Instead, calls can be synthesized by fetching and pushing the current program counter on the data stack and jumping to the subroutine address; returns can be synthesized by getting the return address to the top of the stack and jumping back to it. These conventions are more costly than necessary, and impede static analysis of EVM code, especially rapid validation of some important safety properties.
Facilities to directly support subroutines are provided by all but one of the real and virtual machines programmed by the lead author, including the Burroughs 5000, CDC 7600, IBM 360, DEC PDP 11 and VAX, Motorola 68000, a few generations of Intel silicon, Sun SPARC, UCSD p-Machine, Sun JVM, Wasm, and the sole exception — the EVM. In whatever form, these operations provide for
> We also wish to be able to arrange for the splitting up of operations into subsidiary operations. This should be done in such a way that once we have written down how an operation is done we can use it as a subsidiary to any other operation.
> When we wish to start on a subsidiary operation we need only make a note of where we left off the major operation and then apply the first instruction of the subsidiary. When the subsidiary is over we look up the note and continue with the major operation. Each subsidiary operation can end with instructions for this recovery of the note. How is the burying and disinterring of the note to be done? There are of course many ways. One is to keep a list of these notes in one or more standard size delay lines, (1024) with the most recent last. The position of the most recent of these will be kept in a fixed TS, and this reference will be modified every time a subsidiary is started or finished...
We propose to use Turing's simple mechanism, long known to work well for virtual stack machines, as specified below. Note that this specification is entirely semantic. It constrains only stack usage and control flow and imposes no syntax on code beyond being a sequence of bytes to be executed.
We introduce one more stack into the EVM in addition to the existing `data stack`, known as the `return stack`. The `return stack` is limited to `1024` items. This stack supports three new instructions for subroutines.
* _If a resulting `PC` to be executed is beyond the last instruction then the opcode is implicitly a `STOP`, which is not an error._
* _Values popped off the `return stack` do not need to be validated, since they are alterable only by `JUMPSUB` and `RETURNSUB`._
* _The description above lays out the semantics of this feature in terms of a `return stack`. But the actual state of the `return stack` is not observable by EVM code or consensus-critical to the protocol. (For example, a node implementor may code `JUMPSUB` to unobservably push `PC` on the `return stack` rather than `PC + 1`, which is allowed so long as `RETURNSUB` observably returns control to the `PC + 1` location.)_
* _The `return stack is the functional equivalent of Turing's "delay line" of "where we left off"._
We need [EOF Static Relative Jumps](https://github.com/ethereum/evmone/pull/351) or the equivalent to define and validate the rules for contract safety. These jumps — `RJUMP offset` and `RJUMPI offset` — transfer control to a location in the bytecode at a fixed offset relative to the current `PC`.
We modeled this design on the proven, archetypal Forth virtual machine of 1970. It is a two-stack design — the data stack is supplemented with a return stack to support jumping into and returning from subroutines, as specified above. The return address (Turing's "note") is pushed onto the return stack when calling, and the stack is popped into the `PC` when returning.
The alternative design is to push the return address and the destination address on the data stack before jumping, and to pop the data stack and jump back to the popped `PC` to return. We prefer the separate return stack because it ensures that the return address cannot be overwritten or mislaid, uses fewer data stack slots, and obviates any need to swap the return address past the arguments or return values on the stack. Crucially, a dynamic jump is not needed to implement subroutine returns, allowing for deprecation of `JUMP` and `JUMPI`.
These changes are compatible with using [EIP-3337](https://eips.ethereum.org/EIPS/eip-3337) to provide stack frames, by associating a frame with each subroutine, as sketched out in the Appendix below.
The _low_ cost of `JUMPSUB` is justified by needing only about six Go operations, pushing the return address on the return stack, and decoding the two byte destination to the `PC`. The _verylow_ cost of `RETURNSUB` is justified by needing only about three Go operations to pop the return stack into the `PC`. No 256-bit arithmetic or checking for valid destinations is needed.
These changes do introduce new flow control instructions, so any software which does static/dynamic analysis of EVM code needs to be modified accordingly. The `JUMPSUB` semantics are similar to `JUMP` (but jumping to a `BEGINSUB`), whereas the `RETURNSUB` instruction is different, since it can 'land' on any opcode (but the possible destinations can be statically inferred).
Safety and amenability to static analysis of valid programs are comparable to [EIP-615](https://eips.ethereum.org/EIPS/eip-615), but without imposing syntactic constraints, and thus with improved low-level optimizations (as shown above.) Validity can ensured by following the rules given in the next section, and programs can be validated with the provided algorithm. The validation algorithm is simple and bounded by the size of the code, allowing for validation at creation time. And compilers can easily follow the rules.
_Execution_ is as defined in the [Yellow Paper](https://ethereum.github.io/yellowpaper/paper.pdf) — a sequence of changes to the EVM state. The conditions on valid code are preserved by state changes. At runtime, if execution of an instruction would violate a condition the execution is in an exceptional halting state. The Yellow Paper defines five such states.
We would like to consider EVM code valid iff no execution of the program can lead to an exceptional halting state, but we must be able to validate code in linear time to avoid denial of service attacks. So in practice, we can only partially meet these requirements. Our validation algorithm does not consider the code’s data and computations, only its control flow and stack use. This means we will reject programs with any invalid code paths, even if those paths are not reachable at runtime. Further, conditions *1* and *2* — Insufficient gas and stack overflow — must in general be checked at runtime. Conditions *3*, *4*, and *5* cannot occur if the code conforms to the following rules.
*Rule 0*, deprecating `JUMP` and `JUMPI`, forbids dynamic jumps. Absent dynamic jumps another mechanism is needed for subroutine returns, as provided here.
Jump destinations are currently checked at runtime. Static jumps allow them to be validated at creation time, per *rule 1* and *rule 2*. *Note: Valid instructions are not part of immediate data.*
For *rule 3* and *rule 4* we need to define `stack depth`. The Yellow Paper has the `stack pointer` or `SP` pointing just past the top item on the `data stack`. We define the `stack base` as where the `SP` pointed before the most recent `JUMPSUB`, or `0` on program entry. So we can define the `stack depth` as the number of stack elements between the current `SP` and the current `stack base`.
Given our definition of `stack depth`, *rule 3* ensures that control flows which return to the same place with a different `stack depth` are invalid. These can be caused by irreducible paths like jumping into loops and subroutines, and calling subroutines with different numbers of arguments. Taken together, these rules allow for code to be validated by following the control-flow graph, traversing each edge only once.
The following is a pseudo-Go implementation of an algorithm for enforcing program validity – being a symbolic execution that recursively traverses the bytecode, following its control flow and stack use and checking for violations of the rules above.
This algorithm runs in time equal to `O(vertices + edges)` in the program's control-flow graph, where vertices represent control-flow instructions and the edges represent basic blocks – thus the algorithm takes time proportional to the size of the bytecode.
(For simplicity we assume an `advance_pc()` routine to skip immediate data and `removed_items()` and `added_items()` functions that return the effect of each instruction on the stack. We also don't specify `JUMPTABLE` — which amounts to a loop over `RJUMP`.)
In this example. the JUMPSUB is on the last byte of code. When the subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, and not exit with error
Given [EIP-3337](https://eips.ethereum.org/EIPS/eip-3337) — which introduces a frame pointer register `FP` relative to which which memory can be addressed , we can create a frame stack — a list of data frames in memory for arguments and local variables. Two conventions are typical — either create the frame before calling the subroutine, or create the frame after the `BEGINSUB`. Adding these two instructions to EIP-3337 would ease the way. They are modeled on the corresponding Intel opcodes.
> Write the current `FP` to memory as with MSTOREF at `FP - frame_size`, then set `FP` to `FP - frame size`.
This a shorthand for
```
MSTOREF
GETFP
PUSH frame_size
SUB
SETFP
```
This should be placed either before a `JUMPSUB` operation or after a `BEGINSUB`, depending on the calling convention. Repeated calls to `ENTER` create a stack of frames, linked by their `previous FP` field. The stack grows towards lower addresses in memory, as is the common, efficient practice.
> Restores `FP` to the value which was stored at offset `FP` in memory by the most recent `ENTER`, thus popping a frame off of the stack of frames. This a shorthand for
```
MLOADF
SETFP
```
This should be placed after the `JUMPSUB` operation or before the `RETURNSUB`– depending on the calling convention – to pop the most recent frame from the call stack.
These operations would be especially useful if the gas formula for memory was reinterpreted so that writes from the top of memory down (equivalently, from -1 down, twos-complement) are charged the same gas as writes from the bottom of memory up.
If _a_, _b_ and memory offsets in general are allowed to be negative the formula gives the desired results – stack memory can grow from the top down, and heap memory can be allocated from the bottom up, without address conflicts or excessive gas charges.
A.M. Turing, [Proposals for the development in the Mathematics Division of an Automatic Computing Engine (ACE)](http://www.alanturing.net/turing_archive/archive/p/p01/P01-001.html) Report E882, Executive Committee, NPL 1946
Greg Colvin, Brooklyn Zelenka, Paweł Bylica, Christian Reitwiessner, [EIP-615: Subroutines and Static Jumps for the EVM](https://eips.ethereum.org/EIPS/eip-615), 2016-2019