Skip to content

Commit 45f5fa2

Browse files
committed
[IR] Add commutable matcher for add nuw; NFC
Closes #87179
1 parent 0207819 commit 45f5fa2

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

llvm/include/llvm/IR/PatternMatch.h

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,7 +1185,7 @@ inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
11851185
}
11861186

11871187
template <typename LHS_t, typename RHS_t, unsigned Opcode,
1188-
unsigned WrapFlags = 0>
1188+
unsigned WrapFlags = 0, bool Commutable = false>
11891189
struct OverflowingBinaryOp_match {
11901190
LHS_t L;
11911191
RHS_t R;
@@ -1203,7 +1203,9 @@ struct OverflowingBinaryOp_match {
12031203
if ((WrapFlags & OverflowingBinaryOperator::NoSignedWrap) &&
12041204
!Op->hasNoSignedWrap())
12051205
return false;
1206-
return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
1206+
return (L.match(Op->getOperand(0)) && R.match(Op->getOperand(1))) ||
1207+
(Commutable && L.match(Op->getOperand(1)) &&
1208+
R.match(Op->getOperand(0)));
12071209
}
12081210
return false;
12091211
}
@@ -1250,6 +1252,16 @@ m_NUWAdd(const LHS &L, const RHS &R) {
12501252
OverflowingBinaryOperator::NoUnsignedWrap>(
12511253
L, R);
12521254
}
1255+
1256+
template <typename LHS, typename RHS>
1257+
inline OverflowingBinaryOp_match<
1258+
LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true>
1259+
m_c_NUWAdd(const LHS &L, const RHS &R) {
1260+
return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1261+
OverflowingBinaryOperator::NoUnsignedWrap,
1262+
true>(L, R);
1263+
}
1264+
12531265
template <typename LHS, typename RHS>
12541266
inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
12551267
OverflowingBinaryOperator::NoUnsignedWrap>

llvm/unittests/IR/PatternMatch.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -948,6 +948,16 @@ TEST_F(PatternMatchTest, OverflowingBinOps) {
948948
EXPECT_EQ(L, MatchL);
949949
EXPECT_EQ(R, MatchR);
950950
MatchL = MatchR = nullptr;
951+
952+
EXPECT_TRUE(
953+
m_c_NUWAdd(m_Specific(L), m_Specific(R)).match(IRB.CreateNUWAdd(L, R)));
954+
EXPECT_TRUE(
955+
m_c_NUWAdd(m_Specific(R), m_Specific(L)).match(IRB.CreateNUWAdd(L, R)));
956+
EXPECT_FALSE(
957+
m_c_NUWAdd(m_Specific(R), m_ZeroInt()).match(IRB.CreateNUWAdd(L, R)));
958+
EXPECT_FALSE(
959+
m_NUWAdd(m_Specific(R), m_Specific(L)).match(IRB.CreateNUWAdd(L, R)));
960+
951961
EXPECT_TRUE(
952962
m_NUWSub(m_Value(MatchL), m_Value(MatchR)).match(IRB.CreateNUWSub(L, R)));
953963
EXPECT_EQ(L, MatchL);

0 commit comments

Comments
 (0)