Skip to content

Commit af4e1e3

Browse files
kazutakahiratamahesh-attarde
authored andcommitted
[ADT] Fix a bug in PackedVector::setValue for signed types (llvm#159239)
Without this patch, we forget to update the sign bit. When we assign: Vec[0] = -1; the sign bit is correctly set to 1. Overwriting the same element: Vec[0] = 1; does not update the sign bit, leaving the 4-bit as 0b1001, which reads -2 according to PackedVector's encoding. (It does not use two's complement.) This patch fixes the bug by clearing the sign bit when we are assigning a non-negative value.
1 parent 0392d7e commit af4e1e3

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

llvm/include/llvm/ADT/PackedVector.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ class PackedVectorBase<T, BitNum, BitVectorTy, true> {
5858
if (val < 0) {
5959
val = ~val;
6060
Bits.set((Idx * BitNum) + BitNum - 1);
61+
} else {
62+
Bits.reset((Idx * BitNum) + BitNum - 1);
6163
}
6264
assert((val >> (BitNum-1)) == 0 && "value is too big");
6365
for (unsigned i = 0; i != BitNum-1; ++i)

llvm/unittests/ADT/PackedVectorTest.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,14 @@ TEST(PackedVectorTest, RawBitsSize) {
7171
EXPECT_EQ(12u, Vec.raw_bits().size());
7272
}
7373

74+
TEST(PackedVectorTest, SignedValueOverwrite) {
75+
PackedVector<signed, 4> Vec(1);
76+
Vec[0] = -1;
77+
EXPECT_EQ(-1, Vec[0]);
78+
Vec[0] = 1;
79+
EXPECT_EQ(1, Vec[0]);
80+
}
81+
7482
#ifdef EXPECT_DEBUG_DEATH
7583

7684
TEST(PackedVectorTest, UnsignedValues) {

0 commit comments

Comments
 (0)