Skip to content

Commit 038689a

Browse files
committed
feature: enhance assoc const folding
1 parent 1c1903f commit 038689a

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

src/api/optimize.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,8 @@ def visit_ADDRESS(self, node):
220220
yield node
221221

222222
def visit_BINARY(self, node: symbols.BINARY):
223+
node = yield self.generic_visit(node) # This might convert consts to numbers if possible
224+
223225
if self.O_LEVEL > 1 and node.operator in ("PLUS", "MUL"):
224226
if chk.is_number(node.left) and not chk.is_number(node.right):
225227
node.left, node.right = node.right, node.left
@@ -245,7 +247,30 @@ def visit_BINARY(self, node: symbols.BINARY):
245247
node.left = left
246248
node.right = right
247249

248-
node = yield self.generic_visit(node) # This might convert consts to numbers if possible
250+
if (
251+
node.left.token == node.right.token == "BINARY"
252+
and node.operator == node.left.operator == node.right.operator
253+
and chk.is_number(node.left.right, node.right.right)
254+
):
255+
left = yield symbols.BINARY.make_node(
256+
operator=node.operator,
257+
left=node.left.left,
258+
right=node.right.left,
259+
func=node.left.func,
260+
lineno=node.left.lineno,
261+
)
262+
right = yield symbols.BINARY.make_node(
263+
operator=node.operator,
264+
left=node.left.right,
265+
right=node.right.right,
266+
func=node.right.func,
267+
lineno=node.right.lineno,
268+
)
269+
270+
node = yield symbols.BINARY.make_node(
271+
operator=node.operator, left=left, right=right, func=node.func, lineno=node.lineno
272+
)
273+
249274
# Retry folding
250275
yield symbols.BINARY.make_node(node.operator, node.left, node.right, node.lineno, node.func, node.type_)
251276

tests/functional/zx48k/opt2_assoc.asm

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ _a:
4343
ld h, 6
4444
call .core.__MUL8_FAST
4545
ld (_a), a
46+
ld hl, (_a - 1)
47+
ld a, (_a)
48+
add a, h
49+
add a, 18
50+
ld (_a), a
4651
ld hl, 0
4752
ld b, h
4853
ld c, l
@@ -104,5 +109,5 @@ __MUL8B:
104109
ret ; result = HL
105110
ENDP
106111
pop namespace
107-
#line 38 "zx48k/opt2_assoc.bas"
112+
#line 43 "zx48k/opt2_assoc.bas"
108113
END

tests/functional/zx48k/opt2_assoc.bas

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,5 @@ a = 3 * (a * 2)
1212

1313
a = 2 + (1 + a)
1414
a = 3 * (2 * a)
15+
16+
a = 3 + (a + 4) + (5 + a) + 6

0 commit comments

Comments
 (0)