Skip to content

Commit

Permalink
Merge pull request #618 from egraphs-good/apal-minmax2
Browse files Browse the repository at this point in the history
Rewrite if a </> b then a else b to min/max
  • Loading branch information
ajpal authored Jun 3, 2024
2 parents 9c4fdee + 46554cc commit 379c299
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 0 deletions.
28 changes: 28 additions & 0 deletions dag_in_context/src/optimizations/switch_rewrites.egg
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@
(ruleset switch_rewrite)
(ruleset always-switch-rewrite)

(rule (
(= pred (Bop (LessThan) a b))
(= if_e (If pred inputs thn els))
; a is an input to the if region
(= a (Get inputs i))
; b is an input to the if region
(= b (Get inputs j))
; if a < b then a else b
(= (Get thn k) (Get (Arg ty (InIf true pred inputs)) i))
(= (Get els k) (Get (Arg ty (InIf false pred inputs)) j))
)
((union (Get if_e k) (Bop (Smin) a b)))
:ruleset switch_rewrite)

(rule (
(= pred (Bop (LessThan) a b))
(= if_e (If pred inputs thn els))
; a is an input to the if region
(= a (Get inputs i))
; b is an input to the if region
(= b (Get inputs j))
; if a < b then b else a
(= (Get thn k) (Get (Arg ty (InIf true pred inputs)) j))
(= (Get els k) (Get (Arg ty (InIf false pred inputs)) i))
)
((union (Get if_e k) (Bop (Smax) a b)))
:ruleset switch_rewrite)

; if (a and b) X Y ~~> if a (if b X Y) Y
(rule ((= lhs (If (Bop (And) a b) ins X Y))
(HasType ins (TupleT ins_ty))
Expand Down
14 changes: 14 additions & 0 deletions tests/passing/small/max.bril
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# ARGS: 20 30
@main(x: int, y: int) {
cmp: bool = gt x y;
one: int = const 1;
br cmp .then .else;
.then:
res: int = id x;
jmp .done;
.else:
res: int = id y;
jmp .done;
.done:
print res;
}
11 changes: 11 additions & 0 deletions tests/passing/small/min.bril
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# ARGS: 20 30
@main(x: int, y: int) {
cmp: bool = lt x y;
res: int = id y;
br cmp .then .else;
.then:
res: int = id x;
.else:
.done:
print res;
}
15 changes: 15 additions & 0 deletions tests/snapshots/files__max-optimize.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
source: tests/files.rs
expression: visualization.result
---
@main(v0: int, v1: int) {
.b2_:
v3_: int = smax v1 v0;
v4_: bool = lt v1 v0;
v5_: int = id v1;
br v4_ .b6_ .b7_;
.b6_:
v5_: int = id v0;
.b7_:
print v3_;
}
15 changes: 15 additions & 0 deletions tests/snapshots/files__min-optimize.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
source: tests/files.rs
expression: visualization.result
---
@main(v0: int, v1: int) {
.b2_:
v3_: int = smin v0 v1;
v4_: bool = lt v0 v1;
v5_: int = id v1;
br v4_ .b6_ .b7_;
.b6_:
v5_: int = id v0;
.b7_:
print v3_;
}

0 comments on commit 379c299

Please sign in to comment.