From 14cb0c01ee22fbcd2923db0502e11b1fc51df05d Mon Sep 17 00:00:00 2001 From: Alon Zakai Date: Wed, 17 Jan 2018 21:20:53 -0800 Subject: optimize out 0-x, a zero only used to negate an int, when possible (#1365) --- src/passes/OptimizeInstructions.cpp | 38 ++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/passes/OptimizeInstructions.cpp b/src/passes/OptimizeInstructions.cpp index 06f3d5b02..efea99247 100644 --- a/src/passes/OptimizeInstructions.cpp +++ b/src/passes/OptimizeInstructions.cpp @@ -506,7 +506,43 @@ struct OptimizeInstructions : public WalkerPassop == AddInt32 || binary->op == SubInt32) { + } else if (binary->op == AddInt32) { + // try to get rid of (0 - ..), that is, a zero only used to negate an + // int. an add of a subtract can be flipped in order to remove it: + // (i32.add + // (i32.sub + // (i32.const 0) + // X + // ) + // Y + // ) + // => + // (i32.sub + // Y + // X + // ) + if (auto* sub = binary->left->dynCast()) { + if (sub->op == SubInt32) { + if (auto* subZero = sub->left->dynCast()) { + if (subZero->value.geti32() == 0) { + sub->left = binary->right; + return sub; + } + } + } + } + if (auto* sub = binary->right->dynCast()) { + if (sub->op == SubInt32) { + if (auto* subZero = sub->left->dynCast()) { + if (subZero->value.geti32() == 0) { + sub->left = binary->left; + return sub; + } + } + } + } + return optimizeAddedConstants(binary); + } else if (binary->op == SubInt32) { return optimizeAddedConstants(binary); } // a bunch of operations on a constant right side can be simplified -- cgit v1.2.3