canonical_simplify.cc 35.9 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16 17 18 19
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

20 21 22 23
/*!
 * \file canonical_simplify.cc
 * \brief Canonical form based simplification.
 */
24
#include <tvm/arith/analyzer.h>
25
#include <tvm/tir/op.h>
26 27
#include <tvm/tir/analysis.h>

28 29 30 31 32 33 34
#include "const_fold.h"
#include "pattern_match.h"
#include "rewrite_simplify.h"

namespace tvm {
namespace arith {

35
using namespace tir;
36 37 38 39

class SumExpr;
class SplitExpr;

40

41 42 43 44
/*!
 * \brief Base class of all temporary expression introduced
 *        for canonicalization.
 */
45
class CanonicalExprNode : public PrimExprNode {
46
 public:
47
  virtual ~CanonicalExprNode() {}
48 49 50 51 52
  /*!
   * \brief Return the normal Expr that is equivalent to self.
   * \note Can mutate the internal data structure.
   * \return The normal expression.
   */
53
  virtual PrimExpr Normalize() const = 0;
54 55

  // overrides
56
  void VisitAttrs(tvm::AttrVisitor* v) {
57 58 59
  }

  static constexpr const char* _type_key = "arith.CanonicalExpr";
60
  TVM_DECLARE_BASE_OBJECT_INFO(CanonicalExprNode, PrimExprNode);
61 62
};

63 64 65 66 67 68 69
enum DivMode {
  /*! \brief Truncated division. */
  kTruncDiv,
  /*! \brief Floor division. */
  kFloorDiv
};

70
inline PrimExpr ModImpl(PrimExpr a, PrimExpr b, DivMode mode) {
71
  if (mode == kTruncDiv) {
72
    return truncmod(a, b);
73 74 75 76 77 78
  } else {
    CHECK_EQ(mode, kFloorDiv);
    return floormod(a, b);
  }
}

79
inline PrimExpr DivImpl(PrimExpr a, PrimExpr b, DivMode mode) {
80
  if (mode == kTruncDiv) {
81
    return truncdiv(a, b);
82 83 84 85 86 87
  } else {
    CHECK_EQ(mode, kFloorDiv);
    return floordiv(a, b);
  }
}

88 89 90 91 92 93 94 95 96 97 98
/*!
 * \brief Internal "Split normal form" of expression.
 *
 * This is a special expression that represents
 * a scaled value derived from a split of an index.
 *
 * result = ((index % upper_factor) / lower_factor) * scale
 */
class SplitExprNode : public CanonicalExprNode {
 public:
  /*! \brief The base index expression. */
99
  PrimExpr index;
100 101 102 103 104 105 106 107 108
  /*! \brief The division factor ratio. */
  int64_t lower_factor{1};
  /*!
   * \brief The upper factor.
   * invariance: (upper_factor == kPosInf || upper_factor % lower_factor == 0)
   */
  int64_t upper_factor{kPosInf};
  /*! \brief scale to the expression. */
  int64_t scale{1};
109 110
  /*! \brief Division mode. */
  DivMode div_mode{kTruncDiv};
111 112 113 114 115 116

  /*! \brief verify that this is a valid entry. */
  void Verify() const {
    CHECK(upper_factor == kPosInf || upper_factor % lower_factor == 0);
  }

117 118
  PrimExpr NormalizeWithScale(int64_t sscale) const {
    PrimExpr res = this->index;
119
    DataType dtype = this->dtype;
120 121 122 123
    if (this->scale == 0) {
      return make_const(dtype, 0);
    }
    if (this->upper_factor != SplitExprNode::kPosInf) {
124
      res = ModImpl(res, make_const(dtype, this->upper_factor), div_mode);
125 126
    }
    if (this->lower_factor != 1) {
127
      res = DivImpl(res, make_const(dtype, this->lower_factor), div_mode);
128 129 130 131 132 133 134 135 136
    }
    sscale *= this->scale;
    if (sscale != 1) {
      CHECK(!dtype.is_uint() || sscale > 0);
      res = res * make_const(dtype, sscale);
    }
    return res;
  }

137
  PrimExpr Normalize() const final {
138 139 140 141 142 143 144 145
    return NormalizeWithScale(1);
  }

  void MulToSelf(int64_t scale) {
    this->scale *= scale;
  }

  inline bool IndexEqual(const SplitExpr& other) const;
146
  inline bool DivModeCompatibleTo(DivMode mode) const;
147 148 149 150

