Skip to content

Commit 1044b7f

Browse files
committed
Add 2 more Expr simplifications related to negative numbers
Cleanup Update
1 parent dcfe657 commit 1044b7f

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1616
controlled via `merge-max-budget`
1717

1818
## Changed
19+
- Simplifier now rewrites `Mul(-1, x)` and `~x + 1` to `Sub(0, x)`
1920
- `AbiFunction` and `AbiBytes` parser is now more strict
2021
- We now check length of AbiArrayDynamic and don't crash in case it's too large
2122
- SMT queries now run in separate processes, which allows us to better manage

src/EVM/Expr.hs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1212,6 +1212,10 @@ simplifyNoLitToKeccak e = untilFixpoint (mapExpr go) e
12121212
| b == c = a
12131213
| otherwise = sub (add a b) c
12141214

1215+
-- Negation: ~x + 1 = 0 - x (two's complement)
1216+
go (Add (Lit 1) (Not b)) = Sub (Lit 0) b
1217+
go (Add (Lit 1) (Xor (Lit a) b)) | a == maxLit = Sub (Lit 0) b
1218+
12151219
-- add / sub identities
12161220
go (Add a b)
12171221
| b == (Lit 0) = a
@@ -1271,6 +1275,7 @@ simplifyNoLitToKeccak e = untilFixpoint (mapExpr go) e
12711275
go (Mul a b) = case (a, b) of
12721276
(Lit 0, _) -> Lit 0
12731277
(Lit 1, _) -> b
1278+
(Lit v, _) | v == maxLit -> Sub (Lit 0) b
12741279
_ -> mul a b
12751280

12761281
-- Some trivial (s)div eliminations

test/EVM/Expr/ExprTests.hs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,15 @@ basicSimplificationTests = testGroup "Basic simplification tests"
279279
a = successPath [PEq (Add (Lit 1) (Lit 2)) (Sub (Lit 4) (Lit 1))]
280280
b = Expr.simplify a
281281
assertEqual "Must simplify down" (successPath []) b
282+
, testCase "simp-mul-neg1" $ do
283+
let simp = Expr.simplify $ Mul (Lit Expr.maxLit) (Var "x")
284+
assertEqual "mul by -1 is negation" simp (Sub (Lit 0) (Var "x"))
285+
, testCase "simp-not-plus1" $ do
286+
let simp = Expr.simplify $ Add (Lit 1) (Not (Var "x"))
287+
assertEqual "~x + 1 is negation" simp (Sub (Lit 0) (Var "x"))
288+
, testCase "simp-xor-maxlit-plus1" $ do
289+
let simp = Expr.simplify $ Add (Lit 1) (Xor (Lit Expr.maxLit) (Var "x"))
290+
assertEqual "xor(maxLit, x) + 1 is negation" simp (Sub (Lit 0) (Var "x"))
282291
]
283292

284293
propSimplificationTests :: TestTree

0 commit comments

Comments
 (0)