aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimon Pilgrim <RKSimon@users.noreply.github.com>2024-02-19 15:59:21 +0000
committerGitHub <noreply@github.com>2024-02-19 15:59:21 +0000
commit73f76cda1f1acc496154c3acecc2e74b1280a9bd (patch)
tree6e7fdbd621ce5868a040c6788f14f504986c6b9b
parent1789dc2fbc3b409a7f9469465cc8a5f6fa333a4c (diff)
downloadllvm-73f76cda1f1acc496154c3acecc2e74b1280a9bd.zip
llvm-73f76cda1f1acc496154c3acecc2e74b1280a9bd.tar.gz
llvm-73f76cda1f1acc496154c3acecc2e74b1280a9bd.tar.bz2
[APInt] Add APIntOps::absdiff to compute the absolute difference of 2 unsigned values (#82255)
Equivalent to "umax(A, B) - umin(A, B)" First step towards adding knownbits support for absdiff patterns for #81765
-rw-r--r--llvm/include/llvm/ADT/APInt.h5
-rw-r--r--llvm/unittests/ADT/APIntTest.cpp34
2 files changed, 39 insertions, 0 deletions
diff --git a/llvm/include/llvm/ADT/APInt.h b/llvm/include/llvm/ADT/APInt.h
index 6f2f255..6c05367 100644
--- a/llvm/include/llvm/ADT/APInt.h
+++ b/llvm/include/llvm/ADT/APInt.h
@@ -2187,6 +2187,11 @@ inline const APInt &umax(const APInt &A, const APInt &B) {
return A.ugt(B) ? A : B;
}
+/// Determine the absolute difference of two APInts considered to be unsigned.
+inline const APInt absdiff(const APInt &A, const APInt &B) {
+ return A.uge(B) ? (A - B) : (B - A);
+}
+
/// Compute GCD of two unsigned APInt values.
///
/// This function returns the greatest common divisor of the two APInt values
diff --git a/llvm/unittests/ADT/APIntTest.cpp b/llvm/unittests/ADT/APIntTest.cpp
index 3b909f8..2fe59f0 100644
--- a/llvm/unittests/ADT/APIntTest.cpp
+++ b/llvm/unittests/ADT/APIntTest.cpp
@@ -2497,6 +2497,40 @@ TEST(APIntTest, clearLowBits) {
EXPECT_EQ(16u, i32hi16.popcount());
}
+TEST(APIntTest, AbsDiff) {
+ using APIntOps::absdiff;
+
+ APInt MaxU1(1, 1, false);
+ APInt MinU1(1, 0, false);
+ EXPECT_EQ(1u, absdiff(MaxU1, MinU1).getZExtValue());
+ EXPECT_EQ(1u, absdiff(MinU1, MaxU1).getZExtValue());
+
+ APInt MaxU4(4, 15, false);
+ APInt MinU4(4, 0, false);
+ EXPECT_EQ(15u, absdiff(MaxU4, MinU4).getZExtValue());
+ EXPECT_EQ(15u, absdiff(MinU4, MaxU4).getZExtValue());
+
+ APInt MaxS8(8, 127, true);
+ APInt MinS8(8, -128, true);
+ EXPECT_EQ(1u, absdiff(MaxS8, MinS8).getZExtValue());
+ EXPECT_EQ(1u, absdiff(MinS8, MaxS8).getZExtValue());
+
+ APInt MaxU16(16, 65535, false);
+ APInt MinU16(16, 0, false);
+ EXPECT_EQ(65535u, absdiff(MaxU16, MinU16).getZExtValue());
+ EXPECT_EQ(65535u, absdiff(MinU16, MaxU16).getZExtValue());
+
+ APInt MaxS16(16, 32767, true);
+ APInt MinS16(16, -32768, true);
+ APInt ZeroS16(16, 0, true);
+ EXPECT_EQ(1u, absdiff(MaxS16, MinS16).getZExtValue());
+ EXPECT_EQ(1u, absdiff(MinS16, MaxS16).getZExtValue());
+ EXPECT_EQ(32768u, absdiff(ZeroS16, MinS16));
+ EXPECT_EQ(32768u, absdiff(MinS16, ZeroS16));
+ EXPECT_EQ(32767u, absdiff(ZeroS16, MaxS16));
+ EXPECT_EQ(32767u, absdiff(MaxS16, ZeroS16));
+}
+
TEST(APIntTest, GCD) {
using APIntOps::GreatestCommonDivisor;