  /*! \brief positive infty */
  static const constexpr int64_t kPosInf = ConstIntBoundNode::kPosInf;
  static constexpr const char* _type_key = "arith.SplitExpr";
151
  TVM_DECLARE_FINAL_OBJECT_INFO(SplitExprNode, CanonicalExprNode);
152 153
};

154
class SplitExpr : public PrimExpr {
155
 public:
156
  TVM_DEFINE_OBJECT_REF_METHODS(SplitExpr, PrimExpr, SplitExprNode);
157 158
  TVM_DEFINE_OBJECT_REF_COW_METHOD(SplitExprNode);
};
159 160 161

inline bool SplitExprNode::IndexEqual(const SplitExpr& other) const {
  if (index.same_as(other->index)) return true;
162
  return tir::ExprDeepEqual()(index, other->index);
163 164
}

165 166 167 168 169 170
inline bool SplitExprNode::DivModeCompatibleTo(DivMode mode) const {
  if (this->div_mode == mode) return true;
  if (lower_factor == 1 && upper_factor == kPosInf) return true;
  return false;
}

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
/*!
 * \brief Normal form that represents sum of expressions.
 *
 *  result = sum(args) + base.
 */
class SumExprNode : public CanonicalExprNode {
 public:
  /*!
   * \brief arguments to be summed up.
   *
   * args are divided into segments with the same index.
   * within each segment, the SplitExpr is ordered in descending order of lower_factor.
   */
  std::vector<SplitExpr> args;
  /*! \brief Base value in the summation. */
  int64_t base{0};
187 188 189 190
  /*! \brief The expression equals zero. */
  bool IsZero() const {
    return base == 0 && args.size() == 0;
  }
191 192 193 194
  /*!
   * \brief Return the normal Expr that is equivalent to self.
   * \return The normal expression.
   */
195
  PrimExpr Normalize() const final {
196 197
    // quick path 1.
    if (this->args.size() == 0) {
198
      return make_const(this->dtype, this->base);
199
    }
200
    return Normalize_(this->dtype,
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
                      SimplifySplitExprs(args),
                      base);
  }
  /*!
   * \brief Whether self is divisible by scale.
   * \param scale The scale to be applied.
   */
  bool DivisibleBy(int64_t scale) {
    if (base % scale != 0) return false;
    for (size_t i = 0; i < this->args.size(); ++i) {
      if (args[i]->scale % scale != 0) return false;
    }
    return true;
  }
  /*!
   * \brief mul scale to self.
   * \param scale The scale to be applied.
   */
  void MulToSelf(int64_t scale) {
    this->base *= scale;
    for (size_t i = 0; i < this->args.size(); ++i) {
      args[i].CopyOnWrite()->scale *= scale;
    }
  }
  /*!
   * \brief divide by scale.
   * \param scale The scale to be applied.
   */
  void DivideBy(int64_t scale) {
    CHECK_EQ(this->base % scale, 0);
    this->base /= scale;
    for (size_t i = 0; i < this->args.size(); ++i) {
      CHECK_EQ(args[i]->scale % scale, 0);
      args[i].CopyOnWrite()->scale /= scale;
    }
  }
  /*!
   * \brief add constant value to self.
   * \param value to be added.
   */
  void AddToSelf(int64_t value) {
    this->base += value;
  }
  /*!
   * \brief self += other * scale;
   * \param other The expression to be added.
   * \param scale The additional scale on value.
   */
  void AddToSelf(SplitExpr other, int64_t scale) {
    if (other->scale == 0) return;
    // We need to maintain the segment invariance:
    // Same index are stored close to each other.
    // sorted from big lower_factor to small one.
    size_t start = 0;
    for (; start < args.size(); ++start) {
      if (args[start]->IndexEqual(other)) break;
    }
    for (size_t j = start; j < args.size(); ++j) {
      if (!args[j]->IndexEqual(other) ||
          other->lower_factor > args[j]->lower_factor) {
        other.CopyOnWrite()->scale *= scale;
        this->args.insert(this->args.begin() + j, other);
        return;
      }
      if (other->lower_factor == args[j]->lower_factor &&
266 267
          other->upper_factor == args[j]->upper_factor &&
          other->DivModeCompatibleTo(args[j]->div_mode)) {
268 269 270 271 272 273 274 275 276 277 278 279
        args[j].CopyOnWrite()->scale += other->scale * scale;
        return;
      }
    }
    // Insert other in the end.
    other.CopyOnWrite()->scale *= scale;
    this->args.emplace_back(std::move(other));
  }

  void AddToSelf(const SumExpr& other, int64_t scale);

  static constexpr const char* _type_key = "arith.SumExpr";
280
  TVM_DECLARE_FINAL_OBJECT_INFO(SumExprNode, CanonicalExprNode);
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298

