From 91e421d961d8b5c6da70867dcf86ebd245fff4be Mon Sep 17 00:00:00 2001 From: Irmen de Jong Date: Thu, 8 Apr 2021 22:21:16 +0200 Subject: [PATCH] optimize x % p where p=power-of-2, into just x & (p-1) --- compiler/src/prog8/optimizer/ExpressionSimplifier.kt | 4 ++-- docs/source/todo.rst | 2 -- examples/test.p8 | 11 +++++++++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/compiler/src/prog8/optimizer/ExpressionSimplifier.kt b/compiler/src/prog8/optimizer/ExpressionSimplifier.kt index a13abe973..f2e16a81a 100644 --- a/compiler/src/prog8/optimizer/ExpressionSimplifier.kt +++ b/compiler/src/prog8/optimizer/ExpressionSimplifier.kt @@ -490,9 +490,9 @@ internal class ExpressionSimplifier(private val program: Program) : AstWalker() if(!idt.isKnown) throw FatalAstException("unknown dt") return NumericLiteralValue(idt.typeOrElse(DataType.STRUCT), 0, expr.position) - } else if (cv == 2.0) { + } else if (cv in powersOfTwo) { expr.operator = "&" - expr.right = NumericLiteralValue.optimalInteger(1, expr.position) + expr.right = NumericLiteralValue.optimalInteger(cv!!.toInt()-1, expr.position) return null } } diff --git a/docs/source/todo.rst b/docs/source/todo.rst index 394c43d39..93dd5395a 100644 --- a/docs/source/todo.rst +++ b/docs/source/todo.rst @@ -2,8 +2,6 @@ TODO ==== -- optimize %32 to & 31 - - optimize several inner loops in gfx2 - hoist all variable declarations up to the subroutine scope *before* even the constant folding takes place (to avoid undefined symbol errors when referring to a variable from another nested scope in the subroutine) - optimize swap of two memread values with index, using the same pointer expression/variable, like swap(@(ptr+1), @(ptr+2)) diff --git a/examples/test.p8 b/examples/test.p8 index 8f1696b4d..8354739cd 100644 --- a/examples/test.p8 +++ b/examples/test.p8 @@ -1,10 +1,17 @@ +%import textio main { sub start() { uword width + uword width2 = 12345 + ubyte ub1 + ubyte ub2 = 123 - ; TODO fix compiler crash with noopt: - uword x1 = (width-1 as uword) + 2 + ub1 = ub2 % 32 + txt.print_ub(ub1) + txt.nl() + width = width2 % 32 + txt.print_uw(width) } }