authorgravatar for alichraghi@proton.meAli Chraghi <alichraghi@proton.me> 2025-05-07 20:25:06+03:30
committergravatar for alichraghi@proton.meAli Chraghi <alichraghi@proton.me> 2025-05-21 13:01:20+03:30
logdacd70fbe41d959bb7b48b5bad8612e74231524b
tree6370ef5fa121ecb9aa44cf64d3b6a11530c3d008
parent0901328f12e7ea3d05dc1d5b4a588e595c4bc0bc

spirv: super basic composite int support


10 files changed, 120 insertions(+), 72 deletions(-)

src/Zcu.zig+1-1
......@@ -3693,7 +3693,7 @@ pub fn errorSetBits(zcu: *const Zcu) u16 {
36933693 const target = zcu.getTarget();
36943694
36953695 if (zcu.error_limit == 0) return 0;
3696 if (target.cpu.arch == .spirv64) {
3696 if (target.cpu.arch.isSpirV()) {
36973697 if (!std.Target.spirv.featureSetHas(target.cpu.features, .storage_push_constant16)) {
36983698 return 32;
36993699 }
src/codegen/spirv.zig+103-59
......@@ -30,6 +30,7 @@ const SpvAssembler = @import("spirv/Assembler.zig");
3030const InstMap = std.AutoHashMapUnmanaged(Air.Inst.Index, IdRef);
3131
3232pub const zig_call_abi_ver = 3;
33pub const big_int_bits = 32;
3334
3435const InternMap = std.AutoHashMapUnmanaged(struct { InternPool.Index, NavGen.Repr }, IdResult);
3536const PtrTypeMap = std.AutoHashMapUnmanaged(
......@@ -376,7 +377,7 @@ const NavGen = struct {
376377 /// The number of bits required to store the type.
377378 /// For `integer` and `float`, this is equal to `bits`.
378379 /// For `strange_integer` and `bool` this is the size of the backing integer.
379 /// For `composite_integer` this is 0 (TODO)
380 /// For `composite_integer` this is the elements count.
380381 backing_bits: u16,
381382
382383 /// Null if this type is a scalar, or the length
......@@ -579,11 +580,13 @@ const NavGen = struct {
579580 /// The backing type will be chosen as the smallest supported integer larger or equal to it in number of bits.
580581 /// The result is valid to be used with OpTypeInt.
581582 /// TODO: Should the result of this function be cached?
582 fn backingIntBits(self: *NavGen, bits: u16) ?u16 {
583 fn backingIntBits(self: *NavGen, bits: u16) struct { u16, bool } {
583584 // The backend will never be asked to compiler a 0-bit integer, so we won't have to handle those in this function.
584585 assert(bits != 0);
585586
586 if (self.spv.hasFeature(.arbitrary_precision_integers) and bits <= 32) return bits;
587 if (self.spv.hasFeature(.arbitrary_precision_integers) and bits <= 32) {
588 return .{ bits, false };
589 }
587590
588591 // We require Int8 and Int16 capabilities and benefit Int64 when available.
589592 // 32-bit integers are always supported (see spec, 2.16.1, Data rules).
......@@ -596,10 +599,11 @@ const NavGen = struct {
596599
597600 for (ints) |int| {
598601 const has_feature = if (int.feature) |feature| self.spv.hasFeature(feature) else true;
599 if (bits <= int.bits and has_feature) return int.bits;
602 if (bits <= int.bits and has_feature) return .{ int.bits, false };
600603 }
601604
602 return null;
605 // Big int
606 return .{ std.mem.alignForward(u16, bits, big_int_bits), true };
603607 }
604608
605609 /// Return the amount of bits in the largest supported integer type. This is either 32 (always supported), or 64 (if
......@@ -623,7 +627,7 @@ const NavGen = struct {
623627 return switch (scalar_ty.zigTypeTag(zcu)) {
624628 .bool => .{
625629 .bits = 1, // Doesn't matter for this class.
626 .backing_bits = self.backingIntBits(1).?,
630 .backing_bits = self.backingIntBits(1).@"0",
627631 .vector_len = vector_len,
628632 .signedness = .unsigned, // Technically, but doesn't matter for this class.
629633 .class = .bool,
......@@ -638,19 +642,16 @@ const NavGen = struct {
638642 .int => blk: {
639643 const int_info = scalar_ty.intInfo(zcu);
640644 // TODO: Maybe it's useful to also return this value.
641 const maybe_backing_bits = self.backingIntBits(int_info.bits);
645 const backing_bits, const big_int = self.backingIntBits(int_info.bits);
642646 break :blk .{
643647 .bits = int_info.bits,
644 .backing_bits = maybe_backing_bits orelse 0,
648 .backing_bits = backing_bits,
645649 .vector_len = vector_len,
646650 .signedness = int_info.signedness,
647 .class = if (maybe_backing_bits) |backing_bits|
648 if (backing_bits == int_info.bits)
649 .integer
650 else
651 .strange_integer
652 else
653 .composite_integer,
651 .class = class: {
652 if (big_int) break :class .composite_integer;
653 break :class if (backing_bits == int_info.bits) .integer else .strange_integer;
654 },
654655 };
655656 },
656657 .@"enum" => unreachable,
......@@ -659,6 +660,34 @@ const NavGen = struct {
659660 };
660661 }
661662
663 /// Checks whether the type can be directly translated to SPIR-V vectors
664 fn isSpvVector(self: *NavGen, ty: Type) bool {
665 const zcu = self.pt.zcu;
666 if (ty.zigTypeTag(zcu) != .vector) return false;
667
668 // TODO: This check must be expanded for types that can be represented
669 // as integers (enums / packed structs?) and types that are represented
670 // by multiple SPIR-V values.
671 const scalar_ty = ty.scalarType(zcu);
672 switch (scalar_ty.zigTypeTag(zcu)) {
673 .bool,
674 .int,
675 .float,
676 => {},
677 else => return false,
678 }
679
680 const elem_ty = ty.childType(zcu);
681 const len = ty.vectorLen(zcu);
682
683 if (elem_ty.isNumeric(zcu) or elem_ty.toIntern() == .bool_type) {
684 if (len > 1 and len <= 4) return true;
685 if (self.spv.hasFeature(.vector16)) return (len == 8 or len == 16);
686 }
687
688 return false;
689 }
690
662691 /// Emits a bool constant in a particular representation.
663692 fn constBool(self: *NavGen, value: bool, repr: Repr) !IdRef {
664693 return switch (repr) {
......@@ -675,14 +704,26 @@ const NavGen = struct {
675704 const scalar_ty = ty.scalarType(zcu);
676705 const int_info = scalar_ty.intInfo(zcu);
677706 // Use backing bits so that negatives are sign extended
678 const backing_bits = self.backingIntBits(int_info.bits).?; // Assertion failure means big int
707 const backing_bits, const big_int = self.backingIntBits(int_info.bits);
679708 assert(backing_bits != 0); // u0 is comptime
680709
710 const result_ty_id = try self.resolveType(scalar_ty, .indirect);
681711 const signedness: Signedness = switch (@typeInfo(@TypeOf(value))) {
682712 .int => |int| int.signedness,
683713 .comptime_int => if (value < 0) .signed else .unsigned,
684714 else => unreachable,
685715 };
716 if (@sizeOf(@TypeOf(value)) >= 4 and big_int) {
717 const value64: u64 = switch (signedness) {
718 .signed => @bitCast(@as(i64, @intCast(value))),
719 .unsigned => @as(u64, @intCast(value)),
720 };
721 assert(backing_bits == 64);
722 return self.constructComposite(result_ty_id, &.{
723 try self.constInt(.u32, @as(u32, @truncate(value64))),
724 try self.constInt(.u32, @as(u32, @truncate(value64 << 32))),
725 });
726 }
686727
687728 const final_value: spec.LiteralContextDependentNumber = blk: {
688729 if (self.spv.hasFeature(.kernel)) {
......@@ -700,18 +741,17 @@ const NavGen = struct {
700741 break :blk switch (backing_bits) {
701742 1...32 => .{ .uint32 = @truncate(truncated_value) },
702743 33...64 => .{ .uint64 = truncated_value },
703 else => unreachable, // TODO: Large integer constants
744 else => unreachable,
704745 };
705746 }
706747
707748 break :blk switch (backing_bits) {
708749 1...32 => if (signedness == .signed) .{ .int32 = @intCast(value) } else .{ .uint32 = @intCast(value) },
709750 33...64 => if (signedness == .signed) .{ .int64 = value } else .{ .uint64 = value },
710 else => unreachable, // TODO: Large integer constants
751 else => unreachable,
711752 };
712753 };
713754
714 const result_ty_id = try self.resolveType(scalar_ty, .indirect);
715755 const result_id = try self.spv.constant(result_ty_id, final_value);
716756
717757 if (!ty.isVector(zcu)) return result_id;
......@@ -949,7 +989,7 @@ const NavGen = struct {
949989 // TODO: composite int
950990 // TODO: endianness
951991 const bits: u16 = @intCast(ty.bitSize(zcu));
952 const bytes = std.mem.alignForward(u16, self.backingIntBits(bits).?, 8) / 8;
992 const bytes = std.mem.alignForward(u16, self.backingIntBits(bits).@"0", 8) / 8;
953993 var limbs: [8]u8 = undefined;
954994 @memset(&limbs, 0);
955995 val.writeToPackedMemory(ty, pt, limbs[0..bytes], 0) catch unreachable;
......@@ -1068,19 +1108,11 @@ const NavGen = struct {
10681108 const parent_ptr_id = try self.derivePtr(oac.parent.*);
10691109 const parent_ptr_ty = try oac.parent.ptrType(pt);
10701110 const result_ty_id = try self.resolveType(oac.new_ptr_ty, .direct);
1111 const child_size = oac.new_ptr_ty.childType(zcu).abiSize(zcu);
10711112
1072 if (oac.byte_offset != 0) {
1073 const child_size = oac.new_ptr_ty.childType(zcu).abiSize(zcu);
1074 if (oac.byte_offset % child_size != 0) {
1075 return self.fail("cannot perform pointer cast: '{}' to '{}'", .{
1076 parent_ptr_ty.fmt(pt),
1077 oac.new_ptr_ty.fmt(pt),
1078 });
1079 }
1080
1113 if (parent_ptr_ty.childType(zcu).isVector(zcu) and oac.byte_offset % child_size == 0) {
10811114 // Vector element ptr accesses are derived as offset_and_cast.
10821115 // We can just use OpAccessChain.
1083 assert(parent_ptr_ty.childType(zcu).zigTypeTag(zcu) == .vector);
10841116 return self.accessChain(
10851117 result_ty_id,
10861118 parent_ptr_id,
......@@ -1088,15 +1120,22 @@ const NavGen = struct {
10881120 );
10891121 }
10901122
1091 // Allow changing the pointer type child only to restructure arrays.
1092 // e.g. [3][2]T to T is fine, as is [2]T -> [2][1]T.
1093 const result_ptr_id = self.spv.allocId();
1094 try self.func.body.emit(self.spv.gpa, .OpBitcast, .{
1095 .id_result_type = result_ty_id,
1096 .id_result = result_ptr_id,
1097 .operand = parent_ptr_id,
1123 if (oac.byte_offset == 0) {
1124 // Allow changing the pointer type child only to restructure arrays.
1125 // e.g. [3][2]T to T is fine, as is [2]T -> [2][1]T.
1126 const result_ptr_id = self.spv.allocId();
1127 try self.func.body.emit(self.spv.gpa, .OpBitcast, .{
1128 .id_result_type = result_ty_id,
1129 .id_result = result_ptr_id,
1130 .operand = parent_ptr_id,
1131 });
1132 return result_ptr_id;
1133 }
1134
1135 return self.fail("cannot perform pointer cast: '{}' to '{}'", .{
1136 parent_ptr_ty.fmt(pt),
1137 oac.new_ptr_ty.fmt(pt),
10981138 });
1099 return result_ptr_id;
11001139 },
11011140 }
11021141 }
......@@ -1217,11 +1256,14 @@ const NavGen = struct {
12171256 /// actual operations (as well as store) a Zig type of a particular number of bits. To create
12181257 /// a type with an exact size, use SpvModule.intType.
12191258 fn intType(self: *NavGen, signedness: std.builtin.Signedness, bits: u16) !IdRef {
1220 const backing_bits = self.backingIntBits(bits) orelse {
1221 // TODO: Integers too big for any native type are represented as "composite integers":
1222 // An array of largestSupportedIntBits.
1223 return self.todo("Implement {s} composite int type of {} bits", .{ @tagName(signedness), bits });
1224 };
1259 const backing_bits, const big_int = self.backingIntBits(bits);
1260 if (big_int) {
1261 if (backing_bits > 64) {
1262 return self.fail("composite integers larger than 64bit aren't supported", .{});
1263 }
1264 const int_ty = try self.resolveType(.u32, .direct);
1265 return self.arrayType(backing_bits / big_int_bits, int_ty);
1266 }
12251267
12261268 // Kernel only supports unsigned ints.
12271269 if (self.spv.hasFeature(.kernel)) {
......@@ -1509,6 +1551,17 @@ const NavGen = struct {
15091551 return result_id;
15101552 }
15111553 },
1554 .vector => {
1555 const elem_ty = ty.childType(zcu);
1556 const elem_ty_id = try self.resolveType(elem_ty, repr);
1557 const len = ty.vectorLen(zcu);
1558
1559 if (self.isSpvVector(ty)) {
1560 return try self.spv.vectorType(len, elem_ty_id);
1561 } else {
1562 return try self.arrayType(len, elem_ty_id);
1563 }
1564 },
15121565 .@"fn" => switch (repr) {
15131566 .direct => {
15141567 const fn_info = zcu.typeToFunc(ty).?;
......@@ -1577,12 +1630,6 @@ const NavGen = struct {
15771630 );
15781631 return result_id;
15791632 },
1580 .vector => {
1581 const elem_ty = ty.childType(zcu);
1582 const elem_ty_id = try self.resolveType(elem_ty, repr);
1583 const len = ty.vectorLen(zcu);
1584 return self.arrayType(len, elem_ty_id);
1585 },
15861633 .@"struct" => {
15871634 const struct_type = switch (ip.indexToKey(ty.toIntern())) {
15881635 .tuple_type => |tuple| {
......@@ -3378,8 +3425,7 @@ const NavGen = struct {
33783425 const zcu = self.pt.zcu;
33793426 const ty = value.ty;
33803427 switch (info.class) {
3381 .integer, .bool, .float => return value,
3382 .composite_integer => unreachable, // TODO
3428 .composite_integer, .integer, .bool, .float => return value,
33833429 .strange_integer => switch (info.signedness) {
33843430 .unsigned => {
33853431 const mask_value = if (info.bits == 64) 0xFFFF_FFFF_FFFF_FFFF else (@as(u64, 1) << @as(u6, @intCast(info.bits))) - 1;
......@@ -5039,7 +5085,7 @@ const NavGen = struct {
50395085 const mask_id = try self.constInt(object_ty, (@as(u64, 1) << @as(u6, @intCast(field_bit_size))) - 1);
50405086 const masked = try self.buildBinary(.bit_and, shift, .{ .ty = object_ty, .value = .{ .singleton = mask_id } });
50415087 const result_id = blk: {
5042 if (self.backingIntBits(field_bit_size).? == self.backingIntBits(@intCast(object_ty.bitSize(zcu))).?)
5088 if (self.backingIntBits(field_bit_size).@"0" == self.backingIntBits(@intCast(object_ty.bitSize(zcu))).@"0")
50435089 break :blk try self.bitCast(field_int_ty, object_ty, try masked.materialize(self));
50445090 const trunc = try self.buildConvert(field_int_ty, masked);
50455091 break :blk try trunc.materialize(self);
......@@ -5063,7 +5109,7 @@ const NavGen = struct {
50635109 .{ .ty = backing_int_ty, .value = .{ .singleton = mask_id } },
50645110 );
50655111 const result_id = blk: {
5066 if (self.backingIntBits(field_bit_size).? == self.backingIntBits(@intCast(backing_int_ty.bitSize(zcu))).?)
5112 if (self.backingIntBits(field_bit_size).@"0" == self.backingIntBits(@intCast(backing_int_ty.bitSize(zcu))).@"0")
50675113 break :blk try self.bitCast(int_ty, backing_int_ty, try masked.materialize(self));
50685114 const trunc = try self.buildConvert(int_ty, masked);
50695115 break :blk try trunc.materialize(self);
......@@ -6100,17 +6146,15 @@ const NavGen = struct {
61006146 .bool, .error_set => 1,
61016147 .int => blk: {
61026148 const bits = cond_ty.intInfo(zcu).bits;
6103 const backing_bits = self.backingIntBits(bits) orelse {
6104 return self.todo("implement composite int switch", .{});
6105 };
6149 const backing_bits, const big_int = self.backingIntBits(bits);
6150 if (big_int) return self.todo("implement composite int switch", .{});
61066151 break :blk if (backing_bits <= 32) 1 else 2;
61076152 },
61086153 .@"enum" => blk: {
61096154 const int_ty = cond_ty.intTagType(zcu);
61106155 const int_info = int_ty.intInfo(zcu);
6111 const backing_bits = self.backingIntBits(int_info.bits) orelse {
6112 return self.todo("implement composite int switch", .{});
6113 };
6156 const backing_bits, const big_int = self.backingIntBits(int_info.bits);
6157 if (big_int) return self.todo("implement composite int switch", .{});
61146158 break :blk if (backing_bits <= 32) 1 else 2;
61156159 },
61166160 .pointer => blk: {
src/codegen/spirv/Module.zig+5-2
......@@ -369,8 +369,11 @@ pub fn finalize(self: *Module, a: Allocator) ![]Word {
369369 // Emit memory model
370370 const addressing_model: spec.AddressingModel = blk: {
371371 if (self.hasFeature(.shader)) {
372 assert(self.target.cpu.arch == .spirv64);
373 if (self.hasFeature(.physical_storage_buffer)) break :blk .PhysicalStorageBuffer64;
372 if (self.hasFeature(.physical_storage_buffer)) {
373 assert(self.target.cpu.arch == .spirv64);
374 break :blk .PhysicalStorageBuffer64;
375 }
376 assert(self.target.cpu.arch == .spirv);
374377 break :blk .Logical;
375378 }
376379
src/target.zig+2-1
......@@ -807,7 +807,8 @@ pub fn zigBackend(target: std.Target, use_llvm: bool) std.builtin.CompilerBacken
807807 .powerpc, .powerpcle, .powerpc64, .powerpc64le => .stage2_powerpc,
808808 .riscv64 => .stage2_riscv64,
809809 .sparc64 => .stage2_sparc64,
810 .spirv64 => .stage2_spirv64,
810 .spirv32 => if (target.os.tag == .opencl) .stage2_spirv64 else .other,
811 .spirv, .spirv64 => .stage2_spirv64,
811812 .wasm32, .wasm64 => .stage2_wasm,
812813 .x86 => .stage2_x86,
813814 .x86_64 => .stage2_x86_64,
test/cases/compile_errors/@import_zon_bad_type.zig+3-3
......@@ -117,9 +117,9 @@ export fn testMutablePointer() void {
117117// tmp.zig:37:38: note: imported here
118118// neg_inf.zon:1:1: error: expected type '?u8'
119119// tmp.zig:57:28: note: imported here
120// neg_inf.zon:1:1: error: expected type 'tmp.testNonExhaustiveEnum__enum_499'
120// neg_inf.zon:1:1: error: expected type 'tmp.testNonExhaustiveEnum__enum_501'
121121// tmp.zig:62:39: note: imported here
122// neg_inf.zon:1:1: error: expected type 'tmp.testUntaggedUnion__union_501'
122// neg_inf.zon:1:1: error: expected type 'tmp.testUntaggedUnion__union_503'
123123// tmp.zig:67:44: note: imported here
124// neg_inf.zon:1:1: error: expected type 'tmp.testTaggedUnionVoid__union_504'
124// neg_inf.zon:1:1: error: expected type 'tmp.testTaggedUnionVoid__union_506'
125125// tmp.zig:72:50: note: imported here
test/cases/compile_errors/anytype_param_requires_comptime.zig+1-1
......@@ -15,6 +15,6 @@ pub export fn entry() void {
1515// error
1616//
1717// :7:25: error: unable to resolve comptime value
18// :7:25: note: initializer of comptime-only struct 'tmp.S.foo__anon_473.C' must be comptime-known
18// :7:25: note: initializer of comptime-only struct 'tmp.S.foo__anon_475.C' must be comptime-known
1919// :4:16: note: struct requires comptime because of this field
2020// :4:16: note: types are not available at runtime
test/cases/compile_errors/bogus_method_call_on_slice.zig+1-1
......@@ -16,5 +16,5 @@ pub export fn entry2() void {
1616//
1717// :3:6: error: no field or member function named 'copy' in '[]const u8'
1818// :9:8: error: no field or member function named 'bar' in '@TypeOf(.{})'
19// :12:18: error: no field or member function named 'bar' in 'tmp.entry2__struct_477'
19// :12:18: error: no field or member function named 'bar' in 'tmp.entry2__struct_479'
2020// :12:6: note: struct declared here
test/cases/compile_errors/coerce_anon_struct.zig+1-1
......@@ -6,6 +6,6 @@ export fn foo() void {
66
77// error
88//
9// :4:16: error: expected type 'tmp.T', found 'tmp.foo__struct_466'
9// :4:16: error: expected type 'tmp.T', found 'tmp.foo__struct_468'
1010// :3:16: note: struct declared here
1111// :1:11: note: struct declared here
test/cases/compile_errors/redundant_try.zig+2-2
......@@ -44,9 +44,9 @@ comptime {
4444//
4545// :5:23: error: expected error union type, found 'comptime_int'
4646// :10:23: error: expected error union type, found '@TypeOf(.{})'
47// :15:23: error: expected error union type, found 'tmp.test2__struct_503'
47// :15:23: error: expected error union type, found 'tmp.test2__struct_505'
4848// :15:23: note: struct declared here
49// :20:27: error: expected error union type, found 'tmp.test3__struct_505'
49// :20:27: error: expected error union type, found 'tmp.test3__struct_507'
5050// :20:27: note: struct declared here
5151// :25:23: error: expected error union type, found 'struct { comptime *const [5:0]u8 = "hello" }'
5252// :31:13: error: expected error union type, found 'u32'
test/tests.zig+1-1
......@@ -145,7 +145,7 @@ const test_targets = blk: {
145145 .{
146146 .target = std.Target.Query.parse(.{
147147 .arch_os_abi = "spirv64-vulkan",
148 .cpu_features = "vulkan_v1_2+int64+float16+float64",
148 .cpu_features = "vulkan_v1_2+physical_storage_buffer+int64+float16+float64",
149149 }) catch unreachable,
150150 .use_llvm = false,
151151 .use_lld = false,