Introduce a new instruction, MULDIV(x, y, z), to perform ((x * y) / z) % 2**256 in 512-bit precision. z = 0 is a special case for (x * y) / 2**256.
Fixed point operations in high level languages are very commonly used on Ethereum, especially in the domain of financial applications.
While fixed point addition and subtraction can be done with merely add and sub respectively, being able to efficiently do fixedpoint multiplication and division is a very sought after feature. A commonly used workaround relies on a mulmod-based, rather complex implementation (taking around 50 instructions, excluding stack manipulation). This instruction reduces that to a single opcode.
A secondary use case is likely in cryptographic applications, where the muldiv instruction allows full precision 256x256->512 multiplication. mul(x y) (or muldiv(x, y, 1)) computes the lower order 256 bits and muldiv(x, y, 0) computes the higher order 256 bits.
Finally we aimed to provide an instruction which can be efficiently used both in checked and unchecked arithmetic use cases. By checked we mean to abort on conditions including division-by-zero and wrapping behaviour.
A new instruction is introduced: MULDIV (0x1e).
x, then y and z.z == 0, r = (uint512(x) * y) / 2**256.r = (uint512(x) * y / z) % 2**256, where the intermediate calculation is performed with 512-bit precision.r on the stack.The cost of the instruction is 8 gas (aka mid), the same as for addmod and mulmod.
All the arithmetic instructions in EVM handle division or modulo 0 specially: the instructions return 0. We have decided to break consistency in order to provide a flexible opcode, which can be used to detect wrapping behaviour.
Alternate options include:
While this feature is clever and useful, callers must be aware that unlike other EVM instructions, passing 0 will have a vastly different behaviour.
The order of arguments matches addmod and mulmod.
This is a new instruction not present prior.
TBA
Copyright and related rights waived via CC0.