[clang] [llvm] [Clang] Bit-pack _BitInt vectors and allow arbitrary _BitInt element widths (PR #248936)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Dec 4 06:58:17 PST 2026
https://github.com/gdaiteq created https://github.com/llvm/llvm-project/pull/248936
Fixes https://github.com/llvm/llvm-project/issues/248402
Previously, Clang laid out sub-byte `_BitInt(N)` vectors (`N < 8`) with per-element byte padding in AST layout while LLVM bit-packs `<K x iN>` vectors in memory and aggregates, causing layout/ABI mismatches, invalid constexpr `__builtin_bit_cast` results, and miscompiles. In addition, `vector_size` and `ext_vector_type` unnecessarily rejected non-power-of-2 `_BitInt(N)` element widths.
This stacked series fixes `#248402` and enables arbitrary bit-packed `_BitInt(N)` vectors in 3 commits:
1. **`[Clang][AST][CodeGen] Unify packed vector element width via getPackedVectorElementBits`** (NFC): Extracts `Type::getPackedVectorElementBits(const ASTContext &)` to share bit-packed vector layout, constexpr/`__builtin_bit_cast` (both evaluators), and DWARF sizing logic.
2. **`[Clang] Bit-pack sub-byte _BitInt vectors and fix codegen/ABI/constexpr`**: Bit-packs sub-byte / non-power-of-2 `_BitInt(N)` vectors into integer storage in AST layout, `CodeGen` (`ConvertTypeForMem`, `convertTypeForLoadStore`, `ConstantEmitter`, element/swizzle/coerced-return lowering), constexpr evaluators, target ABIs (x86-64, Windows x64, AArch64), and the `llvm/lib/ABI` library (`-fexperimental-abi-lowering`), and updates Sema/ABI tests and `clang/docs/ReleaseNotes.md`.
3. **`[Clang] Allow arbitrary non-power-of-2 _BitInt vector element widths`**: Lifts the power-of-2 restriction for `_BitInt(N)` elements in `vector_size` and `ext_vector_type` (while preserving it for `matrix_type`), updates `clang/docs/ReleaseNotes.md`, and adds Sema, constexpr (both evaluators), multi-target CodeGen, and DWARF DebugInfo tests.
>From dda71f78de6ee2d11039ad377752b813e6c006c0 Mon Sep 17 00:00:00 2001
From: Filip Chromy <filip at daiteq.com>
Date: Fri, 4 Dec 2026 15:46:23 +0100
Subject: [PATCH 1/3] [Clang][AST][CodeGen] Unify packed vector element width
via getPackedVectorElementBits
Introduce Type::getPackedVectorElementBits(const ASTContext &) returning the element bit-width for vectors whose elements are bit-packed in memory (1 for packed bool vectors, 0 otherwise) and adopt it in type layout computation, constexpr/__builtin_bit_cast (both evaluators), and DWARF debug info.
This is a non-functional cleanup in preparation for supporting bit-packed _BitInt vectors.
---
clang/include/clang/AST/TypeBase.h | 4 ++
clang/lib/AST/ASTContext.cpp | 8 ++-
.../lib/AST/ByteCode/InterpBuiltinBitCast.cpp | 39 +++++++------
clang/lib/AST/ExprConstant.cpp | 56 ++++++++-----------
clang/lib/AST/Type.cpp | 6 ++
clang/lib/CodeGen/CGDebugInfo.cpp | 11 ++--
6 files changed, 61 insertions(+), 63 deletions(-)
diff --git a/clang/include/clang/AST/TypeBase.h b/clang/include/clang/AST/TypeBase.h
index 7e8fbab357a4cf..044b6aaab5cf9c 100644
--- a/clang/include/clang/AST/TypeBase.h
+++ b/clang/include/clang/AST/TypeBase.h
@@ -2705,6 +2705,10 @@ class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
// Extended vector type with bool element that is packed. HLSL doesn't pack
// its bool vectors.
bool isPackedVectorBoolType(const ASTContext &ctx) const;
+ /// Returns the element bit-width if this vector stores elements bit-packed
+ /// without per-element byte padding (1 for packed bool vectors), or 0
+ /// otherwise.
+ unsigned getPackedVectorElementBits(const ASTContext &Ctx) const;
bool isSubscriptableVectorType() const;
bool isMatrixType() const; // Matrix type.
bool isConstantMatrixType() const; // Constant matrix type.
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 2da42f732b3afa..e99882ac9357ac 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -2139,9 +2139,11 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
case Type::Vector: {
const auto *VT = cast<VectorType>(T);
TypeInfo EltInfo = getTypeInfo(VT->getElementType());
- Width = VT->isPackedVectorBoolType(*this)
- ? VT->getNumElements()
- : EltInfo.Width * VT->getNumElements();
+ if (unsigned PackedEltBits = VT->getPackedVectorElementBits(*this))
+ Width = llvm::alignTo(
+ static_cast<uint64_t>(PackedEltBits) * VT->getNumElements(), 8);
+ else
+ Width = EltInfo.Width * VT->getNumElements();
// Enforce at least byte size and alignment.
Width = std::max<unsigned>(8, Width);
Align = std::max<unsigned>(
diff --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 32343e8d79b725..8001be1613e9d0 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -40,7 +40,7 @@ enum class Result { Success, Skip, Failure };
/// Used to iterate over pointer fields.
using DataFunc =
llvm::function_ref<Result(PtrView P, PrimType Ty, Bits BitOffset,
- Bits FullBitWidth, bool PackedBools)>;
+ Bits FullBitWidth, Bits PackedElemBits)>;
#define BITCAST_TYPE_SWITCH(Expr, B) \
do { \
@@ -132,8 +132,7 @@ static Result enumerateData(PtrView P, const Context &Ctx, Bits Offset,
if (FieldDesc->isPrimitive()) {
Bits FullBitWidth =
Bits(Ctx.getASTContext().getTypeSize(FieldDesc->getType()));
- return F(P, FieldDesc->getPrimType(), Offset, FullBitWidth,
- /*PackedBools=*/false);
+ return F(P, FieldDesc->getPrimType(), Offset, FullBitWidth, Bits::zero());
}
// Primitive arrays.
@@ -141,16 +140,17 @@ static Result enumerateData(PtrView P, const Context &Ctx, Bits Offset,
QualType ElemType = FieldDesc->getElemQualType();
Bits ElemSize = Bits(Ctx.getASTContext().getTypeSize(ElemType));
PrimType ElemT = *Ctx.classify(ElemType);
- // Special case, since the bools here are packed.
- bool PackedBools =
- FieldDesc->getType()->isPackedVectorBoolType(Ctx.getASTContext());
+ // Special case: packed bool vectors and bit-packed _BitInt vectors store
+ // elements at sub-byte bit offsets.
+ Bits PackedElemBits(
+ FieldDesc->getType()->getPackedVectorElementBits(Ctx.getASTContext()));
unsigned NumElems = FieldDesc->getNumElems();
bool Ok = true;
for (unsigned I = P.getIndex(); I != NumElems; ++I) {
- Result Res = F(P.atIndex(I), ElemT, Offset, ElemSize, PackedBools);
+ Result Res = F(P.atIndex(I), ElemT, Offset, ElemSize, PackedElemBits);
Ok = Ok && (Res == Result::Success);
- Offset += PackedBools ? Bits(1) : ElemSize;
+ Offset += PackedElemBits.nonZero() ? PackedElemBits : ElemSize;
if (Offset >= BitsToRead)
break;
}
@@ -315,8 +315,9 @@ static bool checkBitcastType(InterpState &S, CodePtr OpPC, QualType T,
const ASTContext &ASTCtx = S.getASTContext();
QualType EltTy = VT->getElementType();
unsigned NElts = VT->getNumElements();
+ unsigned PackedEltBits = VT->getPackedVectorElementBits(ASTCtx);
unsigned EltSize =
- VT->isPackedVectorBoolType(ASTCtx) ? 1 : ASTCtx.getTypeSize(EltTy);
+ PackedEltBits ? PackedEltBits : ASTCtx.getTypeSize(EltTy);
if ((NElts * EltSize) % ASTCtx.getCharWidth() != 0) {
// The vector's size in bits is not a multiple of the target's byte size,
@@ -355,14 +356,14 @@ bool clang::interp::readPointerToBuffer(const Context &Ctx,
return enumeratePointerFields(
FromPtr, Ctx, Buffer.size(),
[&](PtrView P, PrimType T, Bits BitOffset, Bits FullBitWidth,
- bool PackedBools) -> Result {
+ Bits PackedElemBits) -> Result {
Bits BitWidth = FullBitWidth;
if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
BitWidth = Bits(std::min(FD->getBitWidthValue(),
(unsigned)FullBitWidth.getQuantity()));
- else if (T == PT_Bool && PackedBools)
- BitWidth = Bits(1);
+ else if (PackedElemBits.nonZero())
+ BitWidth = PackedElemBits;
if (BitWidth.isZero())
return Result::Skip;
@@ -483,7 +484,7 @@ bool clang::interp::DoBitCastPtr(InterpState &S, CodePtr OpPC,
bool Success = enumeratePointerFields(
ToPtr, S.getContext(), Buffer.size(),
[&](PtrView P, PrimType T, Bits BitOffset, Bits FullBitWidth,
- bool PackedBools) -> Result {
+ Bits PackedElemBits) -> Result {
QualType PtrType = P.getType();
if (T == PT_Float) {
const auto &Semantics = ASTCtx.getFloatTypeSemantics(PtrType);
@@ -507,8 +508,8 @@ bool clang::interp::DoBitCastPtr(InterpState &S, CodePtr OpPC,
if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
BitWidth = Bits(std::min(FD->getBitWidthValue(),
(unsigned)FullBitWidth.getQuantity()));
- else if (T == PT_Bool && PackedBools)
- BitWidth = Bits(1);
+ else if (PackedElemBits.nonZero())
+ BitWidth = PackedElemBits;
else
BitWidth = FullBitWidth;
@@ -583,7 +584,6 @@ bool clang::interp::DoMemcpy(InterpState &S, CodePtr OpPC,
assert(DestPtr.isBlockPointer());
llvm::SmallVector<PrimTypeVariant> Values;
-
if (SrcPtr.isStringPointer()) {
const auto &SP = SrcPtr.asStringPointer();
@@ -591,7 +591,7 @@ bool clang::interp::DoMemcpy(InterpState &S, CodePtr OpPC,
enumeratePointerFields(
Pointer(B).atIndex(SrcPtr.getIndex()), S.getContext(), Size,
[&](const PtrView P, PrimType T, Bits BitOffset, Bits FullBitWidth,
- bool PackedBools) -> Result {
+ Bits PackedElemBits) -> Result {
TYPE_SWITCH(T, { Values.push_back(P.deref<T>()); });
return Result::Success;
},
@@ -599,11 +599,10 @@ bool clang::interp::DoMemcpy(InterpState &S, CodePtr OpPC,
delete[] B;
} else {
-
enumeratePointerFields(
SrcPtr, S.getContext(), Size,
[&](const PtrView P, PrimType T, Bits BitOffset, Bits FullBitWidth,
- bool PackedBools) -> Result {
+ Bits PackedElemBits) -> Result {
TYPE_SWITCH(T, { Values.push_back(P.deref<T>()); });
return Result::Success;
},
@@ -614,7 +613,7 @@ bool clang::interp::DoMemcpy(InterpState &S, CodePtr OpPC,
enumeratePointerFields(
DestPtr, S.getContext(), Size,
[&](const PtrView P, PrimType T, Bits BitOffset, Bits FullBitWidth,
- bool PackedBools) -> Result {
+ Bits PackedElemBits) -> Result {
TYPE_SWITCH(T, {
P.deref<T>() = std::get<T>(Values[ValueIndex]);
P.initialize();
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index b577676b177f73..ff44c52f9d9011 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8240,28 +8240,22 @@ class APValueToBufferConverter {
QualType EltTy = VTy->getElementType();
unsigned NElts = VTy->getNumElements();
- if (VTy->isPackedVectorBoolType(Info.Ctx)) {
- // Special handling for OpenCL bool vectors:
- // Since these vectors are stored as packed bits, but we can't write
- // individual bits to the BitCastBuffer, we'll buffer all of the elements
- // together into an appropriately sized APInt and write them all out at
- // once. Because we don't accept vectors where NElts * EltSize isn't a
- // multiple of the char size, there will be no padding space, so we don't
- // have to worry about writing data which should have been left
- // uninitialized.
+ if (unsigned EltBits = VTy->getPackedVectorElementBits(Info.Ctx)) {
+ // Packed bool and bit-packed _BitInt vectors store elements consecutively
+ // at bit offsets without per-element byte padding.
bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
+ unsigned TotalBits = NElts * EltBits;
+ unsigned TotalBytes = TotalBits / Info.Ctx.getCharWidth();
- llvm::APInt Res = llvm::APInt::getZero(NElts);
+ llvm::APInt Res = llvm::APInt::getZero(TotalBits);
for (unsigned I = 0; I < NElts; ++I) {
const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
- assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
- "bool vector element must be 1-bit unsigned integer!");
-
- Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
+ Res.insertBits(EltAsInt.zextOrTrunc(EltBits),
+ (BigEndian ? (NElts - I - 1) : I) * EltBits);
}
- SmallVector<uint8_t, 8> Bytes(NElts / 8);
- llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
+ SmallVector<uint8_t, 8> Bytes(TotalBytes);
+ llvm::StoreIntToMemory(Res, &*Bytes.begin(), TotalBytes);
Buffer.writeObject(Offset, Bytes);
} else {
// Iterate over each of the elements and write them out to the buffer at
@@ -8504,33 +8498,29 @@ class BufferToAPValueConverter {
std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
QualType EltTy = VTy->getElementType();
unsigned NElts = VTy->getNumElements();
+ unsigned PackedEltBits = VTy->getPackedVectorElementBits(Info.Ctx);
unsigned EltSize =
- VTy->isPackedVectorBoolType(Info.Ctx) ? 1 : Info.Ctx.getTypeSize(EltTy);
+ PackedEltBits ? PackedEltBits : Info.Ctx.getTypeSize(EltTy);
SmallVector<APValue, 4> Elts;
Elts.reserve(NElts);
- if (VTy->isPackedVectorBoolType(Info.Ctx)) {
- // Special handling for OpenCL bool vectors:
- // Since these vectors are stored as packed bits, but we can't read
- // individual bits from the BitCastBuffer, we'll buffer all of the
- // elements together into an appropriately sized APInt and write them all
- // out at once. Because we don't accept vectors where NElts * EltSize
- // isn't a multiple of the char size, there will be no padding space, so
- // we don't have to worry about reading any padding data which didn't
- // actually need to be accessed.
+ if (PackedEltBits) {
bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
+ unsigned TotalBits = NElts * EltSize;
+ unsigned TotalBytes = TotalBits / Info.Ctx.getCharWidth();
SmallVector<uint8_t, 8> Bytes;
- Bytes.reserve(NElts / 8);
- if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
+ Bytes.reserve(TotalBytes);
+ if (!Buffer.readObject(Offset, CharUnits::fromQuantity(TotalBytes),
+ Bytes))
return std::nullopt;
- APSInt SValInt(NElts, true);
+ APSInt SValInt(TotalBits, true);
llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
for (unsigned I = 0; I < NElts; ++I) {
- llvm::APInt Elt =
- SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
+ llvm::APInt Elt = SValInt.extractBits(
+ EltSize, (BigEndian ? NElts - I - 1 : I) * EltSize);
Elts.emplace_back(
APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
}
@@ -8638,8 +8628,8 @@ static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
if (const auto *VTy = Ty->getAs<VectorType>()) {
QualType EltTy = VTy->getElementType();
unsigned NElts = VTy->getNumElements();
- unsigned EltSize =
- VTy->isPackedVectorBoolType(Ctx) ? 1 : Ctx.getTypeSize(EltTy);
+ unsigned PackedEltBits = VTy->getPackedVectorElementBits(Ctx);
+ unsigned EltSize = PackedEltBits ? PackedEltBits : Ctx.getTypeSize(EltTy);
if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
// The vector's size in bits is not a multiple of the target's byte size,
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 4e4c4a37ecff71..cb83ad33624daf 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -545,6 +545,12 @@ bool Type::isPackedVectorBoolType(const ASTContext &ctx) const {
return isExtVectorBoolType();
}
+unsigned Type::getPackedVectorElementBits(const ASTContext &Ctx) const {
+ if (isPackedVectorBoolType(Ctx))
+ return 1;
+ return 0;
+}
+
BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
: Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
NumBits(NumBits) {}
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp
index 50f523c3318d77..4678f3a9c2819e 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3953,13 +3953,10 @@ llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
llvm::DIFile *Unit) {
- if (Ty->isPackedVectorBoolType(CGM.getContext())) {
- // Boolean ext_vector_type(N) are special because their real element type
- // (bits of bit size) is not their Clang element type (_Bool of size byte).
- // For now, we pretend the boolean vector were actually a vector of bytes
- // (where each byte represents 8 bits of the actual vector).
- // FIXME Debug info should actually represent this proper as a vector mask
- // type.
+ if (Ty->getPackedVectorElementBits(CGM.getContext())) {
+ // Packed bool and bit-packed _BitInt vectors store elements bit-packed in
+ // memory rather than padded to byte-addressable element sizes. Emit a
+ // byte vector matching the packed storage bit-width.
auto &Ctx = CGM.getContext();
uint64_t Size = CGM.getContext().getTypeSize(Ty);
uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
>From 02ace5f2ef61ebb1a32df501c28aefe25b6c35a6 Mon Sep 17 00:00:00 2001
From: Filip Chromy <filip at daiteq.com>
Date: Fri, 4 Dec 2026 15:46:21 +0100
Subject: [PATCH 2/3] [Clang] Bit-pack sub-byte _BitInt vectors and fix
codegen/ABI/constexpr
Clang previously laid out sub-byte _BitInt(N) vectors (e.g. _BitInt(2), _BitInt(4)) as byte-padded elements in AST layout while LLVM bit-packs <K x iN> vectors in memory and aggregates, causing layout/ABI mismatches and miscompiles (#GH248402).
Store sub-byte and non-power-of-2 _BitInt(N) vectors bit-packed via integer memory types:
- AST: Add Type::isPackedBitIntVectorType() and implement getPackedVectorElementBits(); handle both little-endian and big-endian occupied bit intervals in PaddingClearer::VisitBitIntStorage.
- Sema: Compute bit-packed vector sizes for vector_size, reject vectors whose padded integer representation exceeds IntegerType::MAX_INT_BITS, and handle packed/unsigned _BitInt(1) vector comparison result types in GetSignedVectorType.
- Constexpr / __builtin_bit_cast: Reject bit-packed vectors with trailing padding in both evaluators, fix sub-byte AP integer serialization in IntegralAP, and size DoBitCastPtr allocations to PackedElemBits.
- CodeGen & ABI: Map bit-packed _BitInt vectors in ConvertTypeForMem / convertTypeForLoadStore / ConstantEmitter::emitForMemory, lower element/swizzle/rvalue accesses via BaseVecType on LValue, use a memory temp on coerced return values, and coerce/pass them properly on x86-64, Windows x64, and AArch64.
- LLVM ABI Library: Keep llvm::abi::Type::getABISizeInBits(), AArch64, and X86_64 target classification in lockstep with Clang for bit-packed _BitInt vectors.
- Docs & Tests: Update ReleaseNotes, ABI unit tests, and existing Sema/CodeGen IR tests.
---
clang/docs/ReleaseNotes.md | 6 +
clang/include/clang/AST/TypeBase.h | 5 +-
clang/lib/AST/ASTContext.cpp | 26 +++-
clang/lib/AST/ByteCode/IntegralAP.h | 6 +-
.../lib/AST/ByteCode/InterpBuiltinBitCast.cpp | 25 ++-
clang/lib/AST/ExprConstant.cpp | 10 +-
clang/lib/AST/Type.cpp | 12 ++
clang/lib/CodeGen/CGAtomic.cpp | 18 ++-
clang/lib/CodeGen/CGExpr.cpp | 146 ++++++++++++++----
clang/lib/CodeGen/CGExprConstant.cpp | 30 ++++
clang/lib/CodeGen/CGStmt.cpp | 11 +-
clang/lib/CodeGen/CGValue.h | 10 +-
clang/lib/CodeGen/CodeGenFunction.cpp | 9 +-
clang/lib/CodeGen/CodeGenTypes.cpp | 31 ++--
clang/lib/CodeGen/Targets/AArch64.cpp | 6 +-
clang/lib/CodeGen/Targets/X86.cpp | 25 ++-
clang/lib/Sema/SemaExpr.cpp | 12 ++
clang/lib/Sema/SemaType.cpp | 38 +++--
.../CodeGen/AArch64/abi-classify-arg-types.c | 14 +-
clang/test/CodeGen/X86/x86_64-abi-size.c | 12 +-
.../test/CodeGen/X86/x86_64-vector-abi-size.c | 16 +-
clang/test/CodeGenCXX/ext-int.cpp | 35 +++--
.../test/CodeGenCXX/matrix-vector-bit-int.cpp | 44 +++---
clang/test/Sema/ext-int.c | 6 +-
clang/test/SemaCXX/ext-int-vector.cpp | 8 +-
llvm/include/llvm/ABI/Types.h | 21 ++-
llvm/lib/ABI/Targets/AArch64.cpp | 12 +-
llvm/lib/ABI/Targets/X86.cpp | 23 ++-
llvm/lib/ABI/Types.cpp | 4 +-
llvm/unittests/ABI/AArch64TargetInfoTest.cpp | 12 +-
llvm/unittests/ABI/TypesTest.cpp | 9 +-
llvm/unittests/ABI/X86TargetInfoTest.cpp | 48 +++---
32 files changed, 478 insertions(+), 212 deletions(-)
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 5a92a4e888f39a..f4f1f20dd5e79b 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -228,6 +228,12 @@ features cannot lower the translation-unit ABI level;
a wrong `this` pointer. The mangled names of the affected thunks change.
(#GH205392)
+- Sub-byte `_BitInt(N)` vectors (`N < 8`) are now stored bit-packed in
+ memory (matching their LLVM IR vector representation without per-element
+ byte padding) and follow the corresponding integer/coerced ABI rules on
+ x86-64, Windows x64, and AArch64. Previously, AST layout treated elements
+ as byte-padded while LLVM bit-packed `<K x iN>` vectors. (#GH248402)
+
### AST Dumping Potentially Breaking Changes
- The AST printer (`-ast-print`) now prints a floating-point literal as the
diff --git a/clang/include/clang/AST/TypeBase.h b/clang/include/clang/AST/TypeBase.h
index 044b6aaab5cf9c..8b5903794dd563 100644
--- a/clang/include/clang/AST/TypeBase.h
+++ b/clang/include/clang/AST/TypeBase.h
@@ -2705,9 +2705,10 @@ class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase {
// Extended vector type with bool element that is packed. HLSL doesn't pack
// its bool vectors.
bool isPackedVectorBoolType(const ASTContext &ctx) const;
+ bool isPackedBitIntVectorType() const;
/// Returns the element bit-width if this vector stores elements bit-packed
- /// without per-element byte padding (1 for packed bool vectors), or 0
- /// otherwise.
+ /// without per-element byte padding (1 for packed bool vectors, or BitInt
+ /// width for sub-byte / non-power-of-2 _BitInt vectors), or 0 otherwise.
unsigned getPackedVectorElementBits(const ASTContext &Ctx) const;
bool isSubscriptableVectorType() const;
bool isMatrixType() const; // Matrix type.
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index e99882ac9357ac..c60b362d95d4b0 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -16207,6 +16207,14 @@ struct PaddingCalculator {
VisitPackedBooleanVector(VT, StartBitOffset);
return;
}
+ if (VT->isPackedBitIntVectorType()) {
+ uint64_t OccupiedBits =
+ static_cast<uint64_t>(
+ VT->getElementType()->castAs<BitIntType>()->getNumBits()) *
+ VT->getNumElements();
+ VisitBitIntStorage(OccupiedBits, Ctx.getTypeSize(VT), StartBitOffset);
+ return;
+ }
uint64_t SizeBit = getScalarOccupiedSizeInBits(VT->getElementType()) *
VT->getNumElements();
@@ -16214,27 +16222,27 @@ struct PaddingCalculator {
ASTContext::BitInterval{StartBitOffset, StartBitOffset + SizeBit});
}
- /// Compute the occupied bit intervals for a BitInt.
+ /// Compute the occupied bit intervals for integer storage padded up to a
+ /// power-of-2 / target-aligned storage width (used by BitInt and bit-packed
+ /// _BitInt vectors).
///
/// In the case of little endian, the occupied bits are always contiguous so a
/// single interval is sufficient. However in big endian, the intervals can be
/// disjoint.
- void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
- const uint64_t OccupiedSizeInBits = Ty->getNumBits();
-
+ void VisitBitIntStorage(uint64_t OccupiedSizeInBits,
+ uint64_t StorageSizeInBits, uint64_t StartBitOffset) {
if (Ctx.getTargetInfo().isLittleEndian()) {
OccuppiedIntervals.push_back(
{StartBitOffset, StartBitOffset + OccupiedSizeInBits});
return;
}
- // In big endian mode, the layout of a BitInt in memory has its bytes in
- // reverse order, and is pictured in this order:
+ // In big endian mode, the layout of integer-packed storage has its bytes
+ // in reverse order, and is pictured in this order:
// 1. Fully padding bytes.
// 2. One partially occupied byte, with padding at the most significant
// bits. ("remaining occupied bits")
// 3. A sequence of fully occupied bytes up until the end of the storage.
- const uint64_t StorageSizeInBits = Ctx.getTypeSize(Ty);
const uint64_t CharWidth = Ctx.getCharWidth();
const uint64_t NumFullyPaddingBytes =
(StorageSizeInBits - OccupiedSizeInBits) / CharWidth;
@@ -16255,6 +16263,10 @@ struct PaddingCalculator {
StartBitOffset + StorageSizeInBits});
}
+ void VisitBitInt(const BitIntType *Ty, uint64_t StartBitOffset) {
+ VisitBitIntStorage(Ty->getNumBits(), Ctx.getTypeSize(Ty), StartBitOffset);
+ }
+
void VisitPackedBooleanVector(const VectorType *VTy,
uint64_t StartBitOffset) {
const uint64_t CharWidth = Ctx.getCharWidth();
diff --git a/clang/lib/AST/ByteCode/IntegralAP.h b/clang/lib/AST/ByteCode/IntegralAP.h
index 056c9024a6ff68..d3b53d9869226a 100644
--- a/clang/lib/AST/ByteCode/IntegralAP.h
+++ b/clang/lib/AST/ByteCode/IntegralAP.h
@@ -201,13 +201,15 @@ template <bool Signed> class IntegralAP final {
}
void bitcastToMemory(std::byte *Dest) const {
- llvm::StoreIntToMemory(getValue(), (uint8_t *)Dest, bitWidth() / 8);
+ llvm::StoreIntToMemory(getValue(), (uint8_t *)Dest,
+ llvm::divideCeil(bitWidth(), 8));
}
static void bitcastFromMemory(const std::byte *Src, unsigned BitWidth,
IntegralAP *Result) {
APInt V(BitWidth, static_cast<uint64_t>(0), Signed);
- llvm::LoadIntFromMemory(V, (const uint8_t *)Src, BitWidth / 8);
+ llvm::LoadIntFromMemory(V, (const uint8_t *)Src,
+ llvm::divideCeil(BitWidth, 8));
Result->copy(V);
}
diff --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 8001be1613e9d0..dbd55b97ade3d7 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -319,11 +319,11 @@ static bool checkBitcastType(InterpState &S, CodePtr OpPC, QualType T,
unsigned EltSize =
PackedEltBits ? PackedEltBits : ASTCtx.getTypeSize(EltTy);
- if ((NElts * EltSize) % ASTCtx.getCharWidth() != 0) {
- // The vector's size in bits is not a multiple of the target's byte size,
- // so its layout is unspecified. For now, we'll simply treat these cases
- // as unsupported (this should only be possible with OpenCL bool vectors
- // whose element count isn't a multiple of the byte size).
+ if ((NElts * EltSize) % ASTCtx.getCharWidth() != 0 ||
+ (PackedEltBits && static_cast<uint64_t>(NElts) * EltSize !=
+ ASTCtx.getTypeSize(QualType(VT, 0)))) {
+ // The vector's size in bits is not a multiple of the target's byte size
+ // or has trailing padding, so its layout is unsupported.
S.FFDiag(S.Current->getSource(OpPC),
diag::note_constexpr_bit_cast_invalid_vector)
<< QualType(VT, 0) << EltSize << NElts << ASTCtx.getCharWidth();
@@ -535,17 +535,16 @@ bool clang::interp::DoBitCastPtr(InterpState &S, CodePtr OpPC,
if (llvm::sys::IsBigEndianHost)
swapBytes(Memory.get(), FullBitWidth.roundToBytes());
+ unsigned APBits = PackedElemBits.nonZero()
+ ? PackedElemBits.getQuantity()
+ : FullBitWidth.getQuantity();
if (T == PT_IntAPS) {
- P.deref<IntegralAP<true>>() =
- S.allocAP<IntegralAP<true>>(FullBitWidth.getQuantity());
- IntegralAP<true>::bitcastFromMemory(Memory.get(),
- FullBitWidth.getQuantity(),
+ P.deref<IntegralAP<true>>() = S.allocAP<IntegralAP<true>>(APBits);
+ IntegralAP<true>::bitcastFromMemory(Memory.get(), APBits,
&P.deref<IntegralAP<true>>());
} else if (T == PT_IntAP) {
- P.deref<IntegralAP<false>>() =
- S.allocAP<IntegralAP<false>>(FullBitWidth.getQuantity());
- IntegralAP<false>::bitcastFromMemory(Memory.get(),
- FullBitWidth.getQuantity(),
+ P.deref<IntegralAP<false>>() = S.allocAP<IntegralAP<false>>(APBits);
+ IntegralAP<false>::bitcastFromMemory(Memory.get(), APBits,
&P.deref<IntegralAP<false>>());
} else {
BITCAST_TYPE_SWITCH_FIXED_SIZE(T, {
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index ff44c52f9d9011..c199d3c4ec7f37 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8631,11 +8631,11 @@ static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
unsigned PackedEltBits = VTy->getPackedVectorElementBits(Ctx);
unsigned EltSize = PackedEltBits ? PackedEltBits : Ctx.getTypeSize(EltTy);
- if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
- // The vector's size in bits is not a multiple of the target's byte size,
- // so its layout is unspecified. For now, we'll simply treat these cases
- // as unsupported (this should only be possible with OpenCL bool vectors
- // whose element count isn't a multiple of the byte size).
+ if ((NElts * EltSize) % Ctx.getCharWidth() != 0 ||
+ (PackedEltBits && static_cast<uint64_t>(NElts) * EltSize !=
+ Ctx.getTypeSize(QualType(VTy, 0)))) {
+ // The vector's bit size does not match a dense multiple of char width
+ // without padding, so bit_cast layout is rejected.
if (Info)
Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
<< QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index cb83ad33624daf..da84e23f39f325 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -545,9 +545,21 @@ bool Type::isPackedVectorBoolType(const ASTContext &ctx) const {
return isExtVectorBoolType();
}
+bool Type::isPackedBitIntVectorType() const {
+ if (const auto *VT = getAs<VectorType>())
+ if (const auto *BIT = VT->getElementType()->getAs<BitIntType>())
+ return !llvm::isPowerOf2_32(BIT->getNumBits()) || BIT->getNumBits() < 8;
+ return false;
+}
+
unsigned Type::getPackedVectorElementBits(const ASTContext &Ctx) const {
if (isPackedVectorBoolType(Ctx))
return 1;
+ if (isPackedBitIntVectorType())
+ return castAs<VectorType>()
+ ->getElementType()
+ ->castAs<BitIntType>()
+ ->getNumBits();
return 0;
}
diff --git a/clang/lib/CodeGen/CGAtomic.cpp b/clang/lib/CodeGen/CGAtomic.cpp
index cd7b278eab15d9..edcaa9558ca0e1 100644
--- a/clang/lib/CodeGen/CGAtomic.cpp
+++ b/clang/lib/CodeGen/CGAtomic.cpp
@@ -1562,8 +1562,8 @@ RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
LVal.getBaseInfo(), TBAAAccessInfo()), loc);
assert(LVal.isExtVectorElt());
return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
- addr, LVal.getExtVectorElts(), LVal.getType(),
- LVal.getBaseInfo(), TBAAAccessInfo()));
+ addr, LVal.getExtVectorElts(), LVal.getType(), LVal.getBaseInfo(),
+ TBAAAccessInfo(), LVal.getExtVectorBaseType()));
}
RValue AtomicInfo::ConvertToValueOrAtomic(llvm::Value *Val,
@@ -1896,13 +1896,14 @@ EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
} else {
assert(AtomicLVal.isExtVectorElt());
- UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
- AtomicLVal.getType(),
- AtomicLVal.getBaseInfo(),
- AtomicLVal.getTBAAInfo());
+ UpdateLVal = LValue::MakeExtVectorElt(
+ Ptr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
+ AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo(),
+ AtomicLVal.getExtVectorBaseType());
DesiredLVal = LValue::MakeExtVectorElt(
DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
- AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
+ AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo(),
+ AtomicLVal.getExtVectorBaseType());
}
UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
}
@@ -2002,7 +2003,8 @@ static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
assert(AtomicLVal.isExtVectorElt());
DesiredLVal = LValue::MakeExtVectorElt(
DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
- AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
+ AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo(),
+ AtomicLVal.getExtVectorBaseType());
}
// Store new value in the corresponding memory area.
assert(UpdateRVal.isScalar());
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ee6283dbfa5f98..110e8974eeb4e7 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -2207,19 +2207,22 @@ llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
}
// Handles vectors of sizes that are likely to be expanded to a larger size
- // to optimize performance.
- auto *VTy = cast<llvm::FixedVectorType>(Addr.getElementType());
- auto *NewVecTy =
- CGM.getABIInfo().getOptimalVectorMemoryType(VTy, getLangOpts());
-
- if (VTy != NewVecTy) {
- Address Cast = Addr.withElementType(NewVecTy);
- llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVecN");
- unsigned OldNumElements = VTy->getNumElements();
- SmallVector<int, 16> Mask(OldNumElements);
- std::iota(Mask.begin(), Mask.end(), 0);
- V = Builder.CreateShuffleVector(V, Mask, "extractVec");
- return EmitFromMemory(V, Ty);
+ // to optimize performance (bit-packed _BitInt vectors use integer storage
+ // via convertTypeForLoadStore/EmitFromMemory below).
+ if (!ClangVecTy->isPackedBitIntVectorType()) {
+ auto *VTy = cast<llvm::FixedVectorType>(Addr.getElementType());
+ auto *NewVecTy =
+ CGM.getABIInfo().getOptimalVectorMemoryType(VTy, getLangOpts());
+
+ if (VTy != NewVecTy) {
+ Address Cast = Addr.withElementType(NewVecTy);
+ llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVecN");
+ unsigned OldNumElements = VTy->getNumElements();
+ SmallVector<int, 16> Mask(OldNumElements);
+ std::iota(Mask.begin(), Mask.end(), 0);
+ V = Builder.CreateShuffleVector(V, Mask, "extractVec");
+ return EmitFromMemory(V, Ty);
+ }
}
}
@@ -2272,6 +2275,19 @@ llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
Value = Builder.CreateBitCast(Value, StoreTy);
}
+ if (Ty->isPackedBitIntVectorType()) {
+ llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
+ if (Value->getType() == StoreTy)
+ return Value;
+ auto *VecTy = cast<llvm::FixedVectorType>(Value->getType());
+ unsigned TotalBits = VecTy->getNumElements() * VecTy->getScalarSizeInBits();
+ llvm::Value *IntV = Builder.CreateBitCast(
+ Value, llvm::IntegerType::get(getLLVMContext(), TotalBits));
+ if (StoreTy->getPrimitiveSizeInBits() != TotalBits)
+ IntV = Builder.CreateZExt(IntV, StoreTy);
+ return IntV;
+ }
+
if (Ty->hasBooleanRepresentation() || Ty->isBitIntType()) {
llvm::Type *StoreTy = convertTypeForLoadStore(Ty, Value->getType());
bool Signed = Ty->isSignedIntegerOrEnumerationType();
@@ -2301,6 +2317,18 @@ llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
return emitBoolVecConversion(V, ValNumElems, "extractvec");
}
+ if (Ty->isPackedBitIntVectorType()) {
+ auto *VecTy = cast<llvm::FixedVectorType>(ConvertType(Ty));
+ if (Value->getType() == VecTy)
+ return Value;
+ unsigned TotalBits = VecTy->getNumElements() * VecTy->getScalarSizeInBits();
+ llvm::Value *IntV = Value;
+ if (IntV->getType()->getPrimitiveSizeInBits() != TotalBits)
+ IntV = Builder.CreateTrunc(
+ IntV, llvm::IntegerType::get(getLLVMContext(), TotalBits));
+ return Builder.CreateBitCast(IntV, VecTy);
+ }
+
llvm::Type *ResTy = ConvertType(Ty);
bool HasBoolRep = Ty->hasBooleanRepresentation() ||
Ty->isExtVectorBoolType() || Ty->isConstantMatrixBoolType();
@@ -2440,7 +2468,11 @@ void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
// to optimize performance.
llvm::Type *SrcTy = Value->getType();
if (const auto *ClangVecTy = Ty->getAs<VectorType>()) {
- if (auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
+ if (ClangVecTy->isPackedBitIntVectorType()) {
+ llvm::Type *StoreTy = convertTypeForLoadStore(Ty, SrcTy);
+ if (Addr.getElementType() != StoreTy)
+ Addr = Addr.withElementType(StoreTy);
+ } else if (auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
auto *NewVecTy =
CGM.getABIInfo().getOptimalVectorMemoryType(VecTy, getLangOpts());
if (!ClangVecTy->isPackedVectorBoolType(getContext()) &&
@@ -2577,6 +2609,14 @@ RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
}
if (LV.isVectorElt()) {
+ if (LV.getType()->isPackedBitIntVectorType()) {
+ llvm::Value *Vec = EmitLoadOfScalar(
+ LV.getVectorAddress(), LV.isVolatileQualified(), LV.getType(), Loc,
+ LV.getBaseInfo(), LV.getTBAAInfo());
+ llvm::Value *Elt =
+ Builder.CreateExtractElement(Vec, LV.getVectorIdx(), "vecext");
+ return RValue::get(Elt);
+ }
llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
LV.isVolatileQualified());
llvm::Value *Elt =
@@ -2691,8 +2731,14 @@ RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
// If this is a reference to a subset of the elements of a vector, create an
// appropriate shufflevector.
RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
- llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
- LV.isVolatileQualified());
+ QualType BaseVecTy = LV.getExtVectorBaseType();
+ llvm::Value *Vec =
+ (!BaseVecTy.isNull() && BaseVecTy->isPackedBitIntVectorType())
+ ? EmitLoadOfScalar(LV.getExtVectorAddress(), LV.isVolatileQualified(),
+ BaseVecTy, SourceLocation(), LV.getBaseInfo(),
+ LV.getTBAAInfo())
+ : Builder.CreateLoad(LV.getExtVectorAddress(),
+ LV.isVolatileQualified());
// HLSL allows treating scalars as one-element vectors. Converting the scalar
// IR value to a vector here allows the rest of codegen to behave as normal.
@@ -2820,6 +2866,18 @@ void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
return;
}
+ if (Dst.getType()->isPackedBitIntVectorType()) {
+ llvm::Value *Vec = EmitLoadOfScalar(
+ Dst.getVectorAddress(), Dst.isVolatileQualified(), Dst.getType(),
+ SourceLocation(), Dst.getBaseInfo(), Dst.getTBAAInfo());
+ Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
+ Dst.getVectorIdx(), "vecins");
+ EmitStoreOfScalar(Vec, Dst.getVectorAddress(),
+ Dst.isVolatileQualified(), Dst.getType(),
+ Dst.getBaseInfo(), Dst.getTBAAInfo(), isInit);
+ return;
+ }
+
// Read/modify/write the vector, inserting the new element.
llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
Dst.isVolatileQualified());
@@ -3135,8 +3193,11 @@ void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
llvm::Value *SrcVal = Src.getScalarVal();
Address DstAddr = Dst.getExtVectorAddress();
const llvm::Constant *Elts = Dst.getExtVectorElts();
- if (DstAddr.getElementType()->getScalarSizeInBits() >
- SrcVal->getType()->getScalarSizeInBits())
+ QualType BaseVecTy = Dst.getExtVectorBaseType();
+ bool IsPackedBitIntVec =
+ !BaseVecTy.isNull() && BaseVecTy->isPackedBitIntVectorType();
+ if (!IsPackedBitIntVec && DstAddr.getElementType()->getScalarSizeInBits() >
+ SrcVal->getType()->getScalarSizeInBits())
SrcVal = Builder.CreateZExt(
SrcVal, convertTypeForLoadStore(Dst.getType(), SrcVal->getType()));
@@ -3182,7 +3243,12 @@ void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
// This access turns into a read/modify/write of the vector. Load the input
// value now.
- llvm::Value *Vec = Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
+ llvm::Value *Vec =
+ IsPackedBitIntVec
+ ? EmitLoadOfScalar(DstAddr, Dst.isVolatileQualified(), BaseVecTy,
+ SourceLocation(), Dst.getBaseInfo(),
+ Dst.getTBAAInfo())
+ : Builder.CreateLoad(DstAddr, Dst.isVolatileQualified());
llvm::Type *VecTy = Vec->getType();
if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
@@ -3235,8 +3301,11 @@ void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
}
- Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
- Dst.isVolatileQualified());
+ if (IsPackedBitIntVec)
+ EmitStoreOfScalar(Vec, DstAddr, Dst.isVolatileQualified(), BaseVecTy,
+ Dst.getBaseInfo(), Dst.getTBAAInfo());
+ else
+ Builder.CreateStore(Vec, DstAddr, Dst.isVolatileQualified());
}
/// Store of global named registers are always calls to intrinsics.
@@ -5226,6 +5295,23 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
if (isa<ExtVectorElementExpr>(E->getBase())) {
LValue LV = EmitLValue(E->getBase());
auto *Idx = EmitIdxAfterBase(/*Promote*/true);
+ if (LV.getType()->isPackedBitIntVectorType()) {
+ unsigned NumElts = LV.getType()->castAs<VectorType>()->getNumElements();
+ llvm::Value *MappedIdx;
+ if (auto *CI = dyn_cast<llvm::ConstantInt>(Idx);
+ CI && CI->getValue().ult(NumElts))
+ MappedIdx = llvm::ConstantInt::get(
+ Idx->getType(),
+ getAccessedFieldNo(CI->getZExtValue(), LV.getExtVectorElts()));
+ else
+ MappedIdx = Builder.CreateExtractElement(LV.getExtVectorElts(), Idx,
+ "vec.swizzle.idx");
+ QualType BaseVecTy = LV.getExtVectorBaseType().withCVRQualifiers(
+ LV.getQuals().getCVRQualifiers());
+ return LValue::MakeVectorElt(LV.getExtVectorAddress(), MappedIdx,
+ BaseVecTy, LV.getBaseInfo(),
+ TBAAAccessInfo());
+ }
Address Addr = EmitExtVectorElementLValue(LV);
QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
@@ -5704,10 +5790,14 @@ EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Address VecMem = CreateMemTemp(E->getBase()->getType());
// need to zero extend an hlsl boolean vector to store it back to memory
QualType Ty = E->getBase()->getType();
- llvm::Type *LTy = convertTypeForLoadStore(Ty, Vec->getType());
- if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
- Vec = Builder.CreateZExt(Vec, LTy);
- Builder.CreateStore(Vec, VecMem);
+ if (Ty->isPackedBitIntVectorType()) {
+ EmitStoreOfScalar(Vec, VecMem, /*Volatile=*/false, Ty);
+ } else {
+ llvm::Type *LTy = convertTypeForLoadStore(Ty, Vec->getType());
+ if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
+ Vec = Builder.CreateZExt(Vec, LTy);
+ Builder.CreateStore(Vec, VecMem);
+ }
Base = MakeAddrLValue(VecMem, Ty, AlignmentSource::Decl);
}
@@ -5722,7 +5812,8 @@ EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
llvm::Constant *CV =
llvm::ConstantDataVector::get(getLLVMContext(), Indices);
return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
- Base.getBaseInfo(), TBAAAccessInfo());
+ Base.getBaseInfo(), TBAAAccessInfo(),
+ Base.getType());
}
if (Base.isMatrixRow()) {
@@ -5770,7 +5861,8 @@ EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
CElts.push_back(BaseElts->getAggregateElement(Index));
llvm::Constant *CV = llvm::ConstantVector::get(CElts);
return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
- Base.getBaseInfo(), TBAAAccessInfo());
+ Base.getBaseInfo(), TBAAAccessInfo(),
+ Base.getExtVectorBaseType());
}
bool CodeGenFunction::isUnderlyingBasePointerConstantNull(const Expr *E) {
diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp
index 5aab1dfd6ac0c4..9a2bdf4bbcdf42 100644
--- a/clang/lib/CodeGen/CGExprConstant.cpp
+++ b/clang/lib/CodeGen/CGExprConstant.cpp
@@ -2109,6 +2109,36 @@ llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
return MemoryValue;
}
+ if (destType->isPackedBitIntVectorType()) {
+ llvm::Type *MemTy = CGM.getTypes().ConvertTypeForMem(destType);
+ if (C->getType() != MemTy) {
+ llvm::Type *LoadStoreTy =
+ CGM.getTypes().convertTypeForLoadStore(destType);
+ auto *VecTy = cast<llvm::FixedVectorType>(C->getType());
+ unsigned TotalBits =
+ VecTy->getNumElements() * VecTy->getScalarSizeInBits();
+ llvm::Type *IntTy =
+ llvm::IntegerType::get(CGM.getLLVMContext(), TotalBits);
+ llvm::Constant *Res = llvm::ConstantFoldCastOperand(
+ llvm::Instruction::BitCast, C, IntTy, CGM.getDataLayout());
+ if (Res && LoadStoreTy != IntTy)
+ Res = llvm::ConstantFoldCastOperand(llvm::Instruction::ZExt, Res,
+ LoadStoreTy, CGM.getDataLayout());
+ assert(Res && "Constant folding must succeed");
+ if (isa<llvm::ArrayType>(MemTy)) {
+ if (isa<llvm::PoisonValue>(Res))
+ return llvm::PoisonValue::get(MemTy);
+ if (isa<llvm::UndefValue>(Res))
+ return llvm::UndefValue::get(MemTy);
+ ConstantAggregateBuilder Builder(CGM);
+ llvm::APInt Value = cast<llvm::ConstantInt>(Res)->getValue();
+ Builder.addBits(Value, /*OffsetInBits=*/0, /*AllowOverwrite=*/false);
+ return Builder.build(MemTy, /*AllowOversized*/ false);
+ }
+ return Res;
+ }
+ }
+
return C;
}
diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index 6b791c0b35e2e5..21be1e30a385c2 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -1531,7 +1531,12 @@ void CodeGenFunction::EmitCXXExpansionStmtInstantiation(
void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) {
if (RV.isScalar()) {
- Builder.CreateStore(RV.getScalarVal(), ReturnValue);
+ if (Ty->isPackedBitIntVectorType() &&
+ ReturnValue.getElementType() != RV.getScalarVal()->getType())
+ EmitStoreOfScalar(RV.getScalarVal(), MakeAddrLValue(ReturnValue, Ty),
+ /*isInit*/ true);
+ else
+ Builder.CreateStore(RV.getScalarVal(), ReturnValue);
} else if (RV.isAggregate()) {
LValue Dest = MakeAddrLValue(ReturnValue, Ty);
LValue Src = MakeAddrLValue(RV.getAggregateAddress(), Ty);
@@ -1666,7 +1671,9 @@ void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
switch (getEvaluationKind(RV->getType())) {
case TEK_Scalar: {
llvm::Value *Ret = EmitScalarExpr(RV);
- if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) {
+ if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect ||
+ (RV->getType()->isPackedBitIntVectorType() &&
+ ReturnValue.getElementType() != Ret->getType())) {
EmitStoreOfScalar(Ret, MakeAddrLValue(ReturnValue, RV->getType()),
/*isInit*/ true);
} else {
diff --git a/clang/lib/CodeGen/CGValue.h b/clang/lib/CodeGen/CGValue.h
index ea1bffd16abcf3..17ca889d33e5f8 100644
--- a/clang/lib/CodeGen/CGValue.h
+++ b/clang/lib/CodeGen/CGValue.h
@@ -214,6 +214,7 @@ class LValue {
llvm::Constant *MatrixRowElts = nullptr;
QualType Type;
+ QualType BaseVecType;
// 'const' is unused here
Qualifiers Quals;
@@ -251,6 +252,7 @@ class LValue {
void Initialize(QualType Type, Qualifiers Quals, Address Addr,
LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo) {
this->Type = Type;
+ this->BaseVecType = QualType();
this->Quals = Quals;
const unsigned MaxAlign = 1U << 31;
CharUnits Alignment = Addr.getAlignment();
@@ -432,6 +434,10 @@ class LValue {
assert(isExtVectorElt());
return VectorElts;
}
+ QualType getExtVectorBaseType() const {
+ assert(isExtVectorElt());
+ return BaseVecType;
+ }
// bitfield lvalue
Address getBitFieldAddress() const {
@@ -473,11 +479,13 @@ class LValue {
static LValue MakeExtVectorElt(Address Addr, llvm::Constant *Elts,
QualType type, LValueBaseInfo BaseInfo,
- TBAAAccessInfo TBAAInfo) {
+ TBAAAccessInfo TBAAInfo,
+ QualType baseVecType = QualType()) {
LValue R;
R.LVType = ExtVectorElt;
R.VectorElts = Elts;
R.Initialize(type, type.getQualifiers(), Addr, BaseInfo, TBAAInfo);
+ R.BaseVecType = baseVecType;
return R;
}
diff --git a/clang/lib/CodeGen/CodeGenFunction.cpp b/clang/lib/CodeGen/CodeGenFunction.cpp
index 0db2d0d06f569c..f778ff69f4c76c 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1290,7 +1290,14 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
ReturnValue = Address(Addr, ConvertType(RetTy),
CGM.getNaturalTypeAlignment(RetTy), KnownNonNull);
} else {
- ReturnValue = CreateIRTempWithoutCast(RetTy, "retval");
+ const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo();
+ if (RetTy->isPackedBitIntVectorType() &&
+ (!RetAI.canHaveCoerceToType() ||
+ RetAI.getCoerceToType() != ConvertType(RetTy) ||
+ RetAI.getDirectOffset() != 0))
+ ReturnValue = CreateMemTemp(RetTy, "retval");
+ else
+ ReturnValue = CreateIRTempWithoutCast(RetTy, "retval");
// Tell the epilog emitter to autorelease the result. We do this
// now so that various specialized functions can suppress it
diff --git a/clang/lib/CodeGen/CodeGenTypes.cpp b/clang/lib/CodeGen/CodeGenTypes.cpp
index 6103fad1c87c2c..24e96ea47af69d 100644
--- a/clang/lib/CodeGen/CodeGenTypes.cpp
+++ b/clang/lib/CodeGen/CodeGenTypes.cpp
@@ -157,25 +157,20 @@ llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
return llvm::IntegerType::get(FixedVT->getContext(), BytePadded);
}
- // If T is _Bool or a _BitInt type, ConvertType will produce an IR type
- // with the exact semantic bit-width of the AST type; for example,
- // _BitInt(17) will turn into i17. In memory, however, we need to store
- // such values extended to their full storage size as decided by AST
- // layout; this is an ABI requirement. Ideally, we would always use an
- // integer type that's just the bit-size of the AST type; for example, if
- // sizeof(_BitInt(17)) == 4, _BitInt(17) would turn into i32. That is what's
- // returned by convertTypeForLoadStore. However, that type does not
- // always satisfy the size requirement on memory representation types
- // describe above. For example, a 32-bit platform might reasonably set
- // sizeof(_BitInt(65)) == 12, but i96 is likely to have to have an alloc size
- // of 16 bytes in the LLVM data layout. In these cases, we simply return
- // a byte array of the appropriate size.
- if (T->isBitIntType()) {
- if (typeRequiresSplitIntoByteArray(T, R))
+ // If T is _Bool, a _BitInt type, or a bit-packed _BitInt vector,
+ // ConvertType produces an IR type with the exact semantic bit-width (e.g.,
+ // _BitInt(17) -> i17, or <10 x i3>). In memory, we store values extended to
+ // their full storage size as decided by AST layout; if the LLVM alloc size
+ // differs from the AST storage size (e.g., i96 with alloc size 16 bytes vs
+ // 12 bytes in AST layout), use a byte array instead.
+ if (T->isBitIntType() || T->isPackedBitIntVectorType()) {
+ llvm::Type *IntTy = llvm::IntegerType::get(
+ getLLVMContext(), (unsigned)Context.getTypeSize(T));
+ llvm::Type *CheckTy = T->isBitIntType() ? R : IntTy;
+ if (typeRequiresSplitIntoByteArray(T, CheckTy))
return llvm::ArrayType::get(CGM.Int8Ty,
Context.getTypeSizeInChars(T).getQuantity());
- return llvm::IntegerType::get(getLLVMContext(),
- (unsigned)Context.getTypeSize(T));
+ return IntTy;
}
if (R->isIntegerTy(1))
@@ -202,7 +197,7 @@ llvm::Type *CodeGenTypes::convertTypeForLoadStore(QualType T,
if (!LLVMTy)
LLVMTy = ConvertType(T);
- if (T->isBitIntType())
+ if (T->isBitIntType() || T->isPackedBitIntVectorType())
return llvm::Type::getIntNTy(
getLLVMContext(), Context.getTypeSizeInChars(T).getQuantity() * 8);
diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp b/clang/lib/CodeGen/Targets/AArch64.cpp
index e493f717af581d..c35e1ebc2b5bdc 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -559,7 +559,8 @@ ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
if (const auto *VT = RetTy->getAs<VectorType>()) {
if (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
- VT->getVectorKind() == VectorKind::SveFixedLengthPredicate) {
+ VT->getVectorKind() == VectorKind::SveFixedLengthPredicate ||
+ VT->isPackedBitIntVectorType()) {
unsigned NSRN = 0, NPRN = 0;
return coerceIllegalVector(RetTy, NSRN, NPRN);
}
@@ -646,7 +647,8 @@ bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
// represented as scalable vectors in function args/return and must be
// coerced from fixed vectors.
if (VT->getVectorKind() == VectorKind::SveFixedLengthData ||
- VT->getVectorKind() == VectorKind::SveFixedLengthPredicate)
+ VT->getVectorKind() == VectorKind::SveFixedLengthPredicate ||
+ VT->isPackedBitIntVectorType())
return true;
// Check whether VT is legal.
diff --git a/clang/lib/CodeGen/Targets/X86.cpp b/clang/lib/CodeGen/Targets/X86.cpp
index 01788d55eb29d4..104e9ae50ad52a 100644
--- a/clang/lib/CodeGen/Targets/X86.cpp
+++ b/clang/lib/CodeGen/Targets/X86.cpp
@@ -2418,7 +2418,7 @@ ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
if (const auto *ED = Ty->getAsEnumDecl())
Ty = ED->getIntegerType();
- if (Ty->isBitIntType())
+ if (Ty->isBitIntType() || Ty->isPackedBitIntVectorType())
return getNaturalAlignIndirect(Ty, getDataLayout().getAllocaAddrSpace());
llvm::Type *IRTy = CGT.ConvertType(Ty);
@@ -2431,6 +2431,8 @@ ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
+ if (VecTy->isPackedBitIntVectorType())
+ return true;
uint64_t Size = getContext().getTypeSize(VecTy);
unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
if (Size <= 64 || Size > LargestVector)
@@ -2519,10 +2521,11 @@ llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
llvm::Type *IRType = CGT.ConvertType(Ty);
if (isa<llvm::VectorType>(IRType)) {
- // Don't pass vXi128 vectors in their native type, the backend can't
- // legalize them.
- if (passInt128VectorsInMem() &&
- cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) {
+ // Don't pass vXi128 vectors or packed _BitInt vectors in their native type,
+ // the backend can't legalize or pass sub-byte packed elements cleanly.
+ if ((passInt128VectorsInMem() &&
+ cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) ||
+ Ty->isPackedBitIntVectorType()) {
// Use a vXi64 vector.
uint64_t Size = getContext().getTypeSize(Ty);
return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()),
@@ -3752,6 +3755,18 @@ ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
}
}
+ if (Ty->isPackedBitIntVectorType()) {
+ if (Width <= 64 && llvm::isPowerOf2_64(Width))
+ return ABIArgInfo::getDirect(
+ llvm::IntegerType::get(getVMContext(), Width));
+ if (Width == 128 || Width == 256 || Width == 512)
+ return ABIArgInfo::getDirect(llvm::FixedVectorType::get(
+ llvm::Type::getInt64Ty(getVMContext()), Width / 64));
+ return ABIArgInfo::getIndirect(
+ Align, /*AddrSpace=*/getDataLayout().getAllocaAddrSpace(),
+ /*ByVal=*/false);
+ }
+
if (Ty->isBitIntType()) {
// MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
// not 1, 2, 4, or 8 bytes, must be passed by reference."
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 699aa30bb915d0..10170312881c6d 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -13828,6 +13828,18 @@ QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
QualType Sema::GetSignedVectorType(QualType V) {
const VectorType *VTy = V->castAs<VectorType>();
+ if (VTy->isPackedBitIntVectorType()) {
+ const auto *BIT = VTy->getElementType()->castAs<BitIntType>();
+ // Signed _BitInt(1) is invalid, so fall back to bool/signed char.
+ QualType SignedElt =
+ BIT->getNumBits() == 1
+ ? (isa<ExtVectorType>(VTy) ? Context.BoolTy : Context.SignedCharTy)
+ : Context.getBitIntType(/*IsUnsigned=*/false, BIT->getNumBits());
+ if (isa<ExtVectorType>(VTy))
+ return Context.getExtVectorType(SignedElt, VTy->getNumElements());
+ return Context.getVectorType(SignedElt, VTy->getNumElements(),
+ VectorKind::Generic);
+ }
unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
if (isa<ExtVectorType>(VTy)) {
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 908bd2d8b406c8..1c86cad6ace8eb 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -2421,14 +2421,26 @@ QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM,
static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc,
const BitIntType *BIT,
bool ForMatrixType = false) {
- // Only support _BitInt elements with byte-sized power of 2 NumBits.
- unsigned NumBits = BIT->getNumBits();
- if (!llvm::isPowerOf2_32(NumBits))
+ if (!llvm::isPowerOf2_32(BIT->getNumBits()))
return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
<< ForMatrixType;
return false;
}
+static bool isPackedBitIntVectorTooLarge(QualType EltTy, uint64_t NumElts) {
+ const auto *BIT = EltTy->getAs<BitIntType>();
+ if (!BIT)
+ return false;
+ unsigned NumBits = BIT->getNumBits();
+ if (llvm::isPowerOf2_32(NumBits) && NumBits >= 8)
+ return false;
+ if (NumElts > llvm::IntegerType::MAX_INT_BITS / NumBits)
+ return true;
+ uint64_t PaddedBits = llvm::bit_ceil(
+ std::max<uint64_t>(8, llvm::alignTo(NumElts * NumBits, 8)));
+ return PaddedBits > llvm::IntegerType::MAX_INT_BITS;
+}
+
// A bool vector is stored as an integer with one bit per element and can be
// formed from any vector (e.g. by the conditional operator); the size bound
// keeps the natural alignment within TypeInfo::Align.
@@ -2481,7 +2493,9 @@ QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
return QualType();
}
uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
- unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
+ unsigned TypeSize = CurType->isBitIntType()
+ ? CurType->castAs<BitIntType>()->getNumBits()
+ : static_cast<unsigned>(Context.getTypeSize(CurType));
if (VectorSizeBits == 0) {
Diag(AttrLoc, diag::err_attribute_zero_size)
@@ -2495,14 +2509,15 @@ QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
return QualType();
}
- if (VectorSizeBits / TypeSize > MaxVectorElements) {
+ uint64_t NumElements = VectorSizeBits / TypeSize;
+ if (NumElements > MaxVectorElements ||
+ isPackedBitIntVectorTooLarge(CurType, NumElements)) {
Diag(AttrLoc, diag::err_attribute_size_too_large)
<< SizeExpr->getSourceRange() << "vector";
return QualType();
}
- return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
- VectorKind::Generic);
+ return Context.getVectorType(CurType, NumElements, VectorKind::Generic);
}
QualType Sema::BuildExtVectorType(QualType T, Expr *SizeExpr,
@@ -2559,7 +2574,8 @@ QualType Sema::BuildExtVectorType(QualType T, Expr *SizeExpr,
}
if (!T->isDependentType() &&
- VectorSize * Context.getTypeSize(T) > MaxVectorSizeInBits) {
+ (VectorSize * Context.getTypeSize(T) > MaxVectorSizeInBits ||
+ isPackedBitIntVectorTooLarge(T, VectorSize))) {
Diag(AttrLoc, diag::err_attribute_size_too_large)
<< SizeExpr->getSourceRange() << "vector";
return QualType();
@@ -2584,9 +2600,11 @@ QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
}
if (const auto *BIT = ElementTy->getAs<BitIntType>();
- BIT &&
- CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
+ BIT && !llvm::isPowerOf2_32(BIT->getNumBits())) {
+ Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
+ << /*ForMatrixType=*/true;
return QualType();
+ }
if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
NumRows->isValueDependent() || NumCols->isValueDependent())
diff --git a/clang/test/CodeGen/AArch64/abi-classify-arg-types.c b/clang/test/CodeGen/AArch64/abi-classify-arg-types.c
index 55e4b2a807997a..104c77c0a9bc7c 100644
--- a/clang/test/CodeGen/AArch64/abi-classify-arg-types.c
+++ b/clang/test/CodeGen/AArch64/abi-classify-arg-types.c
@@ -325,21 +325,23 @@ typedef char v9i8 __attribute__((vector_size(9)));
void arg_v9i8(v9i8 v) {}
// CHECK: define{{.*}} void @arg_v9i8(<4 x i32> %{{.*}})
-// A _BitInt occupies a whole number of bytes, so a sub-byte element counts as
-// 8 bits towards the size of the vector. That makes 8 x _BitInt(2) a legal
-// 64-bit vector rather than an illegal 16-bit one.
+// Sub-byte _BitInt vectors are bit-packed and treated as illegal vectors on
+// AArch64, so 4 x _BitInt(2) (8 bits), 8 x _BitInt(2) (16 bits), and
+// 16 x _BitInt(4) (64 bits) are coerced to integer / 2 x i32 types.
typedef _BitInt(2) b2v4 __attribute__((ext_vector_type(4)));
void arg_b2v4(b2v4 v) {}
-// CHECK: define{{.*}} void @arg_b2v4(i32 %{{.*}})
+// NOANDROID: define{{.*}} void @arg_b2v4(i32 %{{.*}})
+// ANDROID: define{{.*}} void @arg_b2v4(i16 %{{.*}})
typedef _BitInt(2) b2v8 __attribute__((ext_vector_type(8)));
void arg_b2v8(b2v8 v) {}
-// CHECK: define{{.*}} void @arg_b2v8(<8 x i2> noundef %{{.*}})
+// NOANDROID: define{{.*}} void @arg_b2v8(i32 %{{.*}})
+// ANDROID: define{{.*}} void @arg_b2v8(i16 noundef %{{.*}})
typedef _BitInt(4) b4v16 __attribute__((ext_vector_type(16)));
void arg_b4v16(b4v16 v) {}
-// CHECK: define{{.*}} void @arg_b4v16(<16 x i4> noundef %{{.*}})
+// CHECK: define{{.*}} void @arg_b4v16(<2 x i32> noundef %{{.*}})
typedef _BitInt(32) b32v2 __attribute__((ext_vector_type(2)));
void arg_b32v2(b32v2 v) {}
diff --git a/clang/test/CodeGen/X86/x86_64-abi-size.c b/clang/test/CodeGen/X86/x86_64-abi-size.c
index 2b44c1be48dfa2..867e1e85bc9c7a 100644
--- a/clang/test/CodeGen/X86/x86_64-abi-size.c
+++ b/clang/test/CodeGen/X86/x86_64-abi-size.c
@@ -176,19 +176,19 @@ struct LongB12 { long l; b12 v; };
struct LongB12 longb12(struct LongB12 s) { return s; }
// CHECK: define dso_local { i64, i64 } @longb12(i64 %{{.*}}, i64 %{{.*}})
-// A one-bit _BitInt element is not a bool, so it takes a byte.
+// A one-bit _BitInt vector is bit-packed to at least one byte.
ub1x4 vub1x4(ub1x4 v) { return v; }
-// CHECK: define dso_local i32 @vub1x4(i32 %{{.*}})
+// CHECK: define dso_local i8 @vub1x4(i8 noundef %{{.*}})
-// A one-bit _BitInt, char or float vector is not a bool vector, so the
-// eightbyte holding it stays an i64.
+// A bit-packed sub-byte _BitInt vector narrows the eightbyte holding it, while
+// a char or float vector stays an i64.
struct LongUB1x4 { long l; ub1x4 v; };
struct LongUB1x4 longub1x4(struct LongUB1x4 s) { return s; }
-// CHECK: define dso_local { i64, i64 } @longub1x4(i64 %{{.*}}, i64 %{{.*}})
+// CHECK: define dso_local { i64, i8 } @longub1x4(i64 %{{.*}}, i8 %{{.*}})
struct LongUB1x1 { long l; ub1x1 v; };
struct LongUB1x1 longub1x1(struct LongUB1x1 s) { return s; }
-// CHECK: define dso_local { i64, i64 } @longub1x1(i64 %{{.*}}, i64 %{{.*}})
+// CHECK: define dso_local { i64, i8 } @longub1x1(i64 %{{.*}}, i8 %{{.*}})
struct LongC1 { long l; c1 v; };
struct LongC1 longc1(struct LongC1 s) { return s; }
diff --git a/clang/test/CodeGen/X86/x86_64-vector-abi-size.c b/clang/test/CodeGen/X86/x86_64-vector-abi-size.c
index a38513dfb70431..dd68f7d2c41239 100644
--- a/clang/test/CodeGen/X86/x86_64-vector-abi-size.c
+++ b/clang/test/CodeGen/X86/x86_64-vector-abi-size.c
@@ -107,11 +107,11 @@ struct SBI3 sbi3(struct SBI3 s) { return s; }
// NOAVX512: define{{.*}} void @sbi3(ptr dead_on_unwind noalias writable sret(%struct.SBI3) align 64 %{{.*}}, ptr noundef byval(%struct.SBI3) align 64 %{{.*}})
// AVX512: define{{.*}} <8 x i64> @sbi3(<8 x i64> %{{.*}})
-// Each two-element vector of 4-bit _BitInt takes 2 bytes, so the fifth reaches
-// the second eightbyte.
+// Each two-element vector of 4-bit _BitInt takes 1 byte, so five elements fit
+// in 5 bytes.
struct AB { bi4x2 a[5]; };
struct AB ab(struct AB s) { return s; }
-// CHECK: define{{.*}} { i64, i16 } @ab(i64 %{{.*}}, i16 %{{.*}})
+// CHECK: define{{.*}} i40 @ab(i40 %{{.*}})
// Padding past the vector keeps these from being passed as the vector alone.
union __attribute__((aligned(32))) UA32 { ld1 v; };
@@ -139,15 +139,15 @@ b17 vb17(b17 v) { return v; }
void stkb(long a, long b, long c, long d, long e, long f, b4 v) {}
// CHECK: define{{.*}} void @stkb(i64 noundef %{{.*}}, i64 noundef %{{.*}}, i64 noundef %{{.*}}, i64 noundef %{{.*}}, i64 noundef %{{.*}}, i64 noundef %{{.*}}, i8 noundef %{{.*}})
-// Each 4-bit _BitInt element takes a byte.
+// Two 4-bit _BitInt elements are bit-packed into one byte.
bi4x2 vbi4x2(bi4x2 v) { return v; }
-// CHECK: define{{.*}} i16 @vbi4x2(i16 %{{.*}})
+// CHECK: define{{.*}} i8 @vbi4x2(i8 noundef %{{.*}})
-// Sixteen 4-bit _BitInt elements take 16 bytes, so once the SSE registers run
-// out the vector is still passed directly.
+// Sixteen 4-bit _BitInt elements are bit-packed into 8 bytes (an illegal
+// vector type), so once the SSE registers run out it is passed byval.
void exhaust(double a, double b, double c, double d, double e, double f,
double g, double h, bi4x16 v) {}
-// CHECK: define{{.*}} void @exhaust(double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, <16 x i4> noundef %{{.*}})
+// CHECK: define{{.*}} void @exhaust(double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, double noundef %{{.*}}, ptr noundef byval(i64) align 8 %{{.*}})
// Once the SSE registers run out, a vector of _BitInt(128) is still passed
// directly, while a vector of __int128 is passed in memory.
diff --git a/clang/test/CodeGenCXX/ext-int.cpp b/clang/test/CodeGenCXX/ext-int.cpp
index d08788d111e9e8..938504fbfe4cf2 100644
--- a/clang/test/CodeGenCXX/ext-int.cpp
+++ b/clang/test/CodeGenCXX/ext-int.cpp
@@ -585,9 +585,9 @@ void VectorTest(uint16_t4 first, uint16_t4 second) {
typedef unsigned _BitInt(4) uint4_t4 __attribute__((ext_vector_type(4)));
void VectorTest(uint4_t4 first, uint4_t4 second) {
- // LIN64: define{{.*}} void @_Z10VectorTestDv4_DU4_S0_(i32 %{{.+}}, i32 %{{.+}})
+ // LIN64: define{{.*}} void @_Z10VectorTestDv4_DU4_S0_(i16 %{{.+}}, i16 %{{.+}})
// LIN32: define{{.*}} void @_Z10VectorTestDv4_DU4_S0_(<4 x i4> %{{.+}}, <4 x i4> %{{.+}})
- // WIN64: define dso_local void @"?VectorTest@@YAXT?$__vector at U?$_UBitInt@$03 at __clang@@$03 at __clang@@0 at Z"(<4 x i4> %{{.+}}, <4 x i4> %{{.+}})
+ // WIN64: define dso_local void @"?VectorTest@@YAXT?$__vector at U?$_UBitInt@$03 at __clang@@$03 at __clang@@0 at Z"(i16 %{{.+}}, i16 %{{.+}})
// WIN32: define dso_local void @"?VectorTest@@YAXT?$__vector at U?$_UBitInt@$03 at __clang@@$03 at __clang@@0 at Z"(<4 x i4> inreg %{{.+}}, <4 x i4> inreg %{{.+}})
first.xzw + second.zwx;
// CHECK: %[[Shuffle:.+]] = shufflevector <4 x i4> %{{.+}}, <4 x i4> poison, <3 x i32> <i32 0, i32 2, i32 3>
@@ -597,24 +597,27 @@ void VectorTest(uint4_t4 first, uint4_t4 second) {
typedef unsigned _BitInt(2) uint2_t2 __attribute__((ext_vector_type(2)));
uint2_t2 TestBitIntVector2x2Alloca(uint2_t2 v1, uint2_t2 v2) {
- // LIN64: define dso_local i16 @_Z25TestBitIntVector2x2AllocaDv2_DU2_S0_(i16 %[[V1Coerce:.+]], i16 %[[V2Coerce:.+]])
- // LIN64: %[[RetVal:.+]] = alloca <2 x i2>, align 2
- // LIN64: %[[V1Addr:.+]] = alloca <2 x i2>, align 2
- // LIN64: %[[V2Addr:.+]] = alloca <2 x i2>, align 2
- // LIN64: %[[RetValCoerce:.+]] = alloca i16, align 2
- // LIN64: call void @llvm.memcpy.p0.p0.i64(ptr align 2 %[[RetValCoerce]], ptr align 2 %[[RetVal]], i64 1, i1 false)
- // LIN64: %[[Ret:.+]] = load i16, ptr %[[RetValCoerce]], align 2
- // LIN64: ret i16 %[[Ret]]
+ // LIN64: define dso_local i8 @_Z25TestBitIntVector2x2AllocaDv2_DU2_S0_(i8 %[[V1Coerce:.+]], i8 %[[V2Coerce:.+]])
+ // LIN64: %[[RetVal:.+]] = alloca i8, align 1
+ // LIN64: %[[V1Addr:.+]] = alloca i8, align 1
+ // LIN64: %[[V2Addr:.+]] = alloca i8, align 1
+ // LIN64: %[[Ret:.+]] = load i8, ptr %[[RetVal]], align 1
+ // LIN64: ret i8 %[[Ret]]
// LIN32: define dso_local <2 x i2> @_Z25TestBitIntVector2x2AllocaDv2_DU2_S0_(<2 x i2> %{{.+}}, <2 x i2> %{{.+}})
- // LIN32: %[[V1Addr:.+]] = alloca <2 x i2>, align 2
- // LIN32: %[[V2Addr:.+]] = alloca <2 x i2>, align 2
+ // LIN32: %[[V1Addr:.+]] = alloca i8, align 1
+ // LIN32: %[[V2Addr:.+]] = alloca i8, align 1
// LIN32: ret <2 x i2> %[[Ret:.+]]
- // WIN: define dso_local <2 x i2> @"?TestBitIntVector2x2Alloca@@YAT?$__vector at U?$_UBitInt@$01 at __clang@@$01 at __clang@@T12 at 0@Z"(<2 x i2>{{.*}}, <2 x i2>{{.*}})
- // WIN: %[[V1:.+]] = alloca <2 x i2>, align 2
- // WIN: %[[V2:.+]] = alloca <2 x i2>, align 2
- // WIN: ret <2 x i2> %[[Ret:.+]]
+ // WIN64: define dso_local i8 @"?TestBitIntVector2x2Alloca@@YAT?$__vector at U?$_UBitInt@$01 at __clang@@$01 at __clang@@T12 at 0@Z"(i8 %{{.+}}, i8 %{{.+}})
+ // WIN64: %[[V1:.+]] = alloca i8, align 1
+ // WIN64: %[[V2:.+]] = alloca i8, align 1
+ // WIN64: ret i8 %[[Ret:.+]]
+
+ // WIN32: define dso_local <2 x i2> @"?TestBitIntVector2x2Alloca@@YAT?$__vector at U?$_UBitInt@$01 at __clang@@$01 at __clang@@T12 at 0@Z"(<2 x i2>{{.*}}, <2 x i2>{{.*}})
+ // WIN32: %[[V1:.+]] = alloca i8, align 1
+ // WIN32: %[[V2:.+]] = alloca i8, align 1
+ // WIN32: ret <2 x i2> %[[Ret:.+]]
return v1 + v2;
}
diff --git a/clang/test/CodeGenCXX/matrix-vector-bit-int.cpp b/clang/test/CodeGenCXX/matrix-vector-bit-int.cpp
index 4be1cb3067c2fc..ac5960e24d022c 100644
--- a/clang/test/CodeGenCXX/matrix-vector-bit-int.cpp
+++ b/clang/test/CodeGenCXX/matrix-vector-bit-int.cpp
@@ -70,27 +70,31 @@ i512x3 v3(i512x3 a) {
return a + a;
}
-// CHECK-LABEL: define dso_local i32 @_Z2v4Dv3_DB4_(
-// CHECK-SAME: i32 [[A_COERCE:%.*]]) #[[ATTR0]] {
+// CHECK-LABEL: define dso_local noundef i16 @_Z2v4Dv3_DB4_(
+// CHECK-SAME: i16 noundef [[A_COERCE:%.*]]) #[[ATTR0]] {
// CHECK-NEXT: [[ENTRY:.*:]]
-// CHECK-NEXT: [[RETVAL:%.*]] = alloca <3 x i4>, align 4
-// CHECK-NEXT: [[A:%.*]] = alloca <3 x i4>, align 4
-// CHECK-NEXT: [[A_ADDR:%.*]] = alloca <3 x i4>, align 4
-// CHECK-NEXT: [[RETVAL_COERCE:%.*]] = alloca i32, align 4
-// CHECK-NEXT: store i32 [[A_COERCE]], ptr [[A]], align 4
-// CHECK-NEXT: [[LOADVECN:%.*]] = load <4 x i4>, ptr [[A]], align 4
-// CHECK-NEXT: [[A1:%.*]] = shufflevector <4 x i4> [[LOADVECN]], <4 x i4> poison, <3 x i32> <i32 0, i32 1, i32 2>
-// CHECK-NEXT: [[EXTRACTVEC:%.*]] = shufflevector <3 x i4> [[A1]], <3 x i4> undef, <4 x i32> <i32 0, i32 1, i32 2, i32 3>
-// CHECK-NEXT: store <4 x i4> [[EXTRACTVEC]], ptr [[A_ADDR]], align 4
-// CHECK-NEXT: [[LOADVECN2:%.*]] = load <4 x i4>, ptr [[A_ADDR]], align 4
-// CHECK-NEXT: [[EXTRACTVEC3:%.*]] = shufflevector <4 x i4> [[LOADVECN2]], <4 x i4> poison, <3 x i32> <i32 0, i32 1, i32 2>
-// CHECK-NEXT: [[LOADVECN4:%.*]] = load <4 x i4>, ptr [[A_ADDR]], align 4
-// CHECK-NEXT: [[EXTRACTVEC5:%.*]] = shufflevector <4 x i4> [[LOADVECN4]], <4 x i4> poison, <3 x i32> <i32 0, i32 1, i32 2>
-// CHECK-NEXT: [[ADD:%.*]] = add <3 x i4> [[EXTRACTVEC3]], [[EXTRACTVEC5]]
-// CHECK-NEXT: store <3 x i4> [[ADD]], ptr [[RETVAL]], align 4
-// CHECK-NEXT: call void @llvm.memcpy.p0.p0.i64(ptr align 4 [[RETVAL_COERCE]], ptr align 4 [[RETVAL]], i64 2, i1 false)
-// CHECK-NEXT: [[TMP0:%.*]] = load i32, ptr [[RETVAL_COERCE]], align 4
-// CHECK-NEXT: ret i32 [[TMP0]]
+// CHECK-NEXT: [[RETVAL:%.*]] = alloca i16, align 2
+// CHECK-NEXT: [[A:%.*]] = alloca i16, align 2
+// CHECK-NEXT: [[A_ADDR:%.*]] = alloca i16, align 2
+// CHECK-NEXT: store i16 [[A_COERCE]], ptr [[A]], align 2
+// CHECK-NEXT: [[TMP0:%.*]] = load i16, ptr [[A]], align 2
+// CHECK-NEXT: [[TMP1:%.*]] = trunc i16 [[TMP0]] to i12
+// CHECK-NEXT: [[A1:%.*]] = bitcast i12 [[TMP1]] to <3 x i4>
+// CHECK-NEXT: [[TMP2:%.*]] = bitcast <3 x i4> [[A1]] to i12
+// CHECK-NEXT: [[TMP3:%.*]] = zext i12 [[TMP2]] to i16
+// CHECK-NEXT: store i16 [[TMP3]], ptr [[A_ADDR]], align 2
+// CHECK-NEXT: [[TMP4:%.*]] = load i16, ptr [[A_ADDR]], align 2
+// CHECK-NEXT: [[TMP5:%.*]] = trunc i16 [[TMP4]] to i12
+// CHECK-NEXT: [[TMP6:%.*]] = bitcast i12 [[TMP5]] to <3 x i4>
+// CHECK-NEXT: [[TMP7:%.*]] = load i16, ptr [[A_ADDR]], align 2
+// CHECK-NEXT: [[TMP8:%.*]] = trunc i16 [[TMP7]] to i12
+// CHECK-NEXT: [[TMP9:%.*]] = bitcast i12 [[TMP8]] to <3 x i4>
+// CHECK-NEXT: [[ADD:%.*]] = add <3 x i4> [[TMP6]], [[TMP9]]
+// CHECK-NEXT: [[TMP10:%.*]] = bitcast <3 x i4> [[ADD]] to i12
+// CHECK-NEXT: [[TMP11:%.*]] = zext i12 [[TMP10]] to i16
+// CHECK-NEXT: store i16 [[TMP11]], ptr [[RETVAL]], align 2
+// CHECK-NEXT: [[TMP12:%.*]] = load i16, ptr [[RETVAL]], align 2
+// CHECK-NEXT: ret i16 [[TMP12]]
//
i4x3 v4(i4x3 a) {
return a + a;
diff --git a/clang/test/Sema/ext-int.c b/clang/test/Sema/ext-int.c
index 3e61d784b885ee..c6e24ec3fc4762 100644
--- a/clang/test/Sema/ext-int.c
+++ b/clang/test/Sema/ext-int.c
@@ -109,7 +109,7 @@ void GH200665(ExtVec4x4 e4a, ExtVec4x4 e4b, ExtVec8x4 e8a, ExtVec8x4 e8b,
GnuVec8x4 g8a, GnuVec8x4 g8b, GnuVec64x4 g64a, GnuVec64x4 g64b,
GnuVec256x2 g256a, GnuVec256x2 g256b, GnuVec1024x2 g1024a,
GnuVec1024x2 g1024b, GnuUVec256x2 gu256a, GnuUVec256x2 gu256b) {
- _Static_assert(EXPR_HAS_TYPE(e4a == e4b, CharExt4), "");
+ _Static_assert(EXPR_HAS_TYPE(e4a == e4b, ExtVec4x4), "");
_Static_assert(EXPR_HAS_TYPE(e8a != e8b, CharExt4), "");
_Static_assert(EXPR_HAS_TYPE(e32a < e32b, IntExt4), "");
_Static_assert(EXPR_HAS_TYPE(e128a <= e128b, Int128Ext4), "");
@@ -119,11 +119,11 @@ void GH200665(ExtVec4x4 e4a, ExtVec4x4 e4b, ExtVec8x4 e8a, ExtVec8x4 e8b,
_Static_assert(EXPR_HAS_TYPE(0 == e1024a, ExtVec1024x2), "");
_Static_assert(EXPR_HAS_TYPE(e1024a != e1024b, ExtVec1024x2), "");
_Static_assert(EXPR_HAS_TYPE(eu512a == eu512b, ExtVec512x3), "");
- _Static_assert(EXPR_HAS_TYPE(!e4a, CharExt4), "");
+ _Static_assert(EXPR_HAS_TYPE(!e4a, ExtVec4x4), "");
_Static_assert(EXPR_HAS_TYPE(!e512a, ExtVec512x3), "");
_Static_assert(EXPR_HAS_TYPE(!eu512a, ExtVec512x3), "");
_Static_assert(EXPR_HAS_TYPE(e512a && e512b, ExtVec512x3), "");
- _Static_assert(EXPR_HAS_TYPE(e4a || e4b, CharExt4), "");
+ _Static_assert(EXPR_HAS_TYPE(e4a || e4b, ExtVec4x4), "");
_Static_assert(EXPR_HAS_TYPE(e512a ? e512a : e512b, ExtVec512x3), "");
_Static_assert(EXPR_HAS_TYPE((e512a > 0) ? e512a : e512b, ExtVec512x3), "");
_Static_assert(EXPR_HAS_TYPE((eu512a == eu512b) ? eu512a : eu512b, ExtUVec512x3), "");
diff --git a/clang/test/SemaCXX/ext-int-vector.cpp b/clang/test/SemaCXX/ext-int-vector.cpp
index 4e7fc1ea677019..756ad219feea9f 100644
--- a/clang/test/SemaCXX/ext-int-vector.cpp
+++ b/clang/test/SemaCXX/ext-int-vector.cpp
@@ -71,8 +71,8 @@ template <typename V, typename R> void check_int(V a, V b) {
static_assert(__is_same(decltype(a ? a : b), V), "");
}
-template void check_int<ExtVec2x4, CharExt4>(ExtVec2x4, ExtVec2x4);
-template void check_int<ExtVec4x4, CharExt4>(ExtVec4x4, ExtVec4x4);
+template void check_int<ExtVec2x4, ExtVec2x4>(ExtVec2x4, ExtVec2x4);
+template void check_int<ExtVec4x4, ExtVec4x4>(ExtVec4x4, ExtVec4x4);
template void check_int<ExtVec8x4, CharExt4>(ExtVec8x4, ExtVec8x4);
template void check_int<ExtVec16x4, ShortExt4>(ExtVec16x4, ExtVec16x4);
template void check_int<ExtVec32x4, IntExt4>(ExtVec32x4, ExtVec32x4);
@@ -81,7 +81,7 @@ template void check_int<ExtVec128x4, Int128Ext4>(ExtVec128x4, ExtVec128x4);
template void check_int<ExtVec256x2, ExtVec256x2>(ExtVec256x2, ExtVec256x2);
template void check_int<ExtVec512x3, ExtVec512x3>(ExtVec512x3, ExtVec512x3);
template void check_int<ExtVec1024x2, ExtVec1024x2>(ExtVec1024x2, ExtVec1024x2);
-template void check_int<ExtUVec4x4, CharExt4>(ExtUVec4x4, ExtUVec4x4);
+template void check_int<ExtUVec4x4, ExtVec4x4>(ExtUVec4x4, ExtUVec4x4);
template void check_int<ExtUVec128x4, Int128Ext4>(ExtUVec128x4, ExtUVec128x4);
template void check_int<ExtUVec512x3, ExtVec512x3>(ExtUVec512x3, ExtUVec512x3);
template void check_int<UInt128Ext4, Int128Ext4>(UInt128Ext4, UInt128Ext4);
@@ -91,7 +91,7 @@ template void check<FloatExt4, IntExt4>(FloatExt4, FloatExt4);
template void check<DoubleExt4, LongExt4>(DoubleExt4, DoubleExt4);
template void check<LongDoubleExt4, Int128Ext4>(LongDoubleExt4, LongDoubleExt4);
-template void check_int<GnuVec4x2, CharGnu2>(GnuVec4x2, GnuVec4x2);
+template void check_int<GnuVec4x2, GnuVec4x2>(GnuVec4x2, GnuVec4x2);
template void check_int<GnuVec8x4, CharGnu4>(GnuVec8x4, GnuVec8x4);
template void check_int<GnuVec16x4, ShortGnu4>(GnuVec16x4, GnuVec16x4);
template void check_int<GnuVec32x4, IntGnu4>(GnuVec32x4, GnuVec32x4);
diff --git a/llvm/include/llvm/ABI/Types.h b/llvm/include/llvm/ABI/Types.h
index 4db733e7fff3c9..1f3f4620ddb749 100644
--- a/llvm/include/llvm/ABI/Types.h
+++ b/llvm/include/llvm/ABI/Types.h
@@ -21,6 +21,7 @@
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
+#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TypeSize.h"
namespace llvm {
@@ -88,10 +89,10 @@ class Type {
/// type is rounded up further, to its alignment. That alignment must be the
/// one its size is padded to, not one an aligned attribute raised or lowered.
/// A complex type is twice the ABI size of its element type. A fixed-length
- /// vector counts an integer element other than a _BitInt at its bit width and
- /// every other element at its own ABI size, so a bool element takes one bit.
- /// The total is rounded up to a power of two of at least 8 bits. Any other
- /// type returns the size it was created with, and a scalable type returns 0.
+ /// vector counts any integer element (including bool and _BitInt) at its bit
+ /// width and every other element at its own ABI size. The total is rounded
+ /// up to a power of two of at least 8 bits. Any other type returns the size
+ /// it was created with, and a scalable type returns 0.
LLVM_ABI uint64_t getABISizeInBits() const;
Align getAlignment() const { return ABIAlignment; }
@@ -362,6 +363,18 @@ class VectorType : public Type {
/// Returns true for any of the AArch64 SVE flavors.
bool isSVEType() const { return VecKind != VectorKind::Generic; }
+ /// Returns true if this is a fixed-length vector of _BitInt elements whose
+ /// element width is sub-byte or not a power of two (bit-packed in memory).
+ bool isPackedBitIntVector() const {
+ if (!isFixedLength())
+ return false;
+ const auto *IT = dyn_cast<IntegerType>(ElementType);
+ if (!IT || !IT->isBitInt())
+ return false;
+ uint64_t Width = IT->getSizeInBits().getFixedValue();
+ return Width < 8 || !llvm::isPowerOf2_64(Width);
+ }
+
static bool classof(const Type *T) {
return T->getKind() == TypeKind::Vector;
}
diff --git a/llvm/lib/ABI/Targets/AArch64.cpp b/llvm/lib/ABI/Targets/AArch64.cpp
index 3bd536c43a072c..84d199ad30df7e 100644
--- a/llvm/lib/ABI/Targets/AArch64.cpp
+++ b/llvm/lib/ABI/Targets/AArch64.cpp
@@ -102,7 +102,8 @@ ArgInfo AArch64TargetInfo::classifyReturnType(const Type *RetTy,
return ArgInfo::getIgnore();
if (const auto *VT = dyn_cast<VectorType>(RetTy)) {
- if (VT->isFixedLengthSVEData() || VT->isFixedLengthSVEPredicate()) {
+ if (VT->isFixedLengthSVEData() || VT->isFixedLengthSVEPredicate() ||
+ VT->isPackedBitIntVector()) {
unsigned NSRN = 0, NPRN = 0;
return coerceIllegalVector(VT, NSRN, NPRN);
}
@@ -449,10 +450,11 @@ ArgInfo AArch64TargetInfo::coerceIllegalVector(const VectorType *VT,
bool AArch64TargetInfo::isIllegalVectorType(const Type *Ty) const {
if (const auto *VT = dyn_cast<VectorType>(Ty)) {
- // Check whether VT is a fixed-length SVE vector. These types are
- // represented as scalable vectors in function args/return and must be
- // coerced from fixed vectors.
- if (VT->isFixedLengthSVEData() || VT->isFixedLengthSVEPredicate())
+ // Check whether VT is a fixed-length SVE vector or packed _BitInt vector.
+ // Fixed-length SVE vectors are represented as scalable vectors in function
+ // args/return and must be coerced from fixed vectors.
+ if (VT->isFixedLengthSVEData() || VT->isFixedLengthSVEPredicate() ||
+ VT->isPackedBitIntVector())
return true;
// Scalable SVE types are legal.
diff --git a/llvm/lib/ABI/Targets/X86.cpp b/llvm/lib/ABI/Targets/X86.cpp
index 8f886f175d31c6..e37fa989ce0474 100644
--- a/llvm/lib/ABI/Targets/X86.cpp
+++ b/llvm/lib/ABI/Targets/X86.cpp
@@ -1008,8 +1008,8 @@ const Type *X86_64TargetInfo::getIntegerTypeAtOffset(const Type *ABIType,
IT->isSigned());
}
}
- // A bool vector is stored as an integer with one bit per element, at least a
- // byte wide.
+ // A bool or packed _BitInt vector is stored as a bit-packed integer, at
+ // least a byte wide.
if (InMemory && ABIType->isVector()) {
const auto *VT = cast<VectorType>(ABIType);
const auto *IT = dyn_cast<IntegerType>(VT->getElementType());
@@ -1017,6 +1017,9 @@ const Type *X86_64TargetInfo::getIntegerTypeAtOffset(const Type *ABIType,
WorkingType = TB.getIntegerType(
std::max<uint64_t>(VT->getNumElements().getFixedValue(), 8),
ABIType->getAlignment(), /*Signed=*/false);
+ else if (VT->isPackedBitIntVector())
+ WorkingType = TB.getIntegerType(
+ VT->getABISizeInBits(), ABIType->getAlignment(), /*Signed=*/false);
}
// If we're dealing with an un-offset ABI type, then it means that we're
// returning an 8-byte unit starting with it. See if we can safely use it.
@@ -1229,11 +1232,12 @@ const Type *X86_64TargetInfo::getByteVectorType(const Type *Ty) const {
// Handle vector types
if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
- // Don't pass vXi128 vectors in their native type, the backend can't
- // legalize them.
- if (getX86ABICompatInfo().PassInt128VectorsInMem &&
- VT->getElementType()->isInteger() &&
- cast<IntegerType>(VT->getElementType())->getSizeInBits() == 128) {
+ // Don't pass vXi128 or packed _BitInt vectors in their native type; the
+ // backend can't legalize or pass sub-byte packed elements cleanly.
+ if ((getX86ABICompatInfo().PassInt128VectorsInMem &&
+ VT->getElementType()->isInteger() &&
+ cast<IntegerType>(VT->getElementType())->getSizeInBits() == 128) ||
+ VT->isPackedBitIntVector()) {
unsigned Size = VT->getABISizeInBits();
return TB.getVectorType(TB.getIntegerType(64, Align(8), /*Signed=*/false),
ElementCount::getFixed(Size / 64),
@@ -1256,6 +1260,8 @@ const Type *X86_64TargetInfo::getByteVectorType(const Type *Ty) const {
bool X86_64TargetInfo::isIllegalVectorType(const Type *Ty) const {
if (const auto *VecTy = dyn_cast<VectorType>(Ty)) {
+ if (VecTy->isPackedBitIntVector())
+ return true;
uint64_t Size = VecTy->getABISizeInBits();
unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
@@ -1339,6 +1345,9 @@ ArgInfo X86_64TargetInfo::getIndirectResult(const Type *Ty,
ArgInfo X86_64TargetInfo::getIndirectReturnResult(const Type *Ty) const {
if (!isAggregateTypeForABI(Ty)) {
+ if (const auto *VT = dyn_cast<VectorType>(Ty))
+ if (VT->isPackedBitIntVector())
+ return getNaturalAlignIndirect(VT, getAllocaAddrSpace());
// Bit-precise integers are returned indirectly regardless of size.
if (const auto *IntTy = dyn_cast<IntegerType>(Ty)) {
if (IntTy->isBitInt())
diff --git a/llvm/lib/ABI/Types.cpp b/llvm/lib/ABI/Types.cpp
index 1b51f0b6331850..c843255cb95053 100644
--- a/llvm/lib/ABI/Types.cpp
+++ b/llvm/lib/ABI/Types.cpp
@@ -31,8 +31,8 @@ uint64_t llvm::abi::Type::getABISizeInBits() const {
return 0;
const Type *EltTy = VT->getElementType();
const auto *IT = dyn_cast<IntegerType>(EltTy);
- uint64_t EltWidth = IT && !IT->isBitInt() ? IT->getFixedSizeInBitsOrZero()
- : EltTy->getABISizeInBits();
+ uint64_t EltWidth =
+ IT ? IT->getFixedSizeInBitsOrZero() : EltTy->getABISizeInBits();
uint64_t Width = EltWidth * VT->getNumElements().getFixedValue();
return bit_ceil(std::max<uint64_t>(Width, 8));
}
diff --git a/llvm/unittests/ABI/AArch64TargetInfoTest.cpp b/llvm/unittests/ABI/AArch64TargetInfoTest.cpp
index 6fcfddd3c82839..1b0e205d725c32 100644
--- a/llvm/unittests/ABI/AArch64TargetInfoTest.cpp
+++ b/llvm/unittests/ABI/AArch64TargetInfoTest.cpp
@@ -177,9 +177,9 @@ class AArch64TargetInfoTest : public ::testing::Test {
BitInt2(TB.getIntegerType(2, llvm::Align(1), /*Signed=*/true,
/*IsBitInt=*/true)),
V4BitInt2(TB.getVectorType(BitInt2, llvm::ElementCount::getFixed(4),
- llvm::Align(4))),
+ llvm::Align(1))),
V8BitInt2(TB.getVectorType(BitInt2, llvm::ElementCount::getFixed(8),
- llvm::Align(8))),
+ llvm::Align(2))),
ComplexFloat(TB.getComplexType(F32, llvm::Align(4))) {}
static RecordFlags passableRecordFlags(bool IsCXX = false) {
@@ -485,9 +485,9 @@ TEST_F(AArch64TargetInfoTest, ClassifyArgumentNonSVEVectors) {
expectDirectCoercedI32Vector(FI->getArgInfo(0).Info, 4);
}
- // A sub-byte _BitInt element counts as 8 bits towards the size of the
- // vector, so 4 x _BitInt(2) is an illegal 32-bit vector while
- // 8 x _BitInt(2) is a legal 64-bit one.
+ // Sub-byte _BitInt vectors are bit-packed and treated as illegal vectors on
+ // AArch64, so both 4 x _BitInt(2) (8 bits) and 8 x _BitInt(2) (16 bits)
+ // are coerced to i32.
{
std::unique_ptr<FunctionInfo> FI =
FunctionInfo::create(llvm::CallingConv::C, Void, {V4BitInt2});
@@ -499,7 +499,7 @@ TEST_F(AArch64TargetInfoTest, ClassifyArgumentNonSVEVectors) {
std::unique_ptr<FunctionInfo> FI =
FunctionInfo::create(llvm::CallingConv::C, Void, {V8BitInt2});
TI->computeInfo(*FI);
- expectUncoercedDirect(FI->getArgInfo(0).Info);
+ expectDirectCoercedInteger(FI->getArgInfo(0).Info, 32);
}
{
diff --git a/llvm/unittests/ABI/TypesTest.cpp b/llvm/unittests/ABI/TypesTest.cpp
index 13c790763a5149..13b530e2e4494e 100644
--- a/llvm/unittests/ABI/TypesTest.cpp
+++ b/llvm/unittests/ABI/TypesTest.cpp
@@ -239,7 +239,7 @@ TEST_F(ABITypesTest, ScalarABISize) {
EXPECT_EQ(TB.getComplexType(F32, Align(4))->getABISizeInBits(), 64u);
}
-// A bool element takes one bit and a one-bit _BitInt element a whole byte. The
+// Bool and sub-byte / non-power-of-2 _BitInt elements are bit-packed. The
// total is rounded up to a power of two of at least 8 bits.
TEST_F(ABITypesTest, VectorABISize) {
auto MakeVector = [&](const llvm::abi::Type *Elt, unsigned N,
@@ -250,13 +250,16 @@ TEST_F(ABITypesTest, VectorABISize) {
TB.getIntegerType(1, Align(1), /*Signed=*/false);
const llvm::abi::Type *UBitInt1 =
TB.getIntegerType(1, Align(1), /*Signed=*/false, /*IsBitInt=*/true);
+ const llvm::abi::Type *UBitInt3 =
+ TB.getIntegerType(3, Align(1), /*Signed=*/false, /*IsBitInt=*/true);
const llvm::abi::Type *F32 =
TB.getFloatType(llvm::APFloat::IEEEsingle(), Align(4));
EXPECT_EQ(MakeVector(Bool, 4, 1)->getABISizeInBits(), 8u);
EXPECT_EQ(MakeVector(Bool, 8, 1)->getABISizeInBits(), 8u);
EXPECT_EQ(MakeVector(Bool, 12, 2)->getABISizeInBits(), 16u);
- EXPECT_EQ(MakeVector(UBitInt1, 4, 4)->getABISizeInBits(), 32u);
- EXPECT_EQ(MakeVector(UBitInt1, 8, 8)->getABISizeInBits(), 64u);
+ EXPECT_EQ(MakeVector(UBitInt1, 4, 1)->getABISizeInBits(), 8u);
+ EXPECT_EQ(MakeVector(UBitInt1, 8, 1)->getABISizeInBits(), 8u);
+ EXPECT_EQ(MakeVector(UBitInt3, 4, 2)->getABISizeInBits(), 16u);
EXPECT_EQ(MakeVector(F32, 3, 16)->getABISizeInBits(), 128u);
}
diff --git a/llvm/unittests/ABI/X86TargetInfoTest.cpp b/llvm/unittests/ABI/X86TargetInfoTest.cpp
index 81dc2fbfe3433f..a1f035416d5b9f 100644
--- a/llvm/unittests/ABI/X86TargetInfoTest.cpp
+++ b/llvm/unittests/ABI/X86TargetInfoTest.cpp
@@ -593,21 +593,18 @@ TEST_F(X86TargetInfoTest, BoolVectorIsPassedAsInteger) {
expectDirectInteger(classifyArg(V17I1, FI, TI), 32);
}
-// Each two-element vector of 4-bit _BitInt takes 16 bits, so the fifth sits in
-// the high eightbyte and the struct is passed as an i64 and an i16.
+// Each two-element vector of 4-bit _BitInt is bit-packed into 8 bits, so an
+// array of five takes 40 bits and the struct is passed directly as i40.
TEST_F(X86TargetInfoTest, VectorArrayStepsByVectorSize) {
std::unique_ptr<FunctionInfo> FI;
std::unique_ptr<TargetInfo> TI;
const ABIType *I4 = TB.getIntegerType(4, llvm::Align(1), /*Signed=*/true,
/*IsBitInt=*/true);
- const ABIType *V2I4 = makeVector(I4, 2, llvm::Align(2));
+ const ABIType *V2I4 = makeVector(I4, 2, llvm::Align(1));
const ABIType *Arr =
- TB.getArrayType(V2I4, /*NumElements=*/5, /*SizeInBits=*/80);
- const ABIType *S = makeRecord({FieldInfo(Arr, 0)}, 80, llvm::Align(2));
- llvm::ArrayRef<FieldInfo> Pair = directPair(classifyArg(S, FI, TI));
- ASSERT_EQ(Pair.size(), 2u);
- expectInteger(Pair[0].FieldType, 64);
- expectInteger(Pair[1].FieldType, 16);
+ TB.getArrayType(V2I4, /*NumElements=*/5, /*SizeInBits=*/40);
+ const ABIType *S = makeRecord({FieldInfo(Arr, 0)}, 40, llvm::Align(1));
+ expectDirectInteger(classifyArg(S, FI, TI), 40);
}
// Padding past a three-float vector makes the 256-bit struct larger than the
@@ -639,20 +636,22 @@ TEST_F(X86TargetInfoTest, VectorArrayStepsByVectorSizeInUnion) {
expectInteger(Pair[1].FieldType, 64);
}
-// Sixteen 4-bit _BitInt elements take 128 bits, so once the SSE registers run
-// out the vector is still passed directly rather than in memory.
-TEST_F(X86TargetInfoTest, NibbleVectorIsDirectAfterSSERegistersRunOut) {
+// Sixteen 4-bit _BitInt elements are bit-packed into 64 bits (illegal vector
+// type), so once the SSE registers run out the vector is passed indirectly
+// byval while free integer registers remain.
+TEST_F(X86TargetInfoTest, NibbleVectorIsIndirectAfterSSERegistersRunOut) {
const ABIType *I4 = TB.getIntegerType(4, llvm::Align(1), /*Signed=*/true,
/*IsBitInt=*/true);
- const ABIType *V16I4 = makeVector(I4, 16, llvm::Align(16));
+ const ABIType *V16I4 = makeVector(I4, 16, llvm::Align(8));
std::unique_ptr<TargetInfo> TI = target();
std::unique_ptr<FunctionInfo> FI =
FunctionInfo::create(llvm::CallingConv::C, Void,
{F64, F64, F64, F64, F64, F64, F64, F64, V16I4});
TI->computeInfo(*FI);
const ArgInfo &Info = FI->getArgInfo(8).Info;
- ASSERT_TRUE(Info.isDirect());
- EXPECT_EQ(Info.getCoerceToType(), nullptr);
+ ASSERT_TRUE(Info.isIndirect());
+ EXPECT_TRUE(Info.getIndirectByVal());
+ EXPECT_EQ(Info.getIndirectAlign(), llvm::Align(8));
}
// Once the SSE registers run out, a vector of _BitInt(128) is still passed
@@ -920,9 +919,9 @@ TEST_F(X86TargetInfoTest, BoolVectorInMemoryNarrowsInEveryPosition) {
}
}
-// A vector of one-bit _BitInts is not a bool vector, so the eightbyte holding
-// it stays an i64.
-TEST_F(X86TargetInfoTest, BitIntVectorInMemoryIsNotNarrowed) {
+// A packed sub-byte _BitInt vector narrows its eightbyte to its byte storage
+// size, while a byte-sized _BitInt vector keeps the eightbyte as i64.
+TEST_F(X86TargetInfoTest, PackedBitIntVectorInMemoryIsNarrowed) {
std::unique_ptr<FunctionInfo> FI;
std::unique_ptr<TargetInfo> TI;
const ABIType *UBitInt1 = TB.getIntegerType(1, llvm::Align(1),
@@ -934,7 +933,18 @@ TEST_F(X86TargetInfoTest, BitIntVectorInMemoryIsNotNarrowed) {
llvm::ArrayRef<FieldInfo> Pair = directPair(classifyArg(S, FI, TI));
ASSERT_EQ(Pair.size(), 2u);
expectInteger(Pair[0].FieldType, 64);
- expectInteger(Pair[1].FieldType, 64);
+ expectInteger(Pair[1].FieldType, 8);
+
+ const ABIType *UBitInt8 = TB.getIntegerType(8, llvm::Align(1),
+ /*Signed=*/false,
+ /*IsBitInt=*/true);
+ const ABIType *V8 = makeVector(UBitInt8, 1, llvm::Align(1));
+ const ABIType *S8 =
+ makeRecord({FieldInfo(I64, 0), FieldInfo(V8, 64)}, 128, llvm::Align(8));
+ llvm::ArrayRef<FieldInfo> Pair8 = directPair(classifyArg(S8, FI, TI));
+ ASSERT_EQ(Pair8.size(), 2u);
+ expectInteger(Pair8[0].FieldType, 64);
+ expectInteger(Pair8[1].FieldType, 64);
}
TEST_F(X86TargetInfoTest, IntReturnExtension) {
>From 6e4512bab796f3d410467ff94741b768666e80fa Mon Sep 17 00:00:00 2001
From: Filip Chromy <filip at daiteq.com>
Date: Fri, 4 Dec 2026 15:46:20 +0100
Subject: [PATCH 3/3] [Clang] Allow arbitrary non-power-of-2 _BitInt vector
element widths
Relax the power-of-2 restriction for _BitInt(N) elements in vector_size and ext_vector_type (while keeping it for matrix_type).
Sub-byte and non-power-of-2 _BitInt vectors use the bit-packed layout, constexpr evaluation, DebugInfo, and CodeGen/ABI lowering introduced in the preceding commits. Adds Sema, constexpr/__builtin_bit_cast (both evaluators), CodeGen (x86-64, AArch64, RISC-V 64, Windows x64, SystemZ big-endian), and DebugInfo tests, and updates ReleaseNotes.
---
clang/docs/ReleaseNotes.md | 6 +
clang/lib/AST/ASTContext.cpp | 9 +-
clang/lib/Sema/SemaType.cpp | 17 ---
clang/test/CodeGen/bitint-vector.c | 125 ++++++++++++++++++
clang/test/DebugInfo/Generic/bitint-vector.c | 18 +++
clang/test/Sema/bitint-vector.c | 74 +++++++++++
.../test/SemaCXX/bitint-vector-constexpr.cpp | 68 ++++++++++
clang/test/SemaCXX/ext-int-vector.cpp | 4 +-
clang/test/SemaCXX/ext-int.cpp | 9 +-
9 files changed, 298 insertions(+), 32 deletions(-)
create mode 100644 clang/test/CodeGen/bitint-vector.c
create mode 100644 clang/test/DebugInfo/Generic/bitint-vector.c
create mode 100644 clang/test/Sema/bitint-vector.c
create mode 100644 clang/test/SemaCXX/bitint-vector-constexpr.cpp
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index f4f1f20dd5e79b..129137cecd4592 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -439,6 +439,12 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
be detected by watching the directories or by comparing their modification
times.
+- `vector_size` and `ext_vector_type` vectors now support arbitrary `_BitInt(N)`
+ element widths rather than restricting `N` to powers of 2. Non-power-of-2 and
+ sub-byte `_BitInt(N)` vectors are stored bit-packed without per-element byte
+ padding. Matrix types continue to require power-of-2 `_BitInt` element
+ widths.
+
### New Compiler Flags
- Added `-fpch-base-dir-is-cwd` to serialize precompiled header input paths
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index c60b362d95d4b0..8442ee5a901db7 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -4755,10 +4755,7 @@ QualType ASTContext::getScalableVectorType(QualType EltTy, unsigned NumElts,
/// the specified element type and size. VectorType must be a built-in type.
QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
VectorKind VecKind) const {
- assert(vecType->isBuiltinType() ||
- (vecType->isBitIntType() &&
- // Only support _BitInt elements with byte-sized power of 2 NumBits.
- llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
+ assert(vecType->isBuiltinType() || vecType->isBitIntType());
// Check if we've already instantiated a vector of this type.
llvm::FoldingSetNodeID ID;
@@ -4826,9 +4823,7 @@ QualType ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
QualType ASTContext::getExtVectorType(QualType vecType,
unsigned NumElts) const {
assert(vecType->isBuiltinType() || vecType->isDependentType() ||
- (vecType->isBitIntType() &&
- // Only support _BitInt elements with byte-sized power of 2 NumBits.
- llvm::isPowerOf2_32(vecType->castAs<BitIntType>()->getNumBits())));
+ vecType->isBitIntType());
// Check if we've already instantiated a vector of this type.
llvm::FoldingSetNodeID ID;
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 1c86cad6ace8eb..71f0f1f3570b18 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -2418,15 +2418,6 @@ QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM,
return T;
}
-static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc,
- const BitIntType *BIT,
- bool ForMatrixType = false) {
- if (!llvm::isPowerOf2_32(BIT->getNumBits()))
- return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
- << ForMatrixType;
- return false;
-}
-
static bool isPackedBitIntVectorTooLarge(QualType EltTy, uint64_t NumElts) {
const auto *BIT = EltTy->getAs<BitIntType>();
if (!BIT)
@@ -2460,10 +2451,6 @@ QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
return QualType();
}
- if (const auto *BIT = CurType->getAs<BitIntType>();
- BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
- return QualType();
-
if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
VectorKind::Generic);
@@ -2539,10 +2526,6 @@ QualType Sema::BuildExtVectorType(QualType T, Expr *SizeExpr,
return QualType();
}
- if (const auto *BIT = T->getAs<BitIntType>();
- BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
- return QualType();
-
if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
std::optional<llvm::APSInt> VecSize =
SizeExpr->getIntegerConstantExpr(Context);
diff --git a/clang/test/CodeGen/bitint-vector.c b/clang/test/CodeGen/bitint-vector.c
new file mode 100644
index 00000000000000..c3cad90de3643a
--- /dev/null
+++ b/clang/test/CodeGen/bitint-vector.c
@@ -0,0 +1,125 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,X64,LE
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,AARCH64,LE
+// RUN: %clang_cc1 -triple riscv64-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,RV64,LE
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,WIN64,LE
+// RUN: %clang_cc1 -triple s390x-unknown-linux-gnu -emit-llvm -o - %s | FileCheck %s --check-prefixes=CHECK,BE
+
+typedef unsigned _BitInt(3) u3;
+typedef _BitInt(3) i3;
+typedef unsigned _BitInt(4) u4;
+
+typedef u3 v10u3 __attribute__((ext_vector_type(10)));
+typedef u3 v3u3 __attribute__((ext_vector_type(3)));
+typedef u3 v2u3 __attribute__((ext_vector_type(2)));
+typedef i3 v10i3 __attribute__((ext_vector_type(10)));
+typedef u3 v24u3 __attribute__((ext_vector_type(24)));
+typedef u3 v64u3 __attribute__((ext_vector_type(64)));
+typedef u4 v8u4 __attribute__((ext_vector_type(8)));
+typedef u4 v16u4 __attribute__((ext_vector_type(16)));
+
+// LE: @g_u10 = {{.*}}global i32 287267025, align 4
+// BE: @g_u10 = {{.*}}global i32 175304202, align 4
+v10u3 g_u10 = {1, 2, 3, 4, 5, 6, 7, 0, 1, 2};
+
+// LE: @g_u24 = {{.*}}global i128 1746937885674054534792, align 16
+// BE: @g_u24 = {{.*}}global i128 96374544705885771642, align 16
+v24u3 g_u24 = {0, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 0, 2, 4, 6, 1, 3, 5, 7, 2};
+
+// X64-LABEL: define dso_local i32 @add_v10u3(i32 noundef %a.coerce, i32 noundef %b.coerce)
+// AARCH64-LABEL: define dso_local i32 @add_v10u3(i32 noundef %a.coerce, i32 noundef %b.coerce)
+// RV64-LABEL: define dso_local i32 @add_v10u3(i32 noundef %a.coerce, i32 noundef %b.coerce)
+// WIN64-LABEL: define dso_local i32 @add_v10u3(i32 noundef %a.coerce, i32 noundef %b.coerce)
+v10u3 add_v10u3(v10u3 a, v10u3 b) {
+ // CHECK: add <10 x i3>
+ return a + b;
+}
+
+// X64-LABEL: define dso_local double @add_v16u4(double noundef %a.coerce, double noundef %b.coerce)
+// AARCH64-LABEL: define dso_local <2 x i32> @add_v16u4(<2 x i32> noundef %a.coerce, <2 x i32> noundef %b.coerce)
+// RV64-LABEL: define dso_local i64 @add_v16u4(i64 noundef %a.coerce, i64 noundef %b.coerce)
+// WIN64-LABEL: define dso_local i64 @add_v16u4(i64 noundef %a.coerce, i64 noundef %b.coerce)
+v16u4 add_v16u4(v16u4 a, v16u4 b) {
+ // CHECK: add <16 x i4>
+ return a + b;
+}
+
+// X64-LABEL: define dso_local <2 x i64> @add_v24u3(<2 x i64> noundef %a.coerce, <2 x i64> noundef %b.coerce)
+// AARCH64-LABEL: define dso_local <4 x i32> @add_v24u3(<4 x i32> noundef %a.coerce, <4 x i32> noundef %b.coerce)
+// RV64-LABEL: define dso_local i128 @add_v24u3(i128 noundef %a.coerce, i128 noundef %b.coerce)
+// WIN64-LABEL: define dso_local <2 x i64> @add_v24u3(<2 x i64> noundef %a.coerce, <2 x i64> noundef %b.coerce)
+v24u3 add_v24u3(v24u3 a, v24u3 b) {
+ // CHECK: add <24 x i3>
+ return a + b;
+}
+
+// X64-LABEL: define dso_local void @add_v64u3(ptr dead_on_unwind noalias writable sret(i256) align 32 %agg.result, ptr noundef byval(i256) align 32 %0, ptr noundef byval(i256) align 32 %1)
+// AARCH64-LABEL: define dso_local void @add_v64u3(ptr dead_on_unwind noalias writable sret(i256) align 16 %agg.result,
+// RV64-LABEL: define dso_local void @add_v64u3(ptr dead_on_unwind noalias writable sret(i256) align 32 %agg.result,
+// WIN64-LABEL: define dso_local <4 x i64> @add_v64u3(<4 x i64> noundef %a.coerce, <4 x i64> noundef %b.coerce)
+v64u3 add_v64u3(v64u3 a, v64u3 b) {
+ // CHECK: add <64 x i3>
+ return a + b;
+}
+
+// CHECK-LABEL: define dso_local {{.*}}@swizzle_ops(
+v3u3 swizzle_ops(v10u3 a, v10u3 b, int idx, u3 val) {
+ // CHECK: shufflevector <10 x i3> {{.*}}, <3 x i32> <i32 0, i32 2, i32 3>
+ v3u3 r = (a + b).xzw;
+ // CHECK: extractelement <3 x i32> <i32 2, i32 0, i32 1>, i64
+ // CHECK: insertelement <3 x i3> {{.*}}, i3 %{{.*}}, i32 %vec.swizzle.idx
+ r.zxy[idx] = val;
+ r.xy = (v2u3){7, 3};
+ return r;
+}
+
+// CHECK-LABEL: define dso_local {{.*}}@subscript_ops(
+v10u3 subscript_ops(v10u3 a, int idx, u3 val) {
+ // CHECK: extractelement <10 x i3>
+ // CHECK: insertelement <10 x i3>
+ a[idx] += val;
+ return a;
+}
+
+// CHECK-LABEL: define dso_local {{.*}}@cmp_v10i3(
+v10i3 cmp_v10i3(v10i3 a, v10i3 b) {
+ // CHECK: icmp slt <10 x i3>
+ // CHECK: sext <10 x i1> %{{.*}} to <10 x i3>
+ return a < b;
+}
+
+// CHECK-LABEL: define dso_local {{.*}}@bitcast_v8u4(
+v8u4 bitcast_v8u4(unsigned int x) {
+ // CHECK: bitcast i32 %{{.*}} to <8 x i4>
+ v8u4 v = __builtin_bit_cast(v8u4, x);
+ return v;
+}
+
+// CHECK-LABEL: define {{.*}}@nt_load_v10u3(
+v10u3 nt_load_v10u3(v10u3 *p) {
+ // CHECK: load i32, ptr %{{.*}}, !nontemporal
+ return __builtin_nontemporal_load(p);
+}
+
+// CHECK-LABEL: define dso_local void @clear_pad_v10u3(
+void clear_pad_v10u3(v10u3 *p) {
+ // LE: getelementptr i8, ptr %{{.*}}, i32 3
+ // LE: and i8 %{{.*}}, 63
+ // LE-NEXT: store i8
+ // BE: getelementptr i8, ptr %{{.*}}, i32 0
+ // BE: and i8 %{{.*}}, 63
+ // BE-NEXT: store i8
+ __builtin_clear_padding(p);
+}
+
+// CHECK-LABEL: define dso_local void @clear_pad_v24u3(
+void clear_pad_v24u3(v24u3 *p) {
+ // LE: getelementptr i8, ptr %{{.*}}, i32 9
+ // LE-NEXT: store i8 0
+ // LE: getelementptr i8, ptr %{{.*}}, i32 15
+ // LE-NEXT: store i8 0
+ // BE: getelementptr i8, ptr %{{.*}}, i32 0
+ // BE-NEXT: store i8 0
+ // BE: getelementptr i8, ptr %{{.*}}, i32 6
+ // BE-NEXT: store i8 0
+ __builtin_clear_padding(p);
+}
diff --git a/clang/test/DebugInfo/Generic/bitint-vector.c b/clang/test/DebugInfo/Generic/bitint-vector.c
new file mode 100644
index 00000000000000..c7a144f185786b
--- /dev/null
+++ b/clang/test/DebugInfo/Generic/bitint-vector.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=limited -triple x86_64-unknown-linux-gnu %s -o - | FileCheck %s
+
+typedef unsigned _BitInt(3) u3;
+typedef u3 v10u3 __attribute__((ext_vector_type(10)));
+typedef u3 v24u3 __attribute__((ext_vector_type(24)));
+
+v10u3 g10;
+v24u3 g24;
+
+// CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "v24u3"{{.*}}baseType: ![[V24:[0-9]+]])
+// CHECK: ![[V24]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[CHAR:[0-9]+]], size: 128, flags: DIFlagVector, elements: ![[E16:[0-9]+]])
+// CHECK: ![[CHAR]] = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+// CHECK: ![[E16]] = !{![[S16:[0-9]+]]}
+// CHECK: ![[S16]] = !DISubrange(count: 16)
+// CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "v10u3"{{.*}}baseType: ![[V10:[0-9]+]])
+// CHECK: ![[V10]] = !DICompositeType(tag: DW_TAG_array_type, baseType: ![[CHAR]], size: 32, flags: DIFlagVector, elements: ![[E4:[0-9]+]])
+// CHECK: ![[E4]] = !{![[S4:[0-9]+]]}
+// CHECK: ![[S4]] = !DISubrange(count: 4)
diff --git a/clang/test/Sema/bitint-vector.c b/clang/test/Sema/bitint-vector.c
new file mode 100644
index 00000000000000..f694acf019eb03
--- /dev/null
+++ b/clang/test/Sema/bitint-vector.c
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -fsyntax-only -triple x86_64-unknown-linux-gnu -fenable-matrix -verify %s
+
+typedef unsigned _BitInt(1) u1;
+typedef _BitInt(2) i2;
+typedef unsigned _BitInt(2) u2;
+typedef _BitInt(3) i3;
+typedef unsigned _BitInt(3) u3;
+typedef unsigned _BitInt(4) u4;
+typedef _BitInt(5) i5;
+typedef unsigned _BitInt(12) u12;
+typedef _BitInt(24) i24;
+
+typedef u1 v8u1 __attribute__((ext_vector_type(8)));
+typedef u1 v8u1_vec __attribute__((vector_size(1)));
+typedef u2 v4u2 __attribute__((ext_vector_type(4)));
+typedef u3 v10u3 __attribute__((ext_vector_type(10)));
+typedef i3 v10i3 __attribute__((ext_vector_type(10)));
+typedef u4 v8u4 __attribute__((ext_vector_type(8)));
+typedef i5 v8i5 __attribute__((vector_size(5)));
+typedef u12 v4u12 __attribute__((vector_size(6)));
+typedef i24 v3i24 __attribute__((ext_vector_type(3)));
+
+_Static_assert(sizeof(v8u1) == 1, "");
+_Static_assert(_Alignof(v8u1) == 1, "");
+_Static_assert(sizeof(v4u2) == 1, "");
+_Static_assert(_Alignof(v4u2) == 1, "");
+_Static_assert(sizeof(v10u3) == 4, "");
+_Static_assert(_Alignof(v10u3) == 4, "");
+_Static_assert(sizeof(v10i3) == 4, "");
+_Static_assert(_Alignof(v10i3) == 4, "");
+_Static_assert(sizeof(v8u4) == 4, "");
+_Static_assert(_Alignof(v8u4) == 4, "");
+_Static_assert(sizeof(v8i5) == 8, ""); // 40 bits -> align ceil pow2 = 8 bytes
+_Static_assert(sizeof(v4u12) == 8, ""); // 48 bits -> align ceil pow2 = 8 bytes
+_Static_assert(sizeof(v3i24) == 16, ""); // 72 bits -> align ceil pow2 = 16 bytes
+
+typedef i3 v10i3_cmp __attribute__((ext_vector_type(10)));
+typedef u3 v10u3_cmp __attribute__((ext_vector_type(10)));
+
+void test_ops(v10u3 a, v10u3 b, v10i3 sa, v10i3 sb, v8u1 b1, v8u1 b2,
+ v8u1_vec bv1, v8u1_vec bv2) {
+ v10u3 sum = a + b;
+ v10i3_cmp c1 = a == b;
+ v10i3_cmp c2 = sa < sb;
+ _Bool sc __attribute__((ext_vector_type(8))) = b1 == b2;
+ signed char svc __attribute__((vector_size(8))) = bv1 == bv2;
+ (void)sum;
+ (void)c1;
+ (void)c2;
+ (void)sc;
+ (void)svc;
+
+ a.x = 1;
+ u3 e = a.x;
+ (void)e;
+ // expected-error at +1{{address of vector element requested}}
+ (void)&a[0];
+ // expected-error at +1{{address of vector element requested}}
+ (void)&a.x;
+}
+
+// Non-multiple vector_size still rejected:
+// expected-error at +1{{vector size not an integral multiple of component size}}
+typedef u3 bad_vsize __attribute__((vector_size(4)));
+
+// Storage padded integer width must fit in LLVM IntegerType::MAX_INT_BITS:
+// expected-error at +1{{vector size too large}}
+typedef u3 huge_ext_vec __attribute__((ext_vector_type(3000000)));
+// expected-error at +1{{vector size too large}}
+typedef u3 huge_vec_size __attribute__((vector_size(1200000)));
+
+// Matrices still require power-of-2 _BitInt element widths:
+// expected-error at +1{{'_BitInt' matrix element width must be a power of 2}}
+typedef i3 bad_mat __attribute__((matrix_type(2, 2)));
diff --git a/clang/test/SemaCXX/bitint-vector-constexpr.cpp b/clang/test/SemaCXX/bitint-vector-constexpr.cpp
new file mode 100644
index 00000000000000..55ef9c5c3a7b09
--- /dev/null
+++ b/clang/test/SemaCXX/bitint-vector-constexpr.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -triple x86_64-unknown-linux-gnu -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -triple x86_64-unknown-linux-gnu -fexperimental-new-constant-interpreter -verify %s
+
+using u1 = unsigned _BitInt(1);
+using u2 = unsigned _BitInt(2);
+using u3 = unsigned _BitInt(3);
+using i3 = _BitInt(3);
+using u4 = unsigned _BitInt(4);
+using u12 = unsigned _BitInt(12);
+
+using v8u1 = u1 __attribute__((ext_vector_type(8)));
+using v4u2 = u2 __attribute__((ext_vector_type(4)));
+using v4u4 = u4 __attribute__((ext_vector_type(4)));
+using v8u4 = u4 __attribute__((ext_vector_type(8)));
+using v8u3 = u3 __attribute__((ext_vector_type(8)));
+using v10u3 = u3 __attribute__((ext_vector_type(10)));
+using v10i3 = i3 __attribute__((ext_vector_type(10)));
+using v2u12 = u12 __attribute__((ext_vector_type(2)));
+
+constexpr v10u3 v_add = v10u3{1, 2, 3, 4, 5, 6, 7, 0, 1, 2} +
+ v10u3{2, 3, 4, 5, 6, 7, 0, 1, 2, 3};
+static_assert(v_add[0] == 3 && v_add[1] == 5 && v_add[2] == 7 && v_add[3] == 1);
+
+constexpr v10i3 v_sadd = v10i3{-2, -1, 1, 2, 0, 0, 0, 0, 0, 0} +
+ v10i3{-1, 2, 1, 1, 0, 0, 0, 0, 0, 0};
+static_assert(v_sadd[0] == -3 && v_sadd[1] == 1 && v_sadd[2] == 2 && v_sadd[3] == 3);
+
+constexpr auto v_shuf = __builtin_shufflevector(v_add, v_add, 0, 2, 3);
+static_assert(v_shuf[0] == 3 && v_shuf[1] == 7 && v_shuf[2] == 1);
+
+constexpr u3 test_constexpr_fn(v10u3 a, unsigned i) {
+ a[i] += 2;
+ return a[i];
+}
+static_assert(test_constexpr_fn(v_add, 3) == 3);
+
+constexpr auto v_cmp = (v10u3{1, 2, 3} == v10u3{1, 5, 3});
+static_assert(v_cmp[0] == -1 && v_cmp[1] == 0 && v_cmp[2] == -1);
+
+// __builtin_bit_cast for exact byte-multiple packed _BitInt vectors (little-endian):
+constexpr v4u2 bc_u2{1, 2, 3, 0}; // 0b00_11_10_01 = 0x39
+static_assert(__builtin_bit_cast(unsigned char, bc_u2) == 0x39);
+constexpr v4u2 bc_u2_rt = __builtin_bit_cast(v4u2, static_cast<unsigned char>(0xE4)); // 3,2,1,0? 0xE4 = 11_10_01_00
+static_assert(bc_u2_rt[0] == 0 && bc_u2_rt[1] == 1 && bc_u2_rt[2] == 2 && bc_u2_rt[3] == 3);
+
+constexpr v4u4 bc_u4{0x1, 0x2, 0xA, 0xF};
+static_assert(__builtin_bit_cast(unsigned short, bc_u4) == 0xFA21);
+constexpr v4u4 bc_u4_rt = __builtin_bit_cast(v4u4, static_cast<unsigned short>(0x1234));
+static_assert(bc_u4_rt[0] == 4 && bc_u4_rt[1] == 3 && bc_u4_rt[2] == 2 && bc_u4_rt[3] == 1);
+
+constexpr v8u4 bc_u4x8{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7};
+static_assert(__builtin_bit_cast(unsigned int, bc_u4x8) == 0x76543210U);
+
+constexpr v8u1 bc_u1{1, 0, 1, 1, 0, 0, 1, 0}; // 0b01001101 = 0x4D
+static_assert(__builtin_bit_cast(unsigned char, bc_u1) == 0x4D);
+
+constexpr v2u12 bc_u12{0x123, 0x456}; // 0x456123 stored in 3 bytes? Wait: alignTo(24,8)=24, align=32 -> 4 bytes!
+
+// Tail-padded vector (10 * 3 = 30 bits in 32-bit storage) is rejected in constexpr bit_cast:
+// expected-error at +2{{constexpr variable 'bad_bc' must be initialized by a constant expression}}
+// expected-note at +1{{element size 3 * element count 10 is not a multiple of the byte size 8}}
+constexpr unsigned int bad_bc = __builtin_bit_cast(unsigned int, v10u3{1});
+
+void test_ref(v10u3 v) {
+ // expected-error at +1{{non-const reference cannot bind to vector element}}
+ u3 &r = v[0];
+ (void)r;
+}
diff --git a/clang/test/SemaCXX/ext-int-vector.cpp b/clang/test/SemaCXX/ext-int-vector.cpp
index 756ad219feea9f..d53bd0e4b52076 100644
--- a/clang/test/SemaCXX/ext-int-vector.cpp
+++ b/clang/test/SemaCXX/ext-int-vector.cpp
@@ -108,11 +108,9 @@ template void check<FloatGnu4, IntGnu4>(FloatGnu4, FloatGnu4);
template void check<DoubleGnu4, LongLongGnu4>(DoubleGnu4, DoubleGnu4);
template void check<LongDoubleGnu2, Int128Gnu2>(LongDoubleGnu2, LongDoubleGnu2);
-// expected-error at +1{{'_BitInt' vector element width must be a power of 2}}
typedef _BitInt(7) __attribute__((ext_vector_type(4))) ExtVec7x4;
-// expected-error at +1{{'_BitInt' vector element width must be a power of 2}}
typedef _BitInt(255) __attribute__((ext_vector_type(2))) ExtVec255x2;
-// expected-error at +1{{'_BitInt' vector element width must be a power of 2}}
+// expected-error at +1{{vector size not an integral multiple of component size}}
typedef _BitInt(255) __attribute__((vector_size(64))) GnuVec255x2;
} // namespace GH200665
diff --git a/clang/test/SemaCXX/ext-int.cpp b/clang/test/SemaCXX/ext-int.cpp
index b2d0ac57e19ada..ad7aa4ab4e5595 100644
--- a/clang/test/SemaCXX/ext-int.cpp
+++ b/clang/test/SemaCXX/ext-int.cpp
@@ -106,14 +106,13 @@ void Templates() {
#endif
}
-// Reject vector types:
-// expected-error at +1{{'_BitInt' vector element width must be a power of 2}}
+// Bit-packed non-power-of-2 _BitInt vector types:
+// expected-error at +1{{vector size not an integral multiple of component size}}
typedef _BitInt(5) __attribute__((vector_size(16))) VecTy3;
-// expected-error at +1{{'_BitInt' vector element width must be a power of 2}}
+typedef _BitInt(5) __attribute__((vector_size(5))) ValidVecTy3;
typedef _BitInt(5) __attribute__((ext_vector_type(32))) OtherVecTy3;
-// expected-error at +1{{'_BitInt' vector element width must be a power of 2}}
+// expected-error at +1{{vector size not an integral multiple of component size}}
typedef _BitInt(37) __attribute__((vector_size(16))) VecTy4;
-// expected-error at +1{{'_BitInt' vector element width must be a power of 2}}
typedef _BitInt(37) __attribute__((ext_vector_type(32))) OtherVecTy4;
// expected-error at +1{{'_Complex _BitInt' is invalid}}
More information about the cfe-commits
mailing list