 private:
  /*!
   * \brief Simplify the args by merging SplitExprs
   * \param args The original list of arguments.
   * \return simplified version.
   */
  static std::vector<SplitExpr>
  SimplifySplitExprs(std::vector<SplitExpr> args) {
    // NOTE: This algorithm relies on the factor that args are divided into segments
    // and each segment is sorted in descending order of lower_factor.
    for (size_t i = 0; i < args.size(); ++i) {
      if (args[i]->scale == 0) continue;
      for (size_t j = i + 1; j < args.size(); ++j) {
        SplitExpr& lhs = args[i];
        SplitExpr& rhs = args[j];
        if (!lhs->IndexEqual(rhs)) break;
        if (lhs->upper_factor < rhs->lower_factor) break;
299
        if (lhs->upper_factor == rhs->upper_factor &&
300 301
            lhs->lower_factor == rhs->lower_factor &&
            lhs->DivModeCompatibleTo(rhs->div_mode)) {
302 303 304 305
          // folding same co-efficient.
          rhs.CopyOnWrite()->scale += lhs->scale;
          lhs.CopyOnWrite()->scale = 0;
        } else if (lhs->lower_factor == rhs->upper_factor &&
306
                   rhs->scale != 0 &&
307
                   lhs->scale % rhs->scale == 0 &&
308 309
                   lhs->lower_factor == (lhs->scale / rhs->scale) * rhs->lower_factor &&
                   lhs->DivModeCompatibleTo(rhs->div_mode)) {
310 311 312 313 314 315 316 317 318 319 320
          // Rules used in the proof:
          //
          // Rule 1:  (x % (c * s)) / c  =  (x / c) % s
          // Proof:
          //  x can always be decomposed into p * c * s + q * c + r
          //  where  0 <= q * c + r < c * s  and  0 <= r  <  c.
          //  Then, lhs = ((p * c * s + q * c + r) % (c * s)) / c = (q * c + r) / c = q
          //  rhs = ((p * c * s + q * c + r) / c) % s = (p * s + q) % s = q
          //  Thus, lhs = rhs
          //
          // The above proof is for the floordiv.
321
          // The same rule also holds for truncdiv(division rule in C).
322 323 324 325
          // Because both sides only involve mul, div and mod,
          // we can take abs of x, c and s, apply the floordiv proof,
          // and finally add the sign back.
          //
326
          // Rule 2:  (x / s) * s + x % s = x  (true for both trunc and floor div)
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
          //
          // General merge condition and proof:
          // - x = lhs->index % lhs->upper_factor
          // - s = lhs->scale / rhs->scale
          // - c = rhs->lower_factor
          //
          //    (x / (c * s)) * s + (x % (c * s)) / c
          // => ((x / c) / s) * s + ((x / c) % s)
          // => (x / c)
          //
          // Examples:
          //
          //    (z / 6) * 6 + ((z % 6) / 3) * 3
          // => ((z / 6) * 2 + (z % 6) / 3) * 3
          // => (z / 3) * 3
          // note: x = z, c = 3, s = 2
          //
          //    ((z % 12) / 6) * 6 + ((z % 6) / 3) * 3
          // => (((z % 12) / 6) * 2 + ((z % 12) % 6) / 3) * 3
          // => ((z % 12) / 3) * 3
          // note: x = z % 12, c = 3, s = 2
          // note also the invariance lhs->upper_factor % lhs->lower_factor == 0
          //
          SplitExprNode* merged = rhs.CopyOnWrite();
          merged->upper_factor = lhs->upper_factor;
          // reset args[i] to be zero.
          lhs.CopyOnWrite()->scale = 0;
          break;
        }
      }
    }
    // sort by the entry
    // Here we simply sort by descending order of scales.
    // For now, we do not compare by index because that comparison
    // can be runtime dependent and create inderminism.
    // we do not sort by index for now because it can be costly
    // to deep compare Exprs, and address of Vars can be runtime dependent.
    //
    auto fcompare = [](const SplitExpr& lhs, const SplitExpr& rhs) {
      // order by scale first
      if (lhs->scale > rhs->scale) return true;
      if (lhs->scale < rhs->scale) return false;
      // then order by factor
      if (lhs->lower_factor > rhs->lower_factor) return true;
      if (lhs->lower_factor < rhs->lower_factor) return false;
      // then order by upper factor
      if (lhs->upper_factor > rhs->upper_factor) return true;
      if (lhs->upper_factor < rhs->upper_factor) return false;
375 376 377
      // then order by div mode
      if (lhs->div_mode > rhs->div_mode) return true;
      if (lhs->div_mode < rhs->div_mode) return false;
378 379 380 381 382 383 384 385 386
      // tie.
      // TODO(tvm-team) We might consider index as the last comparison point,
      // after we make deep comparator more derministic.
      // Specifically, we can consider comparing names of vars and break ties with address.
      return false;
    };
    std::stable_sort(args.begin(), args.end(), fcompare);
    return args;
  }
387
  static PrimExpr Normalize_(DataType dtype,
388 389 390
                         const std::vector<SplitExpr>& args,
                         int64_t base) {
    // Positive scales first
391
    PrimExpr res = make_const(dtype, 0);
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    for (size_t i = 0; i < args.size(); ++i) {
      if (args[i]->scale > 0) {
        res = res + args[i]->Normalize();
      }
    }
    if (base > 0) {
      res = res + make_const(dtype, base);
    }
    // negative scales follows using sub.
    for (size_t i = 0; i < args.size(); ++i) {
      if (args[i]->scale < 0) {
        res = res - args[i]->NormalizeWithScale(-1);
      }
    }
    if (base < 0) {
      res = res - make_const(dtype, -base);
    }
    return res;
  }
};

413
class SumExpr : public PrimExpr {
414
 public:
415
  TVM_DEFINE_OBJECT_REF_METHODS(SumExpr, PrimExpr, SumExprNode);
416 417
  TVM_DEFINE_OBJECT_REF_COW_METHOD(SumExprNode);
};
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437

void SumExprNode::AddToSelf(const SumExpr& other, int64_t scale) {
  // NOTE: it is rare to have a balanced long expression,
  // linear scan is fine for our case.
  for (size_t i = 0; i < other->args.size(); ++i) {
    this->AddToSelf(other->args[i], scale);
  }
  this->AddToSelf(other->base * scale);
}

// Sub-class RewriteSimplifier::Impl to take benefit of
// rewriter for condition simplification etc.
class CanonicalSimplifier::Impl : public RewriteSimplifier::Impl {
 public:
  using Rewriter = RewriteSimplifier::Impl;

  explicit Impl(Analyzer* parent)
      : Rewriter(parent) {}


438
  PrimExpr CanonicalSimplify(PrimExpr expr) {
439
    expr = operator()(expr);
440 441 442 443
    return expr;
  }

  // override the original mutate function.
444
  PrimExpr VisitExpr(const PrimExpr& input_expr) final {
445
    auto expr = Rewriter::VisitExpr(input_expr);
446 447 448 449
    return Normalize(expr);
  }

  // Normal mutation without normalization.
450
  PrimExpr CanonicalMutate(PrimExpr expr) {
451
    return Rewriter::VisitExpr(expr);
452 453
  }

454
  using Rewriter::VisitExpr_;
455 456 457 458 459 460 461 462
  PrimExpr VisitExpr_(const AddNode* op) final;
  PrimExpr VisitExpr_(const SubNode* op) final;
  PrimExpr VisitExpr_(const MulNode* op) final;
  PrimExpr VisitExpr_(const DivNode* op) final;
  PrimExpr VisitExpr_(const ModNode* op) final;
  PrimExpr VisitExpr_(const FloorDivNode* op) final;
  PrimExpr VisitExpr_(const FloorModNode* op) final;
  PrimExpr VisitExpr_(const ReduceNode* op) final;
463 464 465 466 467 468

