Skip to content

Commit 6459f39

Browse files
authored
[clang][bytecode] Add some convenience API to BitcastBuffer (#169516)
So we check the offsets before using them.
1 parent 8396d4c commit 6459f39

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

clang/lib/AST/ByteCode/BitcastBuffer.h

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@ struct BitcastBuffer {
8989
Data = std::make_unique<std::byte[]>(ByteSize);
9090
}
9191

92+
/// Returns the byte at the given offset.
93+
std::byte *atByte(unsigned Offset) {
94+
assert(Offset < FinalBitSize.roundToBytes());
95+
return Data.get() + Offset;
96+
}
97+
9298
/// Returns the buffer size in bits.
9399
Bits size() const { return FinalBitSize; }
94100
Bytes byteSize() const { return FinalBitSize.toBytes(); }
@@ -113,6 +119,13 @@ struct BitcastBuffer {
113119
std::unique_ptr<std::byte[]> copyBits(Bits BitOffset, Bits BitWidth,
114120
Bits FullBitWidth,
115121
Endian TargetEndianness) const;
122+
123+
/// Dereferences the value at the given offset.
124+
template <typename T> T deref(Bytes Offset) const {
125+
assert(Offset.getQuantity() < FinalBitSize.roundToBytes());
126+
assert((Offset.getQuantity() + sizeof(T)) <= FinalBitSize.roundToBytes());
127+
return *reinterpret_cast<T *>(Data.get() + Offset.getQuantity());
128+
}
116129
};
117130

118131
} // namespace interp

clang/lib/AST/ByteCode/InterpBuiltin.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1997,8 +1997,8 @@ static bool interp__builtin_memcmp(InterpState &S, CodePtr OpPC,
19971997
for (size_t I = 0; I != CmpSize; I += ElemSize) {
19981998
if (IsWide) {
19991999
INT_TYPE_SWITCH(*S.getContext().classify(ASTCtx.getWCharType()), {
2000-
T A = *reinterpret_cast<T *>(BufferA.Data.get() + I);
2001-
T B = *reinterpret_cast<T *>(BufferB.Data.get() + I);
2000+
T A = *reinterpret_cast<T *>(BufferA.atByte(I));
2001+
T B = *reinterpret_cast<T *>(BufferB.atByte(I));
20022002
if (A < B) {
20032003
pushInteger(S, -1, Call->getType());
20042004
return true;
@@ -2009,8 +2009,8 @@ static bool interp__builtin_memcmp(InterpState &S, CodePtr OpPC,
20092009
}
20102010
});
20112011
} else {
2012-
std::byte A = BufferA.Data[I];
2013-
std::byte B = BufferB.Data[I];
2012+
std::byte A = BufferA.deref<std::byte>(Bytes(I));
2013+
std::byte B = BufferB.deref<std::byte>(Bytes(I));
20142014

20152015
if (A < B) {
20162016
pushInteger(S, -1, Call->getType());

0 commit comments

Comments
 (0)