Skip to content

Commit 5aa9efb

Browse files
author
Siva Chandra Reddy
committed
[libc] Fix bug in UInt comparison operators.
Reviewed By: lntue Differential Revision: https://reviews.llvm.org/D128303
1 parent 77ad77c commit 5aa9efb

File tree

2 files changed

+45
-6
lines changed

2 files changed

+45
-6
lines changed

libc/src/__support/CPP/UInt.h

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -247,33 +247,53 @@ template <size_t Bits> class UInt {
247247

248248
constexpr bool operator>(const UInt<Bits> &other) const {
249249
for (size_t i = WordCount; i > 0; --i) {
250-
if (val[i - 1] <= other.val[i - 1])
250+
uint64_t word = val[i - 1];
251+
uint64_t other_word = other.val[i - 1];
252+
if (word > other_word)
253+
return true;
254+
else if (word < other_word)
251255
return false;
252256
}
253-
return true;
257+
// Equal
258+
return false;
254259
}
255260

256261
constexpr bool operator>=(const UInt<Bits> &other) const {
257262
for (size_t i = WordCount; i > 0; --i) {
258-
if (val[i - 1] < other.val[i - 1])
263+
uint64_t word = val[i - 1];
264+
uint64_t other_word = other.val[i - 1];
265+
if (word > other_word)
266+
return true;
267+
else if (word < other_word)
259268
return false;
260269
}
270+
// Equal
261271
return true;
262272
}
263273

264274
constexpr bool operator<(const UInt<Bits> &other) const {
265275
for (size_t i = WordCount; i > 0; --i) {
266-
if (val[i - 1] >= other.val[i - 1])
276+
uint64_t word = val[i - 1];
277+
uint64_t other_word = other.val[i - 1];
278+
if (word > other_word)
267279
return false;
280+
else if (word < other_word)
281+
return true;
268282
}
269-
return true;
283+
// Equal
284+
return false;
270285
}
271286

272287
constexpr bool operator<=(const UInt<Bits> &other) const {
273288
for (size_t i = WordCount; i > 0; --i) {
274-
if (val[i - 1] > other.val[i - 1])
289+
uint64_t word = val[i - 1];
290+
uint64_t other_word = other.val[i - 1];
291+
if (word > other_word)
275292
return false;
293+
else if (word < other_word)
294+
return true;
276295
}
296+
// Equal
277297
return true;
278298
}
279299

libc/test/src/__support/uint128_test.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,22 @@ TEST(LlvmLibcUInt128ClassTest, EqualsTests) {
161161
ASSERT_FALSE(a1 == a_upper);
162162
ASSERT_TRUE(a_lower != a_upper);
163163
}
164+
165+
TEST(LlvmLibcUInt128ClassTest, ComparisonTests) {
166+
UInt128 a({0xffffffff00000000, 0xffff00000000ffff});
167+
UInt128 b({0xff00ff0000ff00ff, 0xf0f0f0f00f0f0f0f});
168+
EXPECT_GT(a, b);
169+
EXPECT_GE(a, b);
170+
EXPECT_LT(b, a);
171+
EXPECT_LE(b, a);
172+
173+
UInt128 x(0xffffffff00000000);
174+
UInt128 y(0x00000000ffffffff);
175+
EXPECT_GT(x, y);
176+
EXPECT_GE(x, y);
177+
EXPECT_LT(y, x);
178+
EXPECT_LE(y, x);
179+
180+
EXPECT_LE(a, a);
181+
EXPECT_GE(a, a);
182+
}

0 commit comments

Comments
 (0)