This is an automated email from the ASF dual-hosted git repository.

spectrometerHBH pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-tirx.git


The following commit(s) were added to refs/heads/main by this push:
     new 20c76ffb4 [TIRx] Give each statement occurrence a distinct identity 
(#262)
20c76ffb4 is described below

commit 20c76ffb4d7b3abbe22e69d5861d34f73ce5185b
Author: Tianqi Chen <[email protected]>
AuthorDate: Mon Nov 23 18:53:56 2026 -0500

    [TIRx] Give each statement occurrence a distinct identity (#262)
    
    Add `MakeStmtUnique` to give each statement occurrence within a function
    a distinct node identity. The pass copies repeated statements while
    preserving shared expressions and variable identity. It uses the default
    sequence mutation to flatten nested sequences and remove no-op
    statements.
    
    Check this invariant during well-formedness verification and normalize
    changed unroll output so downstream passes can associate analysis
    results with individual statements.
---
 docs/reference/python/tirx.transform.rst           |  1 +
 include/tvm/tirx/transform.h                       |  3 ++
 python/tvm_tirx/tirx/transform/transform.py        |  9 +++++
 rust/tvm-tirx/src/tirx/transform/transform.rs      |  5 +++
 src/tirx/analysis/check_well_formed.cc             | 38 +++++++++++++++++---
 src/tirx/transform/ir_utils.cc                     | 40 +++++++++++++++++++---
 src/tirx/transform/ir_utils.h                      |  3 ++
 src/tirx/transform/unroll_loop.cc                  |  2 +-
 .../tirx/transform/test_common_subexpr_elim.py     | 11 +++---
 tests/python/tirx/transform/test_convert_ssa.py    | 37 ++++++++++++++++++++
 10 files changed, 133 insertions(+), 16 deletions(-)

diff --git a/docs/reference/python/tirx.transform.rst 
b/docs/reference/python/tirx.transform.rst
index 0dee81a24..d05df04fc 100644
--- a/docs/reference/python/tirx.transform.rst
+++ b/docs/reference/python/tirx.transform.rst
@@ -55,6 +55,7 @@ Passes
    StmtSimplify
    LowerThreadAllreduce
    ConvertSSA
+   MakeStmtUnique
    MakePackedAPI
    SplitHostDevice
    SkipAssert
diff --git a/include/tvm/tirx/transform.h b/include/tvm/tirx/transform.h
index cca75c532..5f4404a5a 100644
--- a/include/tvm/tirx/transform.h
+++ b/include/tvm/tirx/transform.h
@@ -152,6 +152,9 @@ TVM_TIRX_DLL Pass StmtSimplify();
  */
 TVM_TIRX_DLL Pass ConvertSSA();
 
+/*! \brief Give each statement occurrence in a function a distinct identity. */
+TVM_TIRX_DLL Pass MakeStmtUnique();
+
 /*! \brief Lower cross-thread reductions to target-specific communication. */
 TVM_TIRX_DLL Pass LowerThreadAllreduce();
 
diff --git a/python/tvm_tirx/tirx/transform/transform.py 
b/python/tvm_tirx/tirx/transform/transform.py
index 0227defd5..c7a3860ef 100644
--- a/python/tvm_tirx/tirx/transform/transform.py
+++ b/python/tvm_tirx/tirx/transform/transform.py
@@ -722,6 +722,15 @@ def LowerThreadAllreduce():
     return _ffi_api.LowerThreadAllreduce()
 
 
+def MakeStmtUnique():
+    """Give each statement occurrence in a function a distinct identity.
+
+    Variables and expressions retain their identity. Sequence mutation also
+    flattens nested sequences and removes no-op statements.
+    """
+    return _ffi_api.MakeStmtUnique()  # type: ignore
+
+
 def ConvertSSA():
     """Give every variable definition in an IRModule a distinct identity.
 
diff --git a/rust/tvm-tirx/src/tirx/transform/transform.rs 
b/rust/tvm-tirx/src/tirx/transform/transform.rs
index 477261cc1..d9fdd5257 100644
--- a/rust/tvm-tirx/src/tirx/transform/transform.rs
+++ b/rust/tvm-tirx/src/tirx/transform/transform.rs
@@ -208,6 +208,11 @@ pub fn convert_ssa() -> Result<Pass> {
     
tvm_ffi::cached_global_func!("tirx.transform.ConvertSSA").call_tuple(())?.try_into()
 }
 
+/// Give each statement occurrence in a function a distinct identity 
(`tirx.transform.MakeStmtUnique`).
+pub fn make_stmt_unique() -> Result<Pass> {
+    
tvm_ffi::cached_global_func!("tirx.transform.MakeStmtUnique").call_tuple(())?.try_into()
+}
+
 /// Wrap each function body in a `tirx.device_scope` region 
(`tirx.transform.DecorateDeviceScope`).
 pub fn decorate_device_scope() -> Result<Pass> {
     
tvm_ffi::cached_global_func!("tirx.transform.DecorateDeviceScope").call_tuple(())?.try_into()
diff --git a/src/tirx/analysis/check_well_formed.cc 
b/src/tirx/analysis/check_well_formed.cc
index 7261e9b62..93350721f 100644
--- a/src/tirx/analysis/check_well_formed.cc
+++ b/src/tirx/analysis/check_well_formed.cc
@@ -35,6 +35,7 @@
 #include <optional>
 #include <sstream>
 #include <unordered_map>
+#include <unordered_set>
 #include <utility>
 #include <vector>
 
@@ -48,7 +49,7 @@ class WellFormednessVerifier : public StmtExprVisitor {
   friend class tvm::ObjectVisitor;
 
  public:
-  enum class Check { kVariables, kTensors, kTensorLoadType, kLoopControl, 
kThreadBinding };
+  enum class Check { kVariables, kTensors, kTensorLoadType, kStatements, 
kThreadBinding };
   using AccessPath = ffi::reflection::AccessPath;
   using Result = ffi::Optional<VisitInterrupt>;
 
@@ -120,6 +121,11 @@ class WellFormednessVerifier : public StmtExprVisitor {
       TVM_FFI_VISIT_THROW(TypeError, object.value())
           << "Unsupported non-primitive TIR expression " << 
object.value()->GetTypeKey();
     }
+    if (check_ == Check::kStatements) {
+      if (const auto* stmt = value.as<StmtObj>(); stmt && 
!seen_stmts_.insert(stmt).second) {
+        return ReportSharedStatement(object.value());
+      }
+    }
     if (value.as<Stmt>() && !table_->CanDispatch(value)) {
       TVM_FFI_VISIT_BEGIN();
       Verify(false) << "TIR verifier does not support statement " << 
object.value()->GetTypeKey()
@@ -140,6 +146,26 @@ class WellFormednessVerifier : public StmtExprVisitor {
     return StmtExprVisitor::Visit(value);
   }
 
+  Result ReportSharedStatement(const ffi::ObjectRef& stmt) {
+    has_error_ = true;
+    if (!assert_mode_) return std::nullopt;
+    // Search this body by identity. The current visit's breadcrumbs only 
describe one
+    // parent, and a module may expose the same function under multiple 
globals.
+    const auto& function = visit_stack_[root_.as<IRModuleObj>() ? 1 : 0];
+    auto pattern = ffi::make_object<ffi::VisitErrorContextObj>();
+    pattern->reverse_visit_pattern.push_back(stmt);
+    auto paths = ffi::VisitErrorContext::FindAccessPaths(
+        function.as_or_throw<Function>()->body, 
ffi::VisitErrorContext(std::move(pattern)));
+    std::ostringstream locations;
+    if (paths.size() >= 2) {
+      locations << " Occurrences in the body include " << paths[0] << " and " 
<< paths[1] << ".";
+    }
+    TVM_FFI_VISIT_THROW(ValueError, stmt)
+        << "Statement at <current location> occurs more than once in the same 
function."
+        << locations.str();
+    TVM_FFI_UNREACHABLE();
+  }
+
   class VerifyStream {
    public:
     explicit VerifyStream(bool fail) {
@@ -295,6 +321,7 @@ class WellFormednessVerifier : public StmtExprVisitor {
                        "but a definition is required.";
       return std::nullopt;
     }
+    seen_stmts_.clear();
     int enclosing_depth = loop_depth_;
     loop_depth_ = 0;
     WithScope([&]() -> Result {
@@ -374,7 +401,7 @@ class WellFormednessVerifier : public StmtExprVisitor {
     this->Visit(op->begin);
     this->Visit(op->end);
     this->Visit(op->step);
-    if (check_ == Check::kLoopControl) {
+    if (check_ == Check::kStatements) {
       ++loop_depth_;
       this->Visit(op->body);
       --loop_depth_;
@@ -458,7 +485,7 @@ class WellFormednessVerifier : public StmtExprVisitor {
   }
 
   Result Visit_(const BreakObj* op) override {
-    if (check_ == Check::kLoopControl) {
+    if (check_ == Check::kStatements) {
       Verify(loop_depth_ > 0) << "ValueError: break at <current location> 
requires an enclosing "
                                  "loop in the same function.";
     }
@@ -466,7 +493,7 @@ class WellFormednessVerifier : public StmtExprVisitor {
   }
 
   Result Visit_(const ContinueObj* op) override {
-    if (check_ == Check::kLoopControl) {
+    if (check_ == Check::kStatements) {
       Verify(loop_depth_ > 0) << "ValueError: continue at <current location> 
requires an enclosing "
                                  "loop in the same function.";
     }
@@ -492,6 +519,7 @@ class WellFormednessVerifier : public StmtExprVisitor {
   bool assert_mode_;
   bool has_error_{false};
   int loop_depth_{0};
+  std::unordered_set<const StmtObj*> seen_stmts_;
   ffi::ObjectRef root_;
   std::vector<ffi::ObjectRef> visit_stack_;
   ScopeStack<std::vector<std::pair<Var, DefinitionSite>>> scopes_;
@@ -572,7 +600,7 @@ auto WellFormednessVerifier::Visit_(const TensorLoadObj* 
op) -> Result {
 bool CheckWellFormedCommon(const ffi::ObjectRef& node, bool assert_mode) {
   using Check = WellFormednessVerifier::Check;
   for (Check check :
-       {Check::kVariables, Check::kTensors, Check::kTensorLoadType, 
Check::kLoopControl}) {
+       {Check::kVariables, Check::kTensors, Check::kTensorLoadType, 
Check::kStatements}) {
     if (!ffi::make_object<WellFormednessVerifier>(check, 
assert_mode)->Run(node)) return false;
   }
   return true;
diff --git a/src/tirx/transform/ir_utils.cc b/src/tirx/transform/ir_utils.cc
index 7e4843a92..54439c3ab 100644
--- a/src/tirx/transform/ir_utils.cc
+++ b/src/tirx/transform/ir_utils.cc
@@ -24,6 +24,7 @@
 #include "ir_utils.h"
 
 #include <tvm/ffi/cast.h>
+#include <tvm/ffi/extra/structural_mutate.h>
 #include <tvm/ffi/extra/structural_visit.h>
 #include <tvm/ffi/reflection/registry.h>
 #include <tvm/ir/function.h>
@@ -50,7 +51,6 @@ class IRConvertSSA final : public StmtExprMutator {
   using StmtExprMutator::Mutate;
   using StmtExprMutator::Mutate_;
   Function VisitFunction(Function func);
-  IRModule VisitIRModule(IRModule mod);
 
  private:
   UnchangedOr<Expr> Mutate_(const VarObj* op, InplaceMode inplace_mode) final;
@@ -241,12 +241,13 @@ void IRConvertSSA::SetVarRemap(const Var& old_var, const 
Var& new_var) {
   scope_.Current().insert_or_assign(old_var.get(), new_var);
 }
 
-IRModule IRConvertSSA::VisitIRModule(IRModule mod) {
+template <typename F>
+IRModule MapFunctions(IRModule mod, F transform) {
   ffi::Map<GlobalVar, BaseFunc> functions;
   bool made_change = false;
   for (auto [gvar, base_func] : mod->functions) {
     if (auto* ptr = base_func.as<tirx::FunctionObj>()) {
-      auto updated = VisitFunction(ffi::GetRef<tirx::Function>(ptr));
+      auto updated = transform(ffi::GetRef<tirx::Function>(ptr));
       if (!updated.same_as(base_func)) {
         made_change = true;
         base_func = updated;
@@ -265,17 +266,46 @@ Stmt ConvertSSA(Stmt stmt) {
   return ffi::make_object<IRConvertSSA>()->Mutate(stmt, 
InplaceMode::kAllow).ValueOrUnchanged(stmt);
 }
 
+Stmt MakeStmtUnique(Stmt stmt) {
+  std::unordered_set<const StmtObj*> seen;
+  auto visit = [&](const Stmt& node, ffi::StructuralMutatorObj* mutator) -> 
ffi::Any {
+    // Visit every occurrence. Copying a shared parent alone would leave its 
children shared.
+    bool repeated = !seen.insert(node.get()).second;
+    auto result = mutator->DefaultMutateExpected(node, 
InplaceMode::kDisallow).value();
+    if (!repeated || !result.UnchangedOrSameAs(node)) return result;
+    static const ffi::reflection::TypeAttrColumn 
shallow_copy(ffi::type_attr::kShallowCopy);
+    return shallow_copy[node->type_index()].cast<ffi::Function>()(node);
+  };
+  auto keep_expr = [](const Expr&, ffi::StructuralMutatorObj*) { return 
ffi::Unchanged(); };
+  return ffi::StructuralMutate(std::move(stmt), visit, keep_expr).cast<Stmt>();
+}
+
 namespace transform {
 Pass ConvertSSA() {
   auto pass_func = [](IRModule mod, PassContext ctx) {
-    return 
ffi::make_object<tirx::IRConvertSSA>()->VisitIRModule(std::move(mod));
+    auto converter = ffi::make_object<IRConvertSSA>();
+    return MapFunctions(std::move(mod),
+                        [&](Function func) { return 
converter->VisitFunction(std::move(func)); });
   };
   return tvm::transform::CreateModulePass(pass_func, 0, "tirx.ConvertSSA");
 }
 
+Pass MakeStmtUnique() {
+  auto pass_func = [](IRModule mod, PassContext ctx) {
+    return MapFunctions(std::move(mod), [](Function func) {
+      Stmt body = tirx::MakeStmtUnique(func->body);
+      if (!body.same_as(func->body)) func.CopyOnWrite()->body = 
SeqStmt(std::move(body));
+      return func;
+    });
+  };
+  return tvm::transform::CreateModulePass(pass_func, 0, "tirx.MakeStmtUnique");
+}
+
 TVM_FFI_STATIC_INIT_BLOCK() {
   namespace refl = tvm::ffi::reflection;
-  refl::GlobalDef().def("tirx.transform.ConvertSSA", ConvertSSA);
+  refl::GlobalDef()
+      .def("tirx.transform.ConvertSSA", ConvertSSA)
+      .def("tirx.transform.MakeStmtUnique", MakeStmtUnique);
 }
 
 }  // namespace transform
diff --git a/src/tirx/transform/ir_utils.h b/src/tirx/transform/ir_utils.h
index 1a8dcfc26..e01219cb1 100644
--- a/src/tirx/transform/ir_utils.h
+++ b/src/tirx/transform/ir_utils.h
@@ -67,6 +67,9 @@ inline PrimType APIType(const PrimType& t) {
  */
 Stmt ConvertSSA(Stmt stmt);
 
+/*! \brief Give each occurrence of a statement in this tree a distinct 
identity. */
+Stmt MakeStmtUnique(Stmt stmt);
+
 }  // namespace tirx
 }  // namespace tvm
 #endif  // TVM_TIRX_TRANSFORM_IR_UTILS_H_
diff --git a/src/tirx/transform/unroll_loop.cc 
b/src/tirx/transform/unroll_loop.cc
index 833b41d9b..6aa278477 100644
--- a/src/tirx/transform/unroll_loop.cc
+++ b/src/tirx/transform/unroll_loop.cc
@@ -358,7 +358,7 @@ Stmt UnrollLoop(Stmt stmt, UnrollLoopConfig cfg) {
                                      cfg->explicit_unroll, 
cfg->unroll_local_access)
           ->Mutate(stmt, InplaceMode::kDisallow);
   if (!result.UnchangedOrSameAs(stmt)) {
-    return ConvertSSA(std::move(result).ValueUnchecked());
+    return MakeStmtUnique(ConvertSSA(std::move(result).ValueUnchecked()));
   } else {
     return stmt;
   }
diff --git a/tests/python/tirx/transform/test_common_subexpr_elim.py 
b/tests/python/tirx/transform/test_common_subexpr_elim.py
index 3d33e08a5..1c9d97c4a 100644
--- a/tests/python/tirx/transform/test_common_subexpr_elim.py
+++ b/tests/python/tirx/transform/test_common_subexpr_elim.py
@@ -583,8 +583,7 @@ def test_no_lift_bool_logical():
     assert "cse_v" not in after["main"].script()
 
 
-# T24: Shared subtree stays SSA. UnrollLoop reuses one Stmt object across
-# positions; the identity-keyed rewriter must bind fresh cse vars per 
occurrence.
+# The identity-keyed rewriter must bind fresh CSE variables per statement 
occurrence.
 def test_shared_subtree_stays_ssa():
     @tvm_tirx.script.ir_module
     class Before:
@@ -611,9 +610,11 @@ def test_shared_subtree_stays_ssa():
 
     unrolled = tvm_tirx.tirx.transform.UnrollLoop()(Before)
     body = unrolled["main"].body
-    assert body[0].same_as(body[2])
-    assert body[1].same_as(body[3])
-    After = tvm_tirx.tirx.transform.CommonSubexprElim()(unrolled)
+    assert not body[0].same_as(body[2])
+    assert not body[1].same_as(body[3])
+    # Construct shared input explicitly to exercise CSE on repeated statement 
identities.
+    shared = tvm_tirx.IRModule({"main": unrolled["main"].with_body([body[0], 
body[1]] * 2)})
+    After = tvm_tirx.tirx.transform.CommonSubexprElim()(shared)
     tvm_tirx.ir.assert_structural_equal(After, Expected)
     assert tvm_tirx.tirx.analysis.check_well_formed(After["main"])
 
diff --git a/tests/python/tirx/transform/test_convert_ssa.py 
b/tests/python/tirx/transform/test_convert_ssa.py
index b102c6307..d51d4e859 100644
--- a/tests/python/tirx/transform/test_convert_ssa.py
+++ b/tests/python/tirx/transform/test_convert_ssa.py
@@ -19,6 +19,8 @@
 # ruff: noqa: F841
 
 
+import pytest
+
 import tvm_tirx
 import tvm_tirx.testing
 from tvm_tirx.script import ir as I
@@ -499,5 +501,40 @@ def test_reused_loop_var_in_decl_tensor_elem_offset():
     tvm_tirx.tirx.analysis.check_well_formed(After["main"], assert_mode=True)
 
 
+def test_make_stmt_unique():
+    ir = tvm_tirx.ir
+    check = tvm_tirx.tirx.analysis.check_well_formed
+    normalize = tvm_tirx.tirx.transform.MakeStmtUnique()
+    x = ir.Var("x", "int32")
+    value = x + 1
+    branch = ir.If(x > 0, [ir.Evaluate(value)], None)
+    shared_across_functions = ir.Evaluate(1)
+    helper = tvm_tirx.tirx.Function([], shared_across_functions)
+    before = tvm_tirx.IRModule(
+        {
+            "main": tvm_tirx.tirx.Function([x], [branch, branch, 
shared_across_functions]),
+            "f": helper,
+        }
+    )
+
+    assert not check(before, assert_mode=False)
+    with pytest.raises(
+        (ValueError, RuntimeError), match=r"occurs more than 
once.*seq\[0\].*seq\[1\]"
+    ):
+        check(before)
+    after = normalize(before)
+    assert check(after)
+    first, second, last = after["main"].body
+    assert after["f"].same_as(helper)
+    assert last.same_as(after["f"].body[0])
+    assert first.same_as(branch)
+    assert not second.same_as(first)
+    assert not second.then_case.same_as(first.then_case)
+    assert not second.then_case[0].same_as(first.then_case[0])
+    assert second.then_case[0].value.same_as(value)
+    assert after["main"].params[0].same_as(x)
+    assert normalize(after).same_as(after)
+
+
 if __name__ == "__main__":
     tvm_tirx.testing.main()

Reply via email to