[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:59:11 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-aarch64

Author: gdaiteq

<details>
<summary>Changes</summary>

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.

---

Patch is 103.97 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/248936.diff


38 Files Affected:

- (modified) clang/docs/ReleaseNotes.md (+12) 
- (modified) clang/include/clang/AST/TypeBase.h (+5) 
- (modified) clang/lib/AST/ASTContext.cpp (+26-17) 
- (modified) clang/lib/AST/ByteCode/IntegralAP.h (+4-2) 
- (modified) clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp (+31-33) 
- (modified) clang/lib/AST/ExprConstant.cpp (+29-39) 
- (modified) clang/lib/AST/Type.cpp (+18) 
- (modified) clang/lib/CodeGen/CGAtomic.cpp (+10-8) 
- (modified) clang/lib/CodeGen/CGDebugInfo.cpp (+4-7) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+119-27) 
- (modified) clang/lib/CodeGen/CGExprConstant.cpp (+30) 
- (modified) clang/lib/CodeGen/CGStmt.cpp (+9-2) 
- (modified) clang/lib/CodeGen/CGValue.h (+9-1) 
- (modified) clang/lib/CodeGen/CodeGenFunction.cpp (+8-1) 
- (modified) clang/lib/CodeGen/CodeGenTypes.cpp (+13-18) 
- (modified) clang/lib/CodeGen/Targets/AArch64.cpp (+4-2) 
- (modified) clang/lib/CodeGen/Targets/X86.cpp (+20-5) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+12) 
- (modified) clang/lib/Sema/SemaType.cpp (+24-23) 
- (modified) clang/test/CodeGen/AArch64/abi-classify-arg-types.c (+8-6) 
- (modified) clang/test/CodeGen/X86/x86_64-abi-size.c (+6-6) 
- (modified) clang/test/CodeGen/X86/x86_64-vector-abi-size.c (+8-8) 
- (added) clang/test/CodeGen/bitint-vector.c (+125) 
- (modified) clang/test/CodeGenCXX/ext-int.cpp (+19-16) 
- (modified) clang/test/CodeGenCXX/matrix-vector-bit-int.cpp (+24-20) 
- (added) clang/test/DebugInfo/Generic/bitint-vector.c (+18) 
- (added) clang/test/Sema/bitint-vector.c (+74) 
- (modified) clang/test/Sema/ext-int.c (+3-3) 
- (added) clang/test/SemaCXX/bitint-vector-constexpr.cpp (+68) 
- (modified) clang/test/SemaCXX/ext-int-vector.cpp (+5-7) 
- (modified) clang/test/SemaCXX/ext-int.cpp (+4-5) 
- (modified) llvm/include/llvm/ABI/Types.h (+17-4) 
- (modified) llvm/lib/ABI/Targets/AArch64.cpp (+7-5) 
- (modified) llvm/lib/ABI/Targets/X86.cpp (+16-7) 
- (modified) llvm/lib/ABI/Types.cpp (+2-2) 
- (modified) llvm/unittests/ABI/AArch64TargetInfoTest.cpp (+6-6) 
- (modified) llvm/unittests/ABI/TypesTest.cpp (+6-3) 
- (modified) llvm/unittests/ABI/X86TargetInfoTest.cpp (+29-19) 


``````````diff
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 5a92a4e888f39a..129137cecd4592 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
@@ -433,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/include/clang/AST/TypeBase.h b/clang/include/clang/AST/TypeBase.h
index 7e8fbab357a4cf..8b5903794dd563 100644
--- a/clang/include/clang/AST/TypeBase.h
+++ b/clang/include/clang/AST/TypeBase.h
@@ -2705,6 +2705,11 @@ 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 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.
   bool isConstantMatrixType() const;            // Constant matrix type.
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 2da42f732b3afa..8442ee5a901db7 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>(
@@ -4753,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;
@@ -4824,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;
@@ -16205,6 +16202,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();
@@ -16212,27 +16217,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;
@@ -16253,6 +16258,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 32343e8d79b725..dbd55b97ade3d7 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,14 +315,15 @@ 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,
-      // 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();
@@ -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;
 
@@ -534,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, {
@@ -583,7 +583,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 +590,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 +598,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 +612,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..c199d3c4ec7f37 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...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/248936


More information about the cfe-commits mailing list