From 5a846bdeb55d215a2d220c663878165e4b953e2d Mon Sep 17 00:00:00 2001 From: Irmen de Jong Date: Sat, 2 Jan 2021 20:33:59 +0100 Subject: [PATCH] fixed invalid integer constant expression evaluation leading to wrong results --- .../optimizer/ConstantFoldingOptimizer.kt | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/compiler/src/prog8/optimizer/ConstantFoldingOptimizer.kt b/compiler/src/prog8/optimizer/ConstantFoldingOptimizer.kt index 390e28f7a..ec25e827d 100644 --- a/compiler/src/prog8/optimizer/ConstantFoldingOptimizer.kt +++ b/compiler/src/prog8/optimizer/ConstantFoldingOptimizer.kt @@ -136,21 +136,25 @@ internal class ConstantFoldingOptimizer(private val program: Program) : AstWalke } } - val subExpr: BinaryExpression? = when { - leftconst!=null -> expr.right as? BinaryExpression - rightconst!=null -> expr.left as? BinaryExpression - else -> null - } - if(subExpr!=null) { - val subleftconst = subExpr.left.constValue(program) - val subrightconst = subExpr.right.constValue(program) - if ((subleftconst != null && subrightconst == null) || (subleftconst==null && subrightconst!=null)) { - // try reordering. - val change = groupTwoConstsTogether(expr, subExpr, + if(expr.inferType(program).istype(DataType.FLOAT)) { + val subExpr: BinaryExpression? = when { + leftconst != null -> expr.right as? BinaryExpression + rightconst != null -> expr.left as? BinaryExpression + else -> null + } + if (subExpr != null) { + val subleftconst = subExpr.left.constValue(program) + val subrightconst = subExpr.right.constValue(program) + if ((subleftconst != null && subrightconst == null) || (subleftconst == null && subrightconst != null)) { + // try reordering. + val change = groupTwoFloatConstsTogether( + expr, subExpr, leftconst != null, rightconst != null, - subleftconst != null, subrightconst != null) - if(change!=null) - modifications += change + subleftconst != null, subrightconst != null + ) + if (change != null) + modifications += change + } } } @@ -298,13 +302,15 @@ internal class ConstantFoldingOptimizer(private val program: Program) : AstWalke } } - private fun groupTwoConstsTogether(expr: BinaryExpression, - subExpr: BinaryExpression, - leftIsConst: Boolean, - rightIsConst: Boolean, - subleftIsConst: Boolean, - subrightIsConst: Boolean): IAstModification? + private fun groupTwoFloatConstsTogether(expr: BinaryExpression, + subExpr: BinaryExpression, + leftIsConst: Boolean, + rightIsConst: Boolean, + subleftIsConst: Boolean, + subrightIsConst: Boolean): IAstModification? { + // NOTE: THIS IS ONLY VALID ON FLOATING POINT CONSTANTS + // todo: this implements only a small set of possible reorderings at this time if(expr.operator==subExpr.operator) { // both operators are the same.