[llvm] [DAG] SDPatternMatch - add matchers for reassociatable binops (PR #119985)

Ethan Kaji via llvm-commits llvm-commits at lists.llvm.org
Thu Apr 10 12:44:33 PDT 2025


================
@@ -1134,6 +1136,87 @@ inline BinaryOpc_match<ValTy, AllOnes_match, true> m_Not(const ValTy &V) {
   return m_Xor(V, m_AllOnes());
 }
 
+template <typename... PatternTs> struct ReassociatableOpc_match {
+  unsigned Opcode;
+  std::tuple<PatternTs...> Patterns;
+
+  ReassociatableOpc_match(unsigned Opcode, const PatternTs &...Patterns)
+      : Opcode(Opcode), Patterns(Patterns...) {}
+
+  template <typename MatchContext>
+  bool match(const MatchContext &Ctx, SDValue N) {
+    SmallVector<SDValue> Leaves;
+    collectLeaves(N, Leaves);
+    if (Leaves.size() != std::tuple_size_v<std::tuple<PatternTs...>>)
+      return false;
+
+    // Matches[I][J] == true iff sd_context_match(Leaves[I], Ctx,
+    // std::get<J>(Patterns)) == true
+    std::array<SmallBitVector, std::tuple_size_v<std::tuple<PatternTs...>>>
+        Matches;
+    for (size_t I = 0, N = Leaves.size(); I < N; I++) {
+      SmallVector<bool> MatchResults;
+      std::apply(
+          [&](auto &...P) {
+            (Matches[I].push_back(sd_context_match(Leaves[I], Ctx, P)), ...);
----------------
Esan5 wrote:

I may be misunderstanding, but is the intention here for 
```
if (sd_match(N, m_ReassociatableAdd(m_Srl(m_Value(A), m_SpecificInt(1)),
                                        m_Srl(m_Value(B), m_SpecificInt(1)),
                                        m_Value(C))))
```

to match

```
%s0 = lshr i64 %a0, 1
%s1 = lshr i64 %a1, 1
%s = add i64 %s1, %s0
```

The code in [this helper function](https://github.com/llvm/llvm-project/pull/119985/files#diff-9e3d3860697182773cc3ea371af57d625e8f1dc931359e58799f90460363afc7R1180-R1193) should prevent a given sub-pattern from being used to match more then one leaf by tracking which patterns have already been used.

Unfortunately, I don't have enough experience with LLVM to identify the intended behavior, can you clarify what this test case should do?

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


More information about the llvm-commits mailing list