Skip to content

Commit

Permalink
Solve on canonical simplification side
Browse files Browse the repository at this point in the history
  • Loading branch information
MasterJH5574 committed Feb 3, 2023
1 parent f948d27 commit ce45b2a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
12 changes: 8 additions & 4 deletions src/arith/canonical_simplify.cc
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,8 @@ class SumExprNode : public CanonicalExprNode {
* \return whether the cast can be safely pushed to children
*/
bool CanPushCastToChildren(DataType dtype, Analyzer* analyzer) const {
bool is_min_value = dtype.bits() == 64 ? base == std::numeric_limits<int64_t>::lowest()
: base == -(1LL << (dtype.bits() - 1));
// cast(dtype, arg_1 + arg_2 + ... arg_n) ==
// cast(dtype, arg_1) + ... + cast(dtype, arg_n)
// iff it is an upcast (dtype.bits >= self.dtype.bits) or all of
Expand All @@ -351,7 +353,7 @@ class SumExprNode : public CanonicalExprNode {
}
}
}
if (base > 0) {
if (base > 0 || is_min_value) {
res = res + make_const(dtype, base);
if (!CastIsSafe(dtype, res, analyzer)) {
return false;
Expand All @@ -366,7 +368,7 @@ class SumExprNode : public CanonicalExprNode {
}
}
}
if (base < 0) {
if (base < 0 && !is_min_value) {
res = res - make_const(dtype, -base);
if (!CastIsSafe(dtype, res, analyzer)) {
return false;
Expand Down Expand Up @@ -497,14 +499,16 @@ class SumExprNode : public CanonicalExprNode {
return args;
}
static PrimExpr Normalize_(DataType dtype, const std::vector<SplitExpr>& args, int64_t base) {
bool is_min_value = dtype.bits() == 64 ? base == std::numeric_limits<int64_t>::lowest()
: base == -(1LL << (dtype.bits() - 1));
// Positive scales first
PrimExpr res = make_const(dtype, 0);
for (size_t i = 0; i < args.size(); ++i) {
if (args[i]->scale > 0) {
res = res + args[i]->Normalize();
}
}
if (base > 0) {
if (base > 0 || is_min_value) {
res = res + make_const(dtype, base);
}
// negative scales follows using sub.
Expand All @@ -513,7 +517,7 @@ class SumExprNode : public CanonicalExprNode {
res = res - args[i]->NormalizeWithScale(-1);
}
}
if (base < 0) {
if (base < 0 && !is_min_value) {
res = res - make_const(dtype, -base);
}
return res;
Expand Down
4 changes: 2 additions & 2 deletions tests/python/unittest/test_arith_canonical_simplify.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,9 @@ def test_simplify_cast():
def test_simplify_normalize_min_value_not_error():
ck = CanonicalChecker()
x = te.var("x", "int32")
expr = te.min_value_symmetric("int32") - x == 0
expr = te.min_value("int32") - x == 0
# The simplify should not error in this case.
ck.verify(expr, 0 - x == te.max_value("int32"))
ck.verify(expr, x == te.min_value("int32"))


if __name__ == "__main__":
Expand Down

0 comments on commit ce45b2a

Please sign in to comment.