diff --git a/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt b/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt index 8430b9542..0d4799758 100644 --- a/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt +++ b/codeOptimizers/src/prog8/optimizer/ExpressionSimplifier.kt @@ -187,12 +187,37 @@ class ExpressionSimplifier(private val program: Program, } } + // X <= Y-1 ---> X= Y+1 ---> X>Y + if(leftDt in IntegerDatatypes && rightDt in IntegerDatatypes) { + val rightExpr = expr.right as? BinaryExpression + if(rightExpr!=null && rightExpr.right.constValue(program)?.number==1.0) { + if (expr.operator == "<=" && rightExpr.operator == "-") { + expr.operator = "<" + return listOf(IAstModification.ReplaceNode(rightExpr, rightExpr.left, expr)) + } else if (expr.operator == ">=" && rightExpr.operator == "+") { + expr.operator = ">" + return listOf(IAstModification.ReplaceNode(rightExpr, rightExpr.left, expr)) + } + } + } + if(leftDt!=DataType.FLOAT && expr.operator == ">=" && rightVal?.number == 1.0) { // for integers: x >= 1 --> x > 0 expr.operator = ">" return listOf(IAstModification.ReplaceNode(expr.right, NumericLiteral.optimalInteger(0, expr.right.position), expr)) } + // for signed integers: X <= -1 => X<0 , X > -1 => X>=0 + if(leftDt in SignedDatatypes && leftDt!=DataType.FLOAT && rightVal?.number==-1.0) { + if(expr.operator=="<=") { + expr.operator = "<" + return listOf(IAstModification.ReplaceNode(expr.right, NumericLiteral(rightDt, 0.0, expr.right.position), expr)) + } else if(expr.operator==">") { + expr.operator = ">=" + return listOf(IAstModification.ReplaceNode(expr.right, NumericLiteral(rightDt, 0.0, expr.right.position), expr)) + } + } + if (leftDt == DataType.UBYTE || leftDt == DataType.UWORD) { if(expr.operator == ">=" && rightVal?.number == 0.0) { // unsigned >= 0 --> true diff --git a/docs/source/todo.rst b/docs/source/todo.rst index 7e495acfa..8e0499d74 100644 --- a/docs/source/todo.rst +++ b/docs/source/todo.rst @@ -3,13 +3,6 @@ TODO For next minor release ^^^^^^^^^^^^^^^^^^^^^^ -- add optimizations for integer X <= Y-1 ---> X= Y+1 ---> X>Y -- add optimizations for integer: - X >= 1 => X > 0 (signed and unsigned) - X < 1 => X <= 0 (signed) or X==0 (unsigned) - X <= -1 => X >= 0 (signed only) - X > -1 => X >= 0 (signed only) - ...