 private:
  /*!
   * \brief compute lhs / cval
   * \param lhs The left operand.
   * \param cval The constant value.
469
   * \param div_mode The division mode.
470 471
   * \return The result expression;
   */
472
  SplitExpr SplitDivConst(SplitExpr lhs, int64_t cval, DivMode div_mode);
473 474 475 476
  /*!
   * \brief compute lhs % cval
   * \param lhs The left operand.
   * \param cval The constant value.
477
   * \param div_mode The division mode.
478 479
   * \return The result expression;
   */
480
  SplitExpr SplitModConst(SplitExpr lhs, int64_t cval, DivMode div_mode);
481
  /*!
482
   * \brief Separate psum into divisible and non-divisible parts.
483 484 485 486 487
   * \param psum The sum expression.
   * \param coeff The co-efficient.
   * \param out_divisible The result divisible component.
   * \param out_non_divisible The non-divisible component.
   */
488 489 490 491
  void SeparateDivisibleParts(const SumExprNode* psum,
                              int64_t coeff,
                              SumExpr* out_divisible,
                              SumExpr* out_non_divisible);
492 493 494 495 496
  /*!
   * \brief Normalize expr to normal expr.
   * \param expr The input expression.
   * \return Normalized expr.
   */
497
  PrimExpr Normalize(PrimExpr expr) {
498
    if (const auto* op = expr.as<CanonicalExprNode>()) {
499 500 501 502 503 504 505 506 507 508
      return op->Normalize();
    } else {
      return expr;
    }
  }
  /*!
   * \brief Create a SplitExpr from expr.
   * \param expr The input expr.
   * \return The transformed SplitExpr.
   */
509
  SplitExpr ToSplitExpr(PrimExpr expr) {
510 511 512
    if (const auto* op = expr.as<SplitExprNode>()) {
      return GetRef<SplitExpr>(op);
    }
513 514 515
    if (const auto* op = expr.as<SumExprNode>()) {
      if (op->base == 0 && op->args.size() == 1) return op->args[0];
    }
516
    if (const auto* op = expr.as<CanonicalExprNode>()) {
517 518
      expr = op->Normalize();
    }
519
    ObjectPtr<SplitExprNode> n = make_object<SplitExprNode>();
520
    n->dtype = expr.dtype();
521
    n->index = std::move(expr);
522
    n->div_mode = kTruncDiv;
523 524 525
    return SplitExpr(n);
  }
  /*!
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
   * \brief Convert expr to an equivalent SplitExpr
   *        that has the specified div_mode.
   *
   * This function will return the same expr if its
   * div_mode already satisfies the need.
   *
   * \param expr The input expr.
   * \param div_mode The new div_mode.
   * \return The transformed SplitExpr.
   */
  SplitExpr ConvertDivMode(SplitExpr expr, DivMode div_mode) {
    if (expr->div_mode == div_mode) return expr;
    if (expr->DivModeCompatibleTo(div_mode)) {
      expr.CopyOnWrite()->div_mode = div_mode;
      return expr;
    }
    expr = ToSplitExpr(Normalize(expr));
    CHECK(expr->DivModeCompatibleTo(div_mode));
    expr.CopyOnWrite()->div_mode = div_mode;
    return expr;
  }
  /*!
548 549 550 551
   * \brief Create a SumExpr from expr.
   * \param expr The input expr.
   * \return The transformed SumExpr.
   */
552
  SumExpr ToSumExpr(PrimExpr expr) {
553 554 555
    if (const auto* op = expr.as<SumExprNode>()) {
      return GetRef<SumExpr>(op);
    }
556
    ObjectPtr<SumExprNode> n = make_object<SumExprNode>();
557
    n->dtype = expr.dtype();
558
    if (const auto* op = expr.as<IntImmNode>()) {
559 560 561 562 563 564 565 566
      n->base = op->value;
      return SumExpr(n);
    } else {
      n->args.emplace_back(ToSplitExpr(expr));
      return SumExpr(n);
    }
  }
  // Simplify the combiner used in reduce.
567
  PrimExpr SimplifyReduceCombiner(const ReduceNode* op);
568 569
};

570
PrimExpr CanonicalSimplifier::Impl::
571
VisitExpr_(const AddNode* op) {
572
  if (!IsIndexType(op->dtype)) {
573
    return Rewriter::VisitExpr_(op);
574 575
  }
  // normalize
576 577
  PrimExpr a = this->CanonicalMutate(op->a);
  PrimExpr b = this->CanonicalMutate(op->b);
578 579

  // const folding
580
  PrimExpr const_res = TryConstFold<AddNode>(a, b);
581 582 583 584 585
  if (const_res.defined()) return const_res;

  // canonical form simplification.
  SumExpr ret = ToSumExpr(std::move(a));

586
  if (const auto* op = b.as<IntImmNode>()) {
587 588 589 590 591 592
    ret.CopyOnWrite()->AddToSelf(op->value);
  } else if (const auto* op = b.as<SumExprNode>()) {
    ret.CopyOnWrite()->AddToSelf(GetRef<SumExpr>(op), 1);
  } else {
    ret.CopyOnWrite()->AddToSelf(ToSplitExpr(b), 1);
  }
593
  return std::move(ret);
594 595
}

596
PrimExpr CanonicalSimplifier::Impl::
597
VisitExpr_(const SubNode* op) {
598
  if (!IsIndexType(op->dtype)) {
599
    return Rewriter::VisitExpr_(op);
600 601
  }
  // normalize
602 603
  PrimExpr a = this->CanonicalMutate(op->a);
  PrimExpr b = this->CanonicalMutate(op->b);
604 605

  // const folding
606
  PrimExpr const_res = TryConstFold<SubNode>(a, b);
607 608 609 610 611
  if (const_res.defined()) return const_res;

  // canonical form simplification.
  SumExpr ret = ToSumExpr(std::move(a));

612
  if (const auto* op = b.as<IntImmNode>()) {
613 614 615 616 617 618
    ret.CopyOnWrite()->AddToSelf(-op->value);
  } else if (const auto* op = b.as<SumExprNode>()) {
    ret.CopyOnWrite()->AddToSelf(GetRef<SumExpr>(op), -1);
  } else {
    ret.CopyOnWrite()->AddToSelf(ToSplitExpr(b), -1);
  }
619
  return std::move(ret);
620 621 622
}


623
PrimExpr CanonicalSimplifier::Impl::
624
VisitExpr_(const MulNode* op) {
625
  if (!IsIndexType(op->dtype)) {
626
    return Rewriter::VisitExpr_(op);
627 628
  }
  // normalize
629 630
  PrimExpr a = this->CanonicalMutate(op->a);
  PrimExpr b = this->CanonicalMutate(op->b);
631 632

  // const folding
633
  PrimExpr const_res = TryConstFold<MulNode>(a, b);
634 635 636
  if (const_res.defined()) return const_res;

  // x * c
637
  if (a.as<IntImmNode>()) {
638 639
    std::swap(a, b);
  }
640
  if (const auto* bconst = b.as<IntImmNode>()) {
641
    if (a.as<SumExprNode>()) {
642
      SumExpr ret = Downcast<SumExpr>(std::move(a));
643
      ret.CopyOnWrite()->MulToSelf(bconst->value);
644
      return std::move(ret);
645 646 647
    } else {
      SplitExpr ret = ToSplitExpr(std::move(a));
      ret.CopyOnWrite()->MulToSelf(bconst->value);
648
      return std::move(ret);
649 650 651 652 653 654 655
    }
  }

  // normal path.
  a = Normalize(a);
  b = Normalize(b);
  if (op->a.same_as(a) && op->b.same_as(b)) {
656
    return GetRef<PrimExpr>(op);
657
  } else {
658
    return MulNode::make(a, b);
659 660 661
  }
}

662 663 664 665 666
void CanonicalSimplifier::Impl::
SeparateDivisibleParts(const SumExprNode* psum,
                       int64_t coeff,
                       SumExpr* out_divisible,
                       SumExpr* out_non_divisible) {
667 668
  auto divisible = make_object<SumExprNode>();
  auto non_divisible = make_object<SumExprNode>();
669 670
  divisible->dtype = psum->dtype;
  non_divisible->dtype = psum->dtype;
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

  if (psum->base % coeff == 0) {
    divisible->base = psum->base;
  } else {
    non_divisible->base = psum->base;
  }
  for (const auto& e : psum->args) {
    if (e->scale % coeff == 0) {
      divisible->args.push_back(e);
    } else {
      non_divisible->args.push_back(e);
    }
  }
  *out_divisible = SumExpr(divisible);
  *out_non_divisible = SumExpr(non_divisible);
}

SplitExpr CanonicalSimplifier::Impl::
689 690 691 692 693
SplitDivConst(SplitExpr lhs, int64_t cval, DivMode div_mode) {
  CHECK_GT(cval, 0);
  lhs = ConvertDivMode(lhs, div_mode);

  // the following rule works for both floordiv and truncdiv
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
  if (lhs->scale % cval == 0) {
    lhs.CopyOnWrite()->scale /= cval;
    return lhs;
  }

  if (cval % lhs->scale == 0) {
    int64_t scaled_cval = cval / lhs->scale;
    if (lhs->upper_factor == SplitExprNode::kPosInf ||
        lhs->upper_factor % (lhs->lower_factor * scaled_cval) == 0) {
      // directly fold division.
      lhs.CopyOnWrite()->scale = 1;
      lhs.CopyOnWrite()->lower_factor *= scaled_cval;
      lhs->Verify();
      return lhs;
    } else if (lhs->upper_factor <= (lhs->lower_factor * scaled_cval)) {
      // (x % c1) / c2  => 0 when c2 >= c1
710
      return ToSplitExpr(make_zero(lhs.dtype()));
711 712 713
    } else {
      // move the upper_factor modular into index.
      lhs.CopyOnWrite()->index =
714
          ModImpl(lhs->index, make_const(lhs.dtype(), lhs->upper_factor), div_mode);
715 716 717 718 719 720 721 722 723
      lhs.CopyOnWrite()->upper_factor = SplitExprNode::kPosInf;
      lhs.CopyOnWrite()->scale = 1;
      lhs.CopyOnWrite()->lower_factor *= scaled_cval;
      lhs->Verify();
      return lhs;
    }
  }
  // directly return the split with cval == 1
  lhs = ToSplitExpr(Normalize(lhs));
724
  CHECK(lhs->DivModeCompatibleTo(div_mode));
725 726 727 728 729
  CHECK_EQ(lhs->scale, 1);
  lhs.CopyOnWrite()->lower_factor *= cval;
  return lhs;
}

730
PrimExpr CanonicalSimplifier::Impl::
731
VisitExpr_(const DivNode* op) {
732
  if (!IsIndexType(op->dtype)) {
733
    return Rewriter::VisitExpr_(op);
734
  }
735

736 737
  PrimExpr a = this->CanonicalMutate(op->a);
  PrimExpr b = this->CanonicalMutate(op->b);
738 739

  // const folding
740
  PrimExpr const_res = TryConstFold<DivNode>(a, b);
741
  if (const_res.defined()) return const_res;
742
  PVar<IntImm> c1;
743 744 745 746 747 748 749
  // x / c1
  if (c1.Match(b) && c1.Eval()->value > 0) {
    int64_t cval = c1.Eval()->value;
    if (cval == 1) return a;

    if (const auto* psum = a.as<SumExprNode>()) {
      SumExpr lhs, extra;
750 751 752 753 754 755 756
      SeparateDivisibleParts(psum, cval, &lhs, &extra);
      // can be divided by cval
      if (extra->IsZero()) {
        lhs.CopyOnWrite()->DivideBy(cval);
        return std::move(lhs);
      }
      // both lhs and extra are non-negative
757 758
      if (analyzer_->CanProveGreaterEqual(lhs->Normalize(), 0) &&
          analyzer_->CanProveGreaterEqual(extra->Normalize(), 0)) {
759
        lhs.CopyOnWrite()->DivideBy(cval);
760
        PrimExpr temp = Normalize(extra);
761
        if (const auto* pconst = temp.as<IntImmNode>()) {
762 763
          lhs.CopyOnWrite()->AddToSelf(pconst->value / cval);
        } else {
764
          // if 0 <= extra < cval, it means the extra can be eliminated.
765 766
          if (TryCompare(temp, cval) != kLT) {
            lhs.CopyOnWrite()->AddToSelf(
767
                SplitDivConst(ToSplitExpr(temp), cval, kTruncDiv), 1);
768 769
          }
        }
770
        return std::move(lhs);
771 772 773
      }
    } else {
      // if a >= 0 && a < cval, then result == 0
774
      auto cbound = analyzer_->const_int_bound(Normalize(a));
775
      if (cbound->min_value >= 0 && cbound->max_value < cval) {
776
        return make_zero(a.dtype());
777 778
      }
    }
779
    return SplitDivConst(ToSplitExpr(std::move(a)), cval, kTruncDiv);
780 781 782 783 784
  }
  // normal path
  a = Normalize(a);
  b = Normalize(b);
  if (op->a.same_as(a) && op->b.same_as(b)) {
785
    return GetRef<PrimExpr>(op);
786
  } else {
787
    return DivNode::make(a, b);
788 789 790
  }
}

791
PrimExpr CanonicalSimplifier::Impl::
792
VisitExpr_(const FloorDivNode* op) {
793
  if (!IsIndexType(op->dtype)) {
794
    return Rewriter::VisitExpr_(op);
795
  }
796 797
  PrimExpr a = this->CanonicalMutate(op->a);
  PrimExpr b = this->CanonicalMutate(op->b);
798 799

  // const folding
800
  PrimExpr const_res = TryConstFold<FloorDivNode>(a, b);
801
  if (const_res.defined()) return const_res;
802
  PVar<IntImm> c1;
803 804 805 806 807 808 809 810 811 812 813 814 815 816
  // x / c1
  if (c1.Match(b) && c1.Eval()->value > 0) {
    int64_t cval = c1.Eval()->value;
    if (cval == 1) return a;

    if (const auto* psum = a.as<SumExprNode>()) {
      SumExpr lhs, extra;
      SeparateDivisibleParts(psum, cval, &lhs, &extra);
      if (extra->IsZero()) {
        lhs.CopyOnWrite()->DivideBy(cval);
        return std::move(lhs);
      }
      // continue simplification.
      lhs.CopyOnWrite()->DivideBy(cval);
817
      PrimExpr temp = Normalize(extra);
818
      if (const auto* pconst = temp.as<IntImmNode>()) {
819 820 821
        lhs.CopyOnWrite()->AddToSelf(floordiv(pconst->value, cval));
      } else {
        // if 0 <= extra < cval, it means the extra can be eliminated.
822
        if (!(TryCompare(temp, cval) == kLT && analyzer_->CanProveGreaterEqual(temp, 0))) {
823 824 825 826 827 828 829
          lhs.CopyOnWrite()->AddToSelf(
              SplitDivConst(ToSplitExpr(temp), cval, kFloorDiv), 1);
        }
      }
      return std::move(lhs);
    } else {
      // if a >= 0 && a < cval, then result == 0
830
      auto cbound = analyzer_->const_int_bound(Normalize(a));
831
      if (cbound->min_value >= 0 && cbound->max_value < cval) {
832
        return make_zero(a.dtype());
833 834 835 836 837 838 839 840
      }
    }
    return SplitDivConst(ToSplitExpr(std::move(a)), cval, kFloorDiv);
  }
  // normal path
  a = Normalize(a);
  b = Normalize(b);
  if (op->a.same_as(a) && op->b.same_as(b)) {
841
    return GetRef<PrimExpr>(op);
842
  } else {
843
    return FloorDivNode::make(a, b);
844 845 846
  }
}

847
SplitExpr CanonicalSimplifier::Impl::
848 849 850 851
SplitModConst(SplitExpr lhs, int64_t cval, DivMode div_mode) {
  CHECK_GT(cval, 0);
  lhs = ConvertDivMode(lhs, div_mode);

852 853 854 855 856 857 858 859 860 861 862 863
  if (lhs->scale % cval == 0) {
    lhs.CopyOnWrite()->scale = 0;
    return lhs;
  }
  if (cval % lhs->scale == 0) {
    // (x * c1) % (c2 * c1) => (x % c2) * c1
    int64_t scaled_cval = cval / lhs->scale;
    //  (x / c1) % c2  =>  (x % (c1 * c2)) / c2
    int64_t new_upper_factor = lhs->lower_factor * scaled_cval;
    // try to see if we can reduce the existing upper modular.
    if (lhs->upper_factor == SplitExprNode::kPosInf ||
        lhs->upper_factor % new_upper_factor == 0) {
864 865 866 867 868 869
      // we gained a new upper factor that is smaller
      // than the original one
      // Perhaps there are more chances in simplifying the index
      // Do a recursive call to simplify the mod with the new factor.
      if (new_upper_factor < lhs->upper_factor &&
          lhs->upper_factor != SplitExprNode::kPosInf) {
870
        auto updated = ToSplitExpr(this->VisitExpr(ModImpl(
871
            lhs->index, make_const(lhs.dtype(), new_upper_factor), div_mode)));
872 873 874 875 876 877 878 879 880 881
        // re-apply the lower_factor
        if (lhs->lower_factor != 1) {
          return SplitDivConst(updated, lhs->lower_factor, div_mode);
        } else {
          return updated;
        }
      } else {
        lhs.CopyOnWrite()->upper_factor = new_upper_factor;
        return lhs;
      }
882 883 884 885 886 887 888
    } else if (new_upper_factor % lhs->upper_factor == 0) {
      // (x % 2) % 4 => x % 2
      return lhs;
    }
  }
  // Normalize the value.
  lhs = ToSplitExpr(Normalize(lhs));
889
  CHECK(lhs->DivModeCompatibleTo(div_mode));
890 891
  CHECK_EQ(lhs->scale, 1);
  CHECK_EQ(lhs->lower_factor, 1);
892
  lhs.CopyOnWrite()->div_mode = div_mode;
893 894 895 896
  lhs.CopyOnWrite()->upper_factor = cval;
  return lhs;
}

897
PrimExpr CanonicalSimplifier::Impl::
898
VisitExpr_(const ModNode* op) {
899
  if (!IsIndexType(op->dtype)) {
900
    return Rewriter::VisitExpr_(op);
901 902
  }
  // normalize
903 904
  PrimExpr a = this->CanonicalMutate(op->a);
  PrimExpr b = this->CanonicalMutate(op->b);
905 906

  // const folding
907
  PrimExpr const_res = TryConstFold<ModNode>(a, b);
908 909
  if (const_res.defined()) return const_res;

910
  PVar<IntImm> c1;
911 912 913 914 915
  // x % c1
  if (c1.Match(b) && c1.Eval()->value > 0) {
    int64_t cval = c1.Eval()->value;
    if (const auto* psum = a.as<SumExprNode>()) {
      SumExpr lhs, extra;
916 917
      SeparateDivisibleParts(psum, cval, &lhs, &extra);
      if (extra->IsZero()) {
918
        return make_zero(a.dtype());
919 920
      }
      // both lhs and extra are non-negative
921 922
      if (analyzer_->CanProveGreaterEqual(lhs->Normalize(), 0) &&
          analyzer_->CanProveGreaterEqual(extra->Normalize(), 0)) {
923
        PrimExpr temp = Normalize(extra);
924
        if (temp.as<IntImmNode>()) {
925
          return truncmod(temp, c1.Eval());
926 927 928 929 930
        } else {
          // If temp < cval && temp >=0 then can remove the mod.
          if (TryCompare(temp, cval) == kLT) {
            return temp;
          } else {
931 932 933 934
            // contonue to use logic below.
            a = extra;
            psum = a.as<SumExprNode>();
            CHECK(psum != nullptr);
935 936 937
          }
        }
      }
938 939
      // Simplify the offset constant if necessary.
      // (x - 5) % 3 => (x - 2) % 3 if x - 5 >= 0
940
      auto cbound = analyzer_->const_int_bound(Normalize(a));
941 942 943
      int64_t new_base = psum->base % cval;
      if (cbound->min_value >= 0 &&
          cbound->min_value - psum->base + new_base >= 0) {
944
        SumExpr sum_expr = Downcast<SumExpr>(a);
945
        sum_expr.CopyOnWrite()->base = new_base;
946
        return SplitModConst(ToSplitExpr(std::move(sum_expr)), cval, kTruncDiv);
947
      }
948 949
    } else {
      // if a >= 0 && a < cval, then result == 0
950
      auto cbound = analyzer_->const_int_bound(Normalize(a));
951 952 953 954
      if (cbound->min_value >= 0 && cbound->max_value < cval) {
        return a;
      }
    }
955
    return SplitModConst(ToSplitExpr(std::move(a)), cval, kTruncDiv);
956 957 958 959 960
  }
  // normal path
  a = Normalize(a);
  b = Normalize(b);
  if (op->a.same_as(a) && op->b.same_as(b)) {
961
    return GetRef<PrimExpr>(op);
962
  } else {
963
    return ModNode::make(a, b);
964 965 966
  }
}

967
PrimExpr CanonicalSimplifier::Impl::
968
VisitExpr_(const FloorModNode* op) {
969
  if (!IsIndexType(op->dtype)) {
970
    return Rewriter::VisitExpr_(op);
971 972
  }
  // normalize
973 974
  PrimExpr a = this->CanonicalMutate(op->a);
  PrimExpr b = this->CanonicalMutate(op->b);
975 976

  // const folding
977
  PrimExpr const_res = TryConstFold<FloorModNode>(a, b);
978 979
  if (const_res.defined()) return const_res;

980
  PVar<IntImm> c1;
981 982 983 984 985 986
  // x % c1
  if (c1.Match(b) && c1.Eval()->value > 0) {
    int64_t cval = c1.Eval()->value;
    if (const auto* psum = a.as<SumExprNode>()) {
      SumExpr lhs, extra;
      SeparateDivisibleParts(psum, cval, &lhs, &extra);
987
      PrimExpr temp = Normalize(extra);
988
      if (temp.as<IntImmNode>()) {
989 990 991 992
        return floormod(temp, c1.Eval());
      } else {
        // If temp < cval && temp >=0 then can remove the mod.
        if (TryCompare(temp, cval) == kLT &&
993
            analyzer_->CanProveGreaterEqual(temp, 0)) {
994 995 996 997 998 999 1000 1001 1002 1003 1004
          return temp;
        } else {
          // contonue to use logic below.
          a = extra;
          psum = a.as<SumExprNode>();
          CHECK(psum != nullptr);
        }
      }
      // Simplify the offset constant if necessary.
      // floormod(x - 5, 3) => floormod(x + 1, 3)
      int64_t new_base = floormod(psum->base, cval);
1005
      SumExpr sum_expr = Downcast<SumExpr>(std::move(a));
1006 1007 1008 1009
      sum_expr.CopyOnWrite()->base = new_base;
      return SplitModConst(ToSplitExpr(std::move(sum_expr)), cval, kFloorDiv);
    } else {
      // if a >= 0 && a < cval, then result == a
1010
      auto cbound = analyzer_->const_int_bound(Normalize(a));
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
      if (cbound->min_value >= 0 && cbound->max_value < cval) {
        return a;
      }
    }
    return SplitModConst(ToSplitExpr(std::move(a)), cval, kFloorDiv);
  }
  // normal path
  a = Normalize(a);
  b = Normalize(b);
  if (op->a.same_as(a) && op->b.same_as(b)) {
1021
    return GetRef<PrimExpr>(op);
1022
  } else {
1023
    return FloorModNode::make(a, b);
1024 1025 1026
  }
}

1027
// Simplify reduce expression.
1028
PrimExpr CanonicalSimplifier::Impl::
1029
SimplifyReduceCombiner(const ReduceNode* op) {
1030
  // First simplify the results
1031
  Array<PrimExpr> simplified_result;
1032
  for (const auto& res : op->combiner->result) {
1033
    PrimExpr new_res = this->VisitExpr(res);
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    simplified_result.push_back(new_res);
  }

  // Which components to keep
  std::vector<int> used(op->combiner->result.size(), false);

  // This function recursively marks the used components starting from
  // the index idx
  std::function<void(int)> mark_used;
  mark_used = [&used, &simplified_result, op, &mark_used](size_t idx) {
    // if the idx-th component was marked as used before, do nothing
    if (used[idx]) return;
    used[idx] = true;

    // check if the idx-th result expr uses some lhs or rhs variables
    // and recursively mark the corresponding components
    for (size_t i = 0; i < simplified_result.size(); ++i)
      if (!used[i]) {
        if (ExprUseVar(simplified_result[idx], op->combiner->lhs[i]) ||
            ExprUseVar(simplified_result[idx], op->combiner->rhs[i]))
          mark_used(i);
      }
  };

  // mark all used components starting from the value_index
  mark_used(op->value_index);

  // components which have side effects should also be preserved
  for (size_t i = 0; i < used.size(); ++i) {
    if (HasSideEffect(op->source[i]) ||
        HasSideEffect(op->combiner->identity_element[i]) ||
        HasSideEffect(op->combiner->result[i])) {
      mark_used(i);
    }
  }

  int new_value_index = op->value_index;
1071 1072
  Array<PrimExpr> new_result;
  Array<PrimExpr> new_identity;
1073 1074
  Array<Var> new_lhs;
  Array<Var> new_rhs;
1075
  Array<PrimExpr> new_source;
1076 1077 1078 1079 1080 1081

  // new stuff is old stuff which is used
  for (size_t i = 0; i < used.size(); ++i) {
    if (used[i]) {
      // We simplify the result and identity, but not the source
      new_result.push_back(simplified_result[i]);
1082
      new_identity.push_back(this->VisitExpr(op->combiner->identity_element[i]));
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
      new_lhs.push_back(op->combiner->lhs[i]);
      new_rhs.push_back(op->combiner->rhs[i]);
      new_source.push_back(op->source[i]);
    } else if (static_cast<int>(i) < op->value_index) {
      // value_index should also be adjusted
      new_value_index--;
    }
  }

  CommReducer new_combiner =
      CommReducerNode::make(new_lhs, new_rhs, new_result, new_identity);
1094
  return ReduceNode::make(
1095 1096 1097
      new_combiner, new_source, op->axis, op->condition, new_value_index);
}

1098
PrimExpr CanonicalSimplifier::Impl::
1099
VisitExpr_(const ReduceNode* op) {
1100
  // Recursively call simplification when necessary.
1101
  PrimExpr ret = RewriteSimplifier::Impl::VisitExpr_(op);
1102
  op = ret.as<ReduceNode>();
1103 1104 1105 1106 1107 1108 1109
  // already been simplified by const reduction axis removal
  if (op == nullptr) return ret;
  if (op->axis.empty()) {
    // Note that here we assume that the identity element is indeed identity. Without this
    // assumption we would have to perform a single iteration of the loop, i.e. use
    // `(*op->combiner.get())(op->combineop->identity_element, op->source)[op->value_index]`
    // instead of `op->source[op->value_index]`. The former may be more difficult to simplify.
1110
    return this->VisitExpr(
1111
        SelectNode::make(op->condition,
1112 1113 1114 1115 1116 1117 1118 1119
                     op->source[op->value_index],
                     op->combiner->identity_element[op->value_index]));
  }
  // combiner simplification.
  ret = SimplifyReduceCombiner(op);
  return ret;
}

1120
PrimExpr CanonicalSimplifier::operator()(const PrimExpr& expr) {
1121 1122 1123 1124
  return impl_->CanonicalSimplify(expr);
}

void CanonicalSimplifier::Update(const Var& var,
1125
                                 const PrimExpr& info,
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
                                 bool override) {
  impl_->Update(var, info, override);
}

CanonicalSimplifier::CanonicalSimplifier(Analyzer* parent)
    : impl_(new Impl(parent)) {
}

CanonicalSimplifier::~CanonicalSimplifier() {
  delete impl_;
}

}  // namespace arith
}  // namespace tvm