[Mlir-commits] [mlir] [mlir][AffineExpr] Order arguments in the commutative affine exprs (PR #146895)

Oleksandr Alex Zinenko llvmlistbot at llvm.org
Thu Jul 3 08:29:18 PDT 2025


================
@@ -784,16 +784,48 @@ static AffineExpr simplifyAdd(AffineExpr lhs, AffineExpr rhs) {
   return nullptr;
 }
 
+static std::pair<AffineExpr, AffineExpr>
+orderCommutativeArgs(AffineExpr expr1, AffineExpr expr2) {
+  auto sym1 = dyn_cast<AffineSymbolExpr>(expr1);
+  auto sym2 = dyn_cast<AffineSymbolExpr>(expr2);
+  // Try to order by symbol/dim position first
+  if (sym1 && sym2)
+    return sym1.getPosition() < sym2.getPosition() ? std::pair{expr1, expr2}
+                                                   : std::pair{expr2, expr1};
+
+  auto dim1 = dyn_cast<AffineDimExpr>(expr1);
+  auto dim2 = dyn_cast<AffineDimExpr>(expr2);
+  if (dim1 && dim2)
+    return dim1.getPosition() < dim2.getPosition() ? std::pair{expr1, expr2}
+                                                   : std::pair{expr2, expr1};
+
+  // Put dims before symbols
+  if (dim1 && sym2)
+    return {dim1, sym2};
+
+  if (sym1 && dim2)
+    return {dim2, sym1};
+
+  // Move constants to the right
+  if (isa<AffineConstantExpr>(expr1) && !isa<AffineConstantExpr>(expr2))
+    return {expr2, expr1};
----------------
ftynse wrote:

Could you double-check composition with special cases. IIRC, in multiplication, we wanted to put the constant on the LHS, and there was something special about -1 as well.

https://github.com/llvm/llvm-project/pull/146895


More information about the Mlir-commits mailing list