Skip to content

Commit 48cc8a9

Browse files
Optimize muldiv (#4494)
Co-authored-by: Francisco <[email protected]>
1 parent fa68073 commit 48cc8a9

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

.changeset/pink-suns-mix.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': patch
3+
---
4+
5+
`Math`: Optimized stack operations in `mulDiv`.

contracts/utils/math/Math.sol

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,11 +124,10 @@ library Math {
124124
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
125125
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
126126
// variables such that product = prod1 * 2^256 + prod0.
127-
uint256 prod0; // Least significant 256 bits of the product
127+
uint256 prod0 = x * y; // Least significant 256 bits of the product
128128
uint256 prod1; // Most significant 256 bits of the product
129129
assembly {
130130
let mm := mulmod(x, y, not(0))
131-
prod0 := mul(x, y)
132131
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
133132
}
134133

@@ -163,8 +162,7 @@ library Math {
163162
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
164163
// See https://cs.stackexchange.com/q/138556/92363.
165164

166-
// Does not overflow because the denominator cannot be zero at this stage in the function.
167-
uint256 twos = denominator & (~denominator + 1);
165+
uint256 twos = denominator & (0 - denominator);
168166
assembly {
169167
// Divide denominator by twos.
170168
denominator := div(denominator, twos)

0 commit comments

Comments
 (0)