[llvm] [SPIRV] Add Intermediate cast when Vector From/To types are of different element size and type (PR #182166)

Farzon Lotfi via llvm-commits llvm-commits at lists.llvm.org
Wed Feb 18 22:05:56 PST 2026


================
@@ -78,18 +78,25 @@ class SPIRVLegalizePointerCast : public FunctionPass {
     Value *AssignValue = NewLoad;
     if (TargetType->getElementType() != SourceType->getElementType()) {
       const DataLayout &DL = B.GetInsertBlock()->getModule()->getDataLayout();
-      [[maybe_unused]] TypeSize TargetTypeSize =
-          DL.getTypeSizeInBits(TargetType);
-      [[maybe_unused]] TypeSize SourceTypeSize =
-          DL.getTypeSizeInBits(SourceType);
-      assert(TargetTypeSize == SourceTypeSize);
+      TypeSize TargetTypeSize = DL.getTypeSizeInBits(TargetType);
+      TypeSize SourceTypeSize = DL.getTypeSizeInBits(SourceType);
+      // Bitcast to a same-bitwidth vector with TargetType's element type.
+      // When sizes differ, use an intermediate type to preserve bitwidth.
+      auto *BitcastType = TargetType;
+      if (TargetTypeSize != SourceTypeSize) {
+        unsigned ElemBits = TargetType->getElementType()->getScalarSizeInBits();
+        BitcastType = FixedVectorType::get(TargetType->getElementType(),
+                                           SourceTypeSize / ElemBits);
----------------
farzonl wrote:

I can write this case in LLVM though

```llvm
@.str.in = private unnamed_addr constant [3 x i8] c"In\00", align 1
@.str.out = private unnamed_addr constant [4 x i8] c"Out\00", align 1

define void @main() local_unnamed_addr #0 {
entry:
  %0 = tail call target("spirv.VulkanBuffer", [0 x <3 x i32>], 12, 0) @llvm.spv.resource.handlefrombinding.tspirv.VulkanBuffer_a0v3i32_12_0t(i32 0, i32 0, i32 1, i32 0, ptr nonnull @.str.in)
  %1 = tail call target("spirv.VulkanBuffer", [0 x <2 x i64>], 12, 0) @llvm.spv.resource.handlefrombinding.tspirv.VulkanBuffer_a0v1i64_12_0t(i32 0, i32 1, i32 1, i32 0, ptr nonnull @.str.out)
  %2 = tail call noundef align 16 dereferenceable(12) ptr addrspace(11) @llvm.spv.resource.getpointer.p11.tspirv.VulkanBuffer_a0v3i32_12_0t(target("spirv.VulkanBuffer", [0 x <3 x i32>], 12, 0) %0, i32 0)
  %3 = load <2 x i64>, ptr addrspace(11) %2, align 16
  %4 = tail call noundef align 8 dereferenceable(8) ptr addrspace(11) @llvm.spv.resource.getpointer.p11.tspirv.VulkanBuffer_a0v1i64_12_0t(target("spirv.VulkanBuffer", [0 x <2 x i64>], 12, 0) %1, i32 0)
  store <2 x i64> %3, ptr addrspace(11) %4, align 8
  ret void
}
```

Whats going on here is the source total bit width is not evenly divisible by the target element bit width.
- Source: <3 x i32> = 96 bits, Target: <2 x i64> = 128 bits
- ElemBits = 64, 96 % 64 = 32 != 0

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


More information about the llvm-commits mailing list