[llvm] [IR] Add commutable matcher for `add nuw`; NFC (PR #87179)
via llvm-commits
llvm-commits at lists.llvm.org
Sat Mar 30 20:42:04 PDT 2024
https://github.com/goldsteinn created https://github.com/llvm/llvm-project/pull/87179
None
>From ec56d1211fc593fb413f1d7af1e7b2724f0267c5 Mon Sep 17 00:00:00 2001
From: Noah Goldstein <goldstein.w.n at gmail.com>
Date: Sat, 30 Mar 2024 21:39:40 -0500
Subject: [PATCH] [IR] Add commutable matcher for `add nuw`; NFC
---
llvm/include/llvm/IR/PatternMatch.h | 16 ++++++++++++++--
llvm/unittests/IR/PatternMatch.cpp | 10 ++++++++++
2 files changed, 24 insertions(+), 2 deletions(-)
diff --git a/llvm/include/llvm/IR/PatternMatch.h b/llvm/include/llvm/IR/PatternMatch.h
index 46372c78263a1d..92cb79d54afc29 100644
--- a/llvm/include/llvm/IR/PatternMatch.h
+++ b/llvm/include/llvm/IR/PatternMatch.h
@@ -1185,7 +1185,7 @@ inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
}
template <typename LHS_t, typename RHS_t, unsigned Opcode,
- unsigned WrapFlags = 0>
+ unsigned WrapFlags = 0, bool Commutable = false>
struct OverflowingBinaryOp_match {
LHS_t L;
RHS_t R;
@@ -1203,7 +1203,9 @@ struct OverflowingBinaryOp_match {
if ((WrapFlags & OverflowingBinaryOperator::NoSignedWrap) &&
!Op->hasNoSignedWrap())
return false;
- return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
+ return (L.match(Op->getOperand(0)) && R.match(Op->getOperand(1))) ||
+ (Commutable && L.match(Op->getOperand(1)) &&
+ R.match(Op->getOperand(0)));
}
return false;
}
@@ -1250,6 +1252,16 @@ m_NUWAdd(const LHS &L, const RHS &R) {
OverflowingBinaryOperator::NoUnsignedWrap>(
L, R);
}
+
+template <typename LHS, typename RHS>
+inline OverflowingBinaryOp_match<
+ LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true>
+m_c_NUWAdd(const LHS &L, const RHS &R) {
+ return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
+ OverflowingBinaryOperator::NoUnsignedWrap,
+ true>(L, R);
+}
+
template <typename LHS, typename RHS>
inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
OverflowingBinaryOperator::NoUnsignedWrap>
diff --git a/llvm/unittests/IR/PatternMatch.cpp b/llvm/unittests/IR/PatternMatch.cpp
index a0b873de2d5860..4d0c2e4220fec7 100644
--- a/llvm/unittests/IR/PatternMatch.cpp
+++ b/llvm/unittests/IR/PatternMatch.cpp
@@ -948,6 +948,16 @@ TEST_F(PatternMatchTest, OverflowingBinOps) {
EXPECT_EQ(L, MatchL);
EXPECT_EQ(R, MatchR);
MatchL = MatchR = nullptr;
+
+ EXPECT_TRUE(
+ m_c_NUWAdd(m_Specific(L), m_Specific(R)).match(IRB.CreateNUWAdd(L, R)));
+ EXPECT_TRUE(
+ m_c_NUWAdd(m_Specific(R), m_Specific(L)).match(IRB.CreateNUWAdd(L, R)));
+ EXPECT_FALSE(
+ m_c_NUWAdd(m_Specific(R), m_ZeroInt()).match(IRB.CreateNUWAdd(L, R)));
+ EXPECT_FALSE(
+ m_NUWAdd(m_Specific(R), m_Specific(L)).match(IRB.CreateNUWAdd(L, R)));
+
EXPECT_TRUE(
m_NUWSub(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNUWSub(L, R)));
EXPECT_EQ(L, MatchL);
More information about the llvm-commits
mailing list