Lunderberg commented on code in PR #12972:
URL: https://github.com/apache/tvm/pull/12972#discussion_r993682474


##########
src/arith/conjunctive_normal_form.cc:
##########
@@ -0,0 +1,415 @@
+/*
+ * 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
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * 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.
+ */
+
+/*!
+ * \file tvm/arith/conjunctive_normal_form.cc
+ */
+
+#include "conjunctive_normal_form.h"
+
+#include <tvm/arith/analyzer.h>
+#include <tvm/tir/expr.h>
+
+#include <optional>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "pattern_match.h"
+#include "rewrite_simplify.h"
+
+namespace tvm {
+namespace arith {
+
+namespace {
+/* \brief A utility for simplifying expressions using conjunctive/disjuctive 
normal forms */
+class AndOfOrs {
+ public:
+  /*! \brief Construct the simplifier
+   *
+   * Convert a PrimExpr to the internal representation.
+   *
+   * \param expr The PrimExpr to be simplified.
+   */
+  explicit AndOfOrs(const PrimExpr& expr);
+
+  /*! \brief Convert internal representation to PrimExpr */
+  PrimExpr AsPrimExpr() const;
+
+  /*! \brief Simplify the internal representation */
+  void Simplify(Analyzer* analyzer);
+
+ private:
+  /*! \brief Internal utility, simplify within each group of expressions
+   *
+   * For each pair of values within a chunk, attempt to simplify them into
+   * a single expression.
+   *
+   * For example,
+   *    before = (a == 5) && ((b < 10) || (b > 10))
+   *    after  = (a == 5) && ((b != 10) || false)
+   */
+  void SimplifyWithinChunks(Analyzer* analyzer);
+
+  /*! \brief Internal utility, simplify across groups of expressions
+   *
+   * For each pair of chunks, if the two chunks differ by only a single
+   * term, attempt to simplify those differing terms.
+   *
+   * For example,
+   *    before = ((a == 5) || (b <= 10)) && ((a == 5) || (b >= 10))
+   *    after  = ((a == 5) || (b == 10)) && ((a == 5) || true)
+   */
+  void SimplifyAcrossChunks(Analyzer* analyzer);
+
+  /*! \brief Remove instances of true/false from internal representation
+   *
+   * To avoid invalidating iterators, `SimplifyWithinChunks` and
+   * `SimplifyAcrossChunks` may replace keys, but may not remove keys from
+   * the internal representation.  For example, `(a < 5) && (a < 10)`
+   * would be simplified to `(a < 5) && true`.  The `Cleanup` function
+   * removes these leftover instances of true/false.
+   */
+  void Cleanup();
+
+  /*! \brief Internal utility function used to convert to internal form */
+  static void VisitAndExpressions(const PrimExpr& expr,
+                                  std::function<void(const PrimExpr&)> 
callback);
+  /*! \brief Internal utility function used to convert to internal form */
+  static void VisitOrExpressions(const PrimExpr& expr,
+                                 std::function<void(const PrimExpr&)> 
callback);
+
+  /* \brief Type-safe wrapper class that represents an PrimExpr
+   *
+   * Because integer indices are used frequently through this class,
+   * maintaining a separation between integer indices used to access
+   * specific elements of the internal representation, and unique
+   * identifiers used to represent expressions PrimExpr, is useful.
+   */
+  enum class Key : size_t {};
+
+  /*! \brief Convert a PrimExpr to a Key */
+  Key GetKey(const PrimExpr& expr);
+
+  /*! \brief Convert a Key to a PrimExpr */
+  PrimExpr GetExpr(Key key) const;
+
+  /*! \brief Attempt to simplify (a && b)
+   *
+   * If successful, will overwrite the parameters `a` and `b` with the
+   * simplified form.
+   */
+  void TrySimplifyOr(Key* a, Key* b, Analyzer* analyzer);
+
+  /*! \brief Attempt to simplify (a || b)
+   *
+   * If successful, will overwrite the parameters `a` and `b` with the
+   * simplified form.
+   */
+  void TrySimplifyAnd(Key* a, Key* b, Analyzer* analyzer);
+
+  /*! \brief The internal representation
+   *
+   * `chunks[i][j]` is the j-th expression in the i-th OR-group.
+   */
+  std::vector<std::vector<Key>> chunks;
+
+  /*! \brief Mapping from internal Key to PrimExpr */
+  std::unordered_map<Key, PrimExpr, StructuralHash, StructuralEqual> 
key_to_expr;
+
+  /*! \brief Mapping from PrimExpr to internal Key */
+  std::unordered_map<PrimExpr, Key, StructuralHash, StructuralEqual> 
expr_to_key;
+
+  /*! \brief Cached key representing tir::Bool(true) */
+  Key key_true;
+
+  /*! \brief Cached key representing tir::Bool(false) */
+  Key key_false;
+};
+
+AndOfOrs::AndOfOrs(const PrimExpr& expr)
+    : key_true(GetKey(Bool(true))), key_false(GetKey(Bool(false))) {
+  VisitAndExpressions(expr, [&](const PrimExpr& outer_expr) {
+    std::vector<Key> or_components;
+    VisitOrExpressions(outer_expr, [&](const PrimExpr& inner_expr) {
+      Key key = GetKey(inner_expr);
+      bool is_duplicate = std::any_of(or_components.begin(), 
or_components.end(),
+                                      [&](Key prev) { return prev == key; });
+      if (!is_duplicate) {
+        or_components.push_back(key);
+      }
+    });
+
+    bool is_permutation =
+        std::any_of(chunks.begin(), chunks.end(), [&](const std::vector<Key>& 
prev_components) {
+          return or_components.size() == prev_components.size() &&
+                 std::is_permutation(prev_components.begin(), 
prev_components.end(),
+                                     or_components.begin());
+        });
+    if (!is_permutation) {
+      chunks.push_back(std::move(or_components));
+    }
+  });
+}
+
+void AndOfOrs::VisitAndExpressions(const PrimExpr& expr,
+                                   std::function<void(const PrimExpr&)> 
callback) {
+  PVar<PrimExpr> x, y, z;
+  if ((x && y).Match(expr)) {
+    VisitAndExpressions(x.Eval(), callback);
+    VisitAndExpressions(y.Eval(), callback);
+  } else if ((x || y).Match(expr)) {
+    VisitAndExpressions(x.Eval(), [&](const PrimExpr& x_part) {
+      VisitAndExpressions(y.Eval(), [&](const PrimExpr& y_part) { 
callback(x_part || y_part); });
+    });
+  } else {
+    callback(expr);
+  }
+}

Review Comment:
   Good call, and updated.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to