authorgravatar for alichraghi@proton.meAli Chraghi <alichraghi@proton.me> 2025-02-14 20:28:36+03:30
committergravatar for alichraghi@proton.meAli Chraghi <alichraghi@proton.me> 2025-02-18 18:07:48+03:30
log85169bbba24d7e7592a24de5af6743b34bfe5961
treef60042eb240c9f01f153d67ee0b7387701cf68f6
parent1b0c7f51ef518d0033dc4cc3fc7088746d9088ac
signaturelock-open Commit is signed but in an unrecognized format.

spirv: respect cpu features


3 files changed, 132 insertions(+), 153 deletions(-)

src/codegen/spirv.zig+56-97
......@@ -176,10 +176,10 @@ pub const Object = struct {
176176 push_constant_ptr: SpvModule.Decl.Index,
177177 } = null,
178178
179 pub fn init(gpa: Allocator) Object {
179 pub fn init(gpa: Allocator, target: std.Target) Object {
180180 return .{
181181 .gpa = gpa,
182 .spv = SpvModule.init(gpa),
182 .spv = SpvModule.init(gpa, target),
183183 };
184184 }
185185
......@@ -412,11 +412,6 @@ const NavGen = struct {
412412 self.func.deinit(self.gpa);
413413 }
414414
415 /// Return the target which we are currently compiling for.
416 pub fn getTarget(self: *NavGen) std.Target {
417 return self.pt.zcu.getTarget();
418 }
419
420415 pub fn fail(self: *NavGen, comptime format: []const u8, args: anytype) Error {
421416 @branchHint(.cold);
422417 const zcu = self.pt.zcu;
......@@ -431,12 +426,12 @@ const NavGen = struct {
431426 }
432427
433428 /// This imports the "default" extended instruction set for the target
434 /// For OpenCL, OpenCL.std.100. For Vulkan, GLSL.std.450.
429 /// For OpenCL, OpenCL.std.100. For Vulkan and OpenGL, GLSL.std.450.
435430 fn importExtendedSet(self: *NavGen) !IdResult {
436 const target = self.getTarget();
431 const target = self.spv.target;
437432 return switch (target.os.tag) {
438433 .opencl => try self.spv.importInstructionSet(.@"OpenCL.std"),
439 .vulkan => try self.spv.importInstructionSet(.@"GLSL.std.450"),
434 .vulkan, .opengl => try self.spv.importInstructionSet(.@"GLSL.std.450"),
440435 else => unreachable,
441436 };
442437 }
......@@ -546,14 +541,10 @@ const NavGen = struct {
546541 }
547542
548543 fn addFunctionDep(self: *NavGen, decl_index: SpvModule.Decl.Index, storage_class: StorageClass) !void {
549 const target = self.getTarget();
550 if (target.os.tag == .vulkan) {
551 // Shader entry point dependencies must be variables with Input or Output storage class
552 switch (storage_class) {
553 .Input, .Output => {
554 try self.func.decl_deps.put(self.spv.gpa, decl_index, {});
555 },
556 else => {},
544 if (self.spv.version.minor < 4) {
545 // Before version 1.4, the interface’s storage classes are limited to the Input and Output
546 if (storage_class == .Input or storage_class == .Output) {
547 try self.func.decl_deps.put(self.spv.gpa, decl_index, {});
557548 }
558549 } else {
559550 try self.func.decl_deps.put(self.spv.gpa, decl_index, {});
......@@ -561,11 +552,7 @@ const NavGen = struct {
561552 }
562553
563554 fn castToGeneric(self: *NavGen, type_id: IdRef, ptr_id: IdRef) !IdRef {
564 const target = self.getTarget();
565
566 if (target.os.tag == .vulkan) {
567 return ptr_id;
568 } else {
555 if (self.spv.hasFeature(.Kernel)) {
569556 const result_id = self.spv.allocId();
570557 try self.func.body.emit(self.spv.gpa, .OpPtrCastToGeneric, .{
571558 .id_result_type = type_id,
......@@ -574,6 +561,8 @@ const NavGen = struct {
574561 });
575562 return result_id;
576563 }
564
565 return ptr_id;
577566 }
578567
579568 /// Start a new SPIR-V block, Emits the label of the new block, and stores which
......@@ -596,8 +585,6 @@ const NavGen = struct {
596585 /// TODO: This probably needs an ABI-version as well (especially in combination with SPV_INTEL_arbitrary_precision_integers).
597586 /// TODO: Should the result of this function be cached?
598587 fn backingIntBits(self: *NavGen, bits: u16) ?u16 {
599 const target = self.getTarget();
600
601588 // The backend will never be asked to compiler a 0-bit integer, so we won't have to handle those in this function.
602589 assert(bits != 0);
603590
......@@ -611,14 +598,8 @@ const NavGen = struct {
611598 };
612599
613600 for (ints) |int| {
614 const has_feature = if (int.feature) |feature|
615 Target.spirv.featureSetHas(target.cpu.features, feature)
616 else
617 true;
618
619 if (bits <= int.bits and has_feature) {
620 return int.bits;
621 }
601 const has_feature = if (int.feature) |feature| self.spv.hasFeature(feature) else true;
602 if (bits <= int.bits and has_feature) return int.bits;
622603 }
623604
624605 return null;
......@@ -631,11 +612,7 @@ const NavGen = struct {
631612 /// is no way of knowing whether those are actually supported.
632613 /// TODO: Maybe this should be cached?
633614 fn largestSupportedIntBits(self: *NavGen) u16 {
634 const target = self.getTarget();
635 return if (Target.spirv.featureSetHas(target.cpu.features, .Int64))
636 64
637 else
638 32;
615 return if (self.spv.hasFeature(.Int64)) 64 else 32;
639616 }
640617
641618 /// Checks whether the type is "composite int", an integer consisting of multiple native integers. These are represented by
......@@ -648,7 +625,6 @@ const NavGen = struct {
648625 /// Checks whether the type can be directly translated to SPIR-V vectors
649626 fn isSpvVector(self: *NavGen, ty: Type) bool {
650627 const zcu = self.pt.zcu;
651 const target = self.getTarget();
652628 if (ty.zigTypeTag(zcu) != .vector) return false;
653629
654630 // TODO: This check must be expanded for types that can be represented
......@@ -664,17 +640,19 @@ const NavGen = struct {
664640 }
665641
666642 const elem_ty = ty.childType(zcu);
667
668643 const len = ty.vectorLen(zcu);
669 const is_scalar = elem_ty.isNumeric(zcu) or elem_ty.toIntern() == .bool_type;
670 const spirv_len = len > 1 and len <= 4;
671 const opencl_len = if (target.os.tag == .opencl) (len == 8 or len == 16) else false;
672 return is_scalar and (spirv_len or opencl_len);
644
645 if (elem_ty.isNumeric(zcu) or elem_ty.toIntern() == .bool_type) {
646 if (len > 1 and len <= 4) return true;
647 if (self.spv.hasFeature(.Vector16)) return (len == 8 or len == 16);
648 }
649
650 return false;
673651 }
674652
675653 fn arithmeticTypeInfo(self: *NavGen, ty: Type) ArithmeticTypeInfo {
676654 const zcu = self.pt.zcu;
677 const target = self.getTarget();
655 const target = self.spv.target;
678656 var scalar_ty = ty.scalarType(zcu);
679657 if (scalar_ty.zigTypeTag(zcu) == .@"enum") {
680658 scalar_ty = scalar_ty.intTagType(zcu);
......@@ -791,7 +769,7 @@ const NavGen = struct {
791769 /// ty must be an aggregate type.
792770 fn constructCompositeSplat(self: *NavGen, ty: Type, constituent: IdRef) !IdRef {
793771 const zcu = self.pt.zcu;
794 const n = ty.arrayLen(zcu);
772 const n: usize = @intCast(ty.arrayLen(zcu));
795773
796774 const constituents = try self.gpa.alloc(IdRef, n);
797775 defer self.gpa.free(constituents);
......@@ -817,7 +795,7 @@ const NavGen = struct {
817795
818796 const pt = self.pt;
819797 const zcu = pt.zcu;
820 const target = self.getTarget();
798 const target = self.spv.target;
821799 const result_ty_id = try self.resolveType(ty, repr);
822800 const ip = &zcu.intern_pool;
823801
......@@ -1263,11 +1241,11 @@ const NavGen = struct {
12631241 };
12641242
12651243 // Kernel only supports unsigned ints.
1266 if (self.getTarget().os.tag == .vulkan) {
1267 return self.spv.intType(signedness, backing_bits);
1244 if (self.spv.hasFeature(.Kernel)) {
1245 return self.spv.intType(.unsigned, backing_bits);
12681246 }
12691247
1270 return self.spv.intType(.unsigned, backing_bits);
1248 return self.spv.intType(signedness, backing_bits);
12711249 }
12721250
12731251 fn arrayType(self: *NavGen, len: u32, child_ty: IdRef) !IdRef {
......@@ -1436,7 +1414,7 @@ const NavGen = struct {
14361414 const zcu = pt.zcu;
14371415 const ip = &zcu.intern_pool;
14381416 log.debug("resolveType: ty = {}", .{ty.fmt(pt)});
1439 const target = self.getTarget();
1417 const target = self.spv.target;
14401418
14411419 const section = &self.spv.sections.types_globals_constants;
14421420
......@@ -1533,7 +1511,7 @@ const NavGen = struct {
15331511 return try self.arrayType(1, elem_ty_id);
15341512 } else {
15351513 const result_id = try self.arrayType(total_len, elem_ty_id);
1536 if (target.os.tag == .vulkan) {
1514 if (self.spv.hasFeature(.Shader)) {
15371515 try self.spv.decorate(result_id, .{ .ArrayStride = .{
15381516 .array_stride = @intCast(elem_ty.abiSize(zcu)),
15391517 } });
......@@ -1667,7 +1645,7 @@ const NavGen = struct {
16671645 continue;
16681646 }
16691647
1670 if (target.os.tag == .vulkan) {
1648 if (self.spv.hasFeature(.Shader)) {
16711649 try self.spv.decorateMember(result_id, index, .{ .Offset = .{
16721650 .byte_offset = @intCast(ty.structFieldOffset(field_index, zcu)),
16731651 } });
......@@ -1769,20 +1747,11 @@ const NavGen = struct {
17691747 }
17701748
17711749 fn spvStorageClass(self: *NavGen, as: std.builtin.AddressSpace) StorageClass {
1772 const target = self.getTarget();
17731750 return switch (as) {
1774 .generic => switch (target.os.tag) {
1775 .vulkan => .Function,
1776 .opencl => .Generic,
1777 else => unreachable,
1778 },
1751 .generic => if (self.spv.hasFeature(.GenericPointer)) .Generic else .Function,
17791752 .shared => .Workgroup,
17801753 .local => .Function,
1781 .global => switch (target.os.tag) {
1782 .opencl => .CrossWorkgroup,
1783 .vulkan => .PhysicalStorageBuffer,
1784 else => unreachable,
1785 },
1754 .global => if (self.spv.hasFeature(.Shader)) .PhysicalStorageBuffer else .CrossWorkgroup,
17861755 .constant => .UniformConstant,
17871756 .push_constant => .PushConstant,
17881757 .input => .Input,
......@@ -2326,7 +2295,7 @@ const NavGen = struct {
23262295 }
23272296
23282297 fn buildFma(self: *NavGen, a: Temporary, b: Temporary, c: Temporary) !Temporary {
2329 const target = self.getTarget();
2298 const target = self.spv.target;
23302299
23312300 const v = self.vectorization(.{ a, b, c });
23322301 const ops = v.operations();
......@@ -2348,7 +2317,7 @@ const NavGen = struct {
23482317 // NOTE: Vulkan's FMA instruction does *NOT* produce the right values!
23492318 // its precision guarantees do NOT match zigs and it does NOT match OpenCLs!
23502319 // it needs to be emulated!
2351 .vulkan => unreachable, // TODO: See above
2320 .vulkan, .opengl => unreachable, // TODO: See above
23522321 else => unreachable,
23532322 };
23542323
......@@ -2485,14 +2454,14 @@ const NavGen = struct {
24852454 };
24862455
24872456 fn buildUnary(self: *NavGen, op: UnaryOp, operand: Temporary) !Temporary {
2488 const target = self.getTarget();
2457 const target = self.spv.target;
24892458 const v = blk: {
24902459 const v = self.vectorization(.{operand});
24912460 break :blk switch (op) {
24922461 // TODO: These instructions don't seem to be working
24932462 // properly for LLVM-based backends on OpenCL for 8- and
24942463 // 16-component vectors.
2495 .i_abs => if (target.os.tag == .opencl and v.components() >= 8) v.unroll() else v,
2464 .i_abs => if (self.spv.hasFeature(.Vector16) and v.components() >= 8) v.unroll() else v,
24962465 else => v,
24972466 };
24982467 };
......@@ -2545,7 +2514,7 @@ const NavGen = struct {
25452514 // Note: We'll need to check these for floating point accuracy
25462515 // Vulkan does not put tight requirements on these, for correction
25472516 // we might want to emulate them at some point.
2548 .vulkan => switch (op) {
2517 .vulkan, .opengl => switch (op) {
25492518 .i_abs => 5, // SAbs
25502519 .f_abs => 4, // FAbs
25512520 .clz => unreachable, // TODO
......@@ -2615,7 +2584,7 @@ const NavGen = struct {
26152584 };
26162585
26172586 fn buildBinary(self: *NavGen, op: BinaryOp, lhs: Temporary, rhs: Temporary) !Temporary {
2618 const target = self.getTarget();
2587 const target = self.spv.target;
26192588
26202589 const v = self.vectorization(.{ lhs, rhs });
26212590 const ops = v.operations();
......@@ -2674,7 +2643,7 @@ const NavGen = struct {
26742643 .u_min => 159, // u_min
26752644 else => unreachable,
26762645 },
2677 .vulkan => switch (op) {
2646 .vulkan, .opengl => switch (op) {
26782647 .f_max => 40, // FMax
26792648 .s_max => 42, // SMax
26802649 .u_max => 41, // UMax
......@@ -2713,7 +2682,7 @@ const NavGen = struct {
27132682 ) !struct { Temporary, Temporary } {
27142683 const pt = self.pt;
27152684 const zcu = pt.zcu;
2716 const target = self.getTarget();
2685 const target = self.spv.target;
27172686 const ip = &zcu.intern_pool;
27182687
27192688 const v = lhs.vectorization(self).unify(rhs.vectorization(self));
......@@ -2756,7 +2725,7 @@ const NavGen = struct {
27562725 });
27572726 }
27582727 },
2759 .vulkan => {
2728 .vulkan, .opengl => {
27602729 // Operations return a struct{T, T}
27612730 // where T is maybe vectorized.
27622731 const op_result_ty: Type = .fromInterned(try ip.getTupleType(zcu.gpa, pt.tid, .{
......@@ -2843,7 +2812,7 @@ const NavGen = struct {
28432812
28442813 const section = &self.spv.sections.functions;
28452814
2846 const target = self.getTarget();
2815 const target = self.spv.target;
28472816
28482817 const p_error_id = self.spv.allocId();
28492818 switch (target.os.tag) {
......@@ -2866,7 +2835,7 @@ const NavGen = struct {
28662835 .id_result = self.spv.allocId(),
28672836 });
28682837 },
2869 .vulkan => {
2838 .vulkan, .opengl => {
28702839 const ptr_ptr_anyerror_ty_id = self.spv.allocId();
28712840 try self.spv.sections.types_globals_constants.emit(self.spv.gpa, .OpTypePointer, .{
28722841 .id_result = ptr_ptr_anyerror_ty_id,
......@@ -2967,7 +2936,7 @@ const NavGen = struct {
29672936 defer self.gpa.free(test_name);
29682937
29692938 const execution_mode: spec.ExecutionModel = switch (target.os.tag) {
2970 .vulkan => .GLCompute,
2939 .vulkan, .opengl => .GLCompute,
29712940 .opencl => .Kernel,
29722941 else => unreachable,
29732942 };
......@@ -3670,7 +3639,6 @@ const NavGen = struct {
36703639 }
36713640
36723641 fn abs(self: *NavGen, result_ty: Type, value: Temporary) !Temporary {
3673 const target = self.getTarget();
36743642 const operand_info = self.arithmeticTypeInfo(value.ty);
36753643
36763644 switch (operand_info.class) {
......@@ -3682,7 +3650,7 @@ const NavGen = struct {
36823650 // depending on the result type. Do that when
36833651 // bitCast is implemented for vectors.
36843652 // This is only relevant for Vulkan
3685 assert(target.os.tag != .vulkan); // TODO
3653 assert(self.spv.hasFeature(.Kernel)); // TODO
36863654
36873655 return try self.normalize(abs_value, self.arithmeticTypeInfo(result_ty));
36883656 },
......@@ -3756,7 +3724,6 @@ const NavGen = struct {
37563724 }
37573725
37583726 fn airMulOverflow(self: *NavGen, inst: Air.Inst.Index) !?IdRef {
3759 const target = self.getTarget();
37603727 const pt = self.pt;
37613728
37623729 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -3780,7 +3747,7 @@ const NavGen = struct {
37803747 // - Additionally, if info.bits != 32, we'll have to check the high bits
37813748 // of the result too.
37823749
3783 const largest_int_bits: u16 = if (Target.spirv.featureSetHas(target.cpu.features, .Int64)) 64 else 32;
3750 const largest_int_bits = self.largestSupportedIntBits();
37843751 // If non-null, the number of bits that the multiplication should be performed in. If
37853752 // null, we have to use wide multiplication.
37863753 const maybe_op_ty_bits: ?u16 = switch (info.bits) {
......@@ -3989,7 +3956,6 @@ const NavGen = struct {
39893956 if (self.liveness.isUnused(inst)) return null;
39903957
39913958 const zcu = self.pt.zcu;
3992 const target = self.getTarget();
39933959 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
39943960 const operand = try self.temporary(ty_op.operand);
39953961
......@@ -4002,10 +3968,7 @@ const NavGen = struct {
40023968 .float, .bool => unreachable,
40033969 }
40043970
4005 switch (target.os.tag) {
4006 .vulkan => unreachable, // TODO
4007 else => {},
4008 }
3971 assert(self.spv.hasFeature(.Kernel)); // TODO
40093972
40103973 const count = try self.buildUnary(op, operand);
40113974
......@@ -4241,23 +4204,22 @@ const NavGen = struct {
42414204 defer self.gpa.free(ids);
42424205
42434206 const result_id = self.spv.allocId();
4244 const target = self.getTarget();
4245 switch (target.os.tag) {
4246 .opencl => try self.func.body.emit(self.spv.gpa, .OpInBoundsPtrAccessChain, .{
4207 if (self.spv.hasFeature(.Kernel)) {
4208 try self.func.body.emit(self.spv.gpa, .OpInBoundsPtrAccessChain, .{
42474209 .id_result_type = result_ty_id,
42484210 .id_result = result_id,
42494211 .base = base,
42504212 .element = element,
42514213 .indexes = ids,
4252 }),
4253 .vulkan => try self.func.body.emit(self.spv.gpa, .OpPtrAccessChain, .{
4214 });
4215 } else {
4216 try self.func.body.emit(self.spv.gpa, .OpPtrAccessChain, .{
42544217 .id_result_type = result_ty_id,
42554218 .id_result = result_id,
42564219 .base = base,
42574220 .element = element,
42584221 .indexes = ids,
4259 }),
4260 else => unreachable,
4222 });
42614223 }
42624224 return result_id;
42634225 }
......@@ -5328,10 +5290,7 @@ const NavGen = struct {
53285290 .initializer = options.initializer,
53295291 });
53305292
5331 const target = self.getTarget();
5332 if (target.os.tag == .vulkan) {
5333 return var_id;
5334 }
5293 if (self.spv.hasFeature(.Shader)) return var_id;
53355294
53365295 switch (options.storage_class) {
53375296 .Generic => {
......@@ -6204,7 +6163,7 @@ const NavGen = struct {
62046163 fn airSwitchBr(self: *NavGen, inst: Air.Inst.Index) !void {
62056164 const pt = self.pt;
62066165 const zcu = pt.zcu;
6207 const target = self.getTarget();
6166 const target = self.spv.target;
62086167 const switch_br = self.air.unwrapSwitch(inst);
62096168 const cond_ty = self.typeOf(switch_br.operand);
62106169 const cond = try self.resolve(switch_br.operand);
src/codegen/spirv/Module.zig+27-13
......@@ -118,6 +118,12 @@ gpa: Allocator,
118118/// Arena for things that need to live for the length of this program.
119119arena: std.heap.ArenaAllocator,
120120
121/// Target info
122target: std.Target,
123
124/// The target SPIR-V version
125version: spec.Version,
126
121127/// Module layout, according to SPIR-V Spec section 2.4, "Logical Layout of a Module".
122128sections: struct {
123129 /// Capability instructions
......@@ -196,10 +202,23 @@ entry_points: std.ArrayListUnmanaged(EntryPoint) = .empty,
196202/// The list of extended instruction sets that should be imported.
197203extended_instruction_set: std.AutoHashMapUnmanaged(spec.InstructionSet, IdRef) = .empty,
198204
199pub fn init(gpa: Allocator) Module {
205pub fn init(gpa: Allocator, target: std.Target) Module {
206 const version_minor: u8 = blk: {
207 // Prefer higher versions
208 if (std.Target.spirv.featureSetHas(target.cpu.features, .v1_6)) break :blk 6;
209 if (std.Target.spirv.featureSetHas(target.cpu.features, .v1_5)) break :blk 5;
210 if (std.Target.spirv.featureSetHas(target.cpu.features, .v1_4)) break :blk 4;
211 if (std.Target.spirv.featureSetHas(target.cpu.features, .v1_3)) break :blk 3;
212 if (std.Target.spirv.featureSetHas(target.cpu.features, .v1_2)) break :blk 2;
213 if (std.Target.spirv.featureSetHas(target.cpu.features, .v1_1)) break :blk 1;
214 break :blk 0;
215 };
216
200217 return .{
201218 .gpa = gpa,
202219 .arena = std.heap.ArenaAllocator.init(gpa),
220 .target = target,
221 .version = .{ .major = 1, .minor = version_minor },
203222 .next_result_id = 1, // 0 is an invalid SPIR-V result id, so start counting at 1.
204223 };
205224}
......@@ -263,6 +282,10 @@ pub fn idBound(self: Module) Word {
263282 return self.next_result_id;
264283}
265284
285pub fn hasFeature(self: *Module, feature: std.Target.spirv.Feature) bool {
286 return std.Target.spirv.featureSetHas(self.target.cpu.features, feature);
287}
288
266289fn addEntryPointDeps(
267290 self: *Module,
268291 decl_index: Decl.Index,
......@@ -315,7 +338,7 @@ fn entryPoints(self: *Module) !Section {
315338 return entry_points;
316339}
317340
318pub fn finalize(self: *Module, a: Allocator, target: std.Target) ![]Word {
341pub fn finalize(self: *Module, a: Allocator) ![]Word {
319342 // See SPIR-V Spec section 2.3, "Physical Layout of a SPIR-V Module and Instruction"
320343 // TODO: Audit calls to allocId() in this function to make it idempotent.
321344
......@@ -324,16 +347,7 @@ pub fn finalize(self: *Module, a: Allocator, target: std.Target) ![]Word {
324347
325348 const header = [_]Word{
326349 spec.magic_number,
327 // TODO: From cpu features
328 spec.Version.toWord(.{
329 .major = 1,
330 .minor = switch (target.os.tag) {
331 // Emit SPIR-V 1.3 for now. This is the highest version that Vulkan 1.1 supports.
332 .vulkan => 3,
333 // Emit SPIR-V 1.4 for now. This is the highest version that Intel's CPU OpenCL supports.
334 else => 4,
335 },
336 }),
350 self.version.toWord(),
337351 spec.zig_generator_id,
338352 self.idBound(),
339353 0, // Schema (currently reserved for future use)
......@@ -342,7 +356,7 @@ pub fn finalize(self: *Module, a: Allocator, target: std.Target) ![]Word {
342356 var source = Section{};
343357 defer source.deinit(self.gpa);
344358 try self.sections.debug_strings.emit(self.gpa, .OpSource, .{
345 .source_language = .Unknown,
359 .source_language = .Zig,
346360 .version = 0,
347361 // We cannot emit these because the Khronos translator does not parse this instruction
348362 // correctly.
src/link/SpirV.zig+49-43
......@@ -75,7 +75,7 @@ pub fn createEmpty(
7575 .disable_lld_caching = options.disable_lld_caching,
7676 .build_id = options.build_id,
7777 },
78 .object = codegen.Object.init(gpa),
78 .object = codegen.Object.init(gpa, comp.getTarget()),
7979 };
8080 errdefer self.deinit();
8181
......@@ -172,7 +172,7 @@ pub fn updateExports(
172172 const spv_decl_index = try self.object.resolveNav(zcu, nav_index);
173173 const cc = Type.fromInterned(nav_ty).fnCallingConvention(zcu);
174174 const execution_model: spec.ExecutionModel = switch (target.os.tag) {
175 .vulkan => switch (cc) {
175 .vulkan, .opengl => switch (cc) {
176176 .spirv_vertex => .Vertex,
177177 .spirv_fragment => .Fragment,
178178 .spirv_kernel => .GLCompute,
......@@ -231,10 +231,9 @@ pub fn flushModule(
231231 const spv = &self.object.spv;
232232 const diags = &comp.link_diags;
233233 const gpa = comp.gpa;
234 const target = comp.getTarget();
235234
236 try writeCapabilities(spv, target);
237 try writeMemoryModel(spv, target);
235 try writeCapabilities(spv);
236 try writeMemoryModel(spv);
238237
239238 // We need to export the list of error names somewhere so that we can pretty-print them in the
240239 // executor. This is not really an important thing though, so we can just dump it in any old
......@@ -269,7 +268,7 @@ pub fn flushModule(
269268 .extension = error_info.items,
270269 });
271270
272 const module = try spv.finalize(arena, target);
271 const module = try spv.finalize(arena);
273272 errdefer arena.free(module);
274273
275274 const linked_module = self.linkModule(arena, module, sub_prog_node) catch |err| switch (err) {
......@@ -299,56 +298,63 @@ fn linkModule(self: *SpirV, a: Allocator, module: []Word, progress: std.Progress
299298 return binary.finalize(a);
300299}
301300
302fn writeCapabilities(spv: *SpvModule, target: std.Target) !void {
303 const gpa = spv.gpa;
304 // TODO: Integrate with a hypothetical feature system
305 const caps: []const spec.Capability = switch (target.os.tag) {
306 .opencl => &.{ .Kernel, .Addresses, .Int8, .Int16, .Int64, .Float64, .Float16, .Vector16, .GenericPointer },
307 .vulkan => &.{ .Shader, .PhysicalStorageBufferAddresses, .Int8, .Int16, .Int64, .Float64, .Float16, .VariablePointers, .VariablePointersStorageBuffer },
308 else => unreachable,
309 };
301fn writeCapabilities(spv: *SpvModule) !void {
302 var caps: std.ArrayList(spec.Capability) = .init(spv.gpa);
303 var extensions: std.ArrayList([]const u8) = .init(spv.gpa);
304 defer {
305 caps.deinit();
306 extensions.deinit();
307 }
310308
311 for (caps) |cap| {
312 try spv.sections.capabilities.emit(gpa, .OpCapability, .{
309 // Currently all spirv target features name are mapped to a Capability or an Extension.
310 // Except for versions which we ignore.
311 for (std.Target.spirv.all_features, 0..) |_, i| {
312 if (spv.target.cpu.features.isEnabled(@intCast(i))) {
313 const feature: std.Target.spirv.Feature = @enumFromInt(i);
314 const name = @tagName(feature);
315 if (std.meta.stringToEnum(spec.Capability, name)) |cap| {
316 try caps.append(cap);
317 } else if (std.mem.startsWith(u8, name, "SPV_")) {
318 try extensions.append(name);
319 }
320 }
321 }
322
323 for (caps.items) |cap| {
324 try spv.sections.capabilities.emit(spv.gpa, .OpCapability, .{
313325 .capability = cap,
314326 });
315327 }
316328
317 switch (target.os.tag) {
318 .vulkan => {
319 try spv.sections.extensions.emit(gpa, .OpExtension, .{
320 .name = "SPV_KHR_physical_storage_buffer",
321 });
322 },
323 else => {},
329 for (extensions.items) |ext| {
330 try spv.sections.extensions.emit(spv.gpa, .OpExtension, .{ .name = ext });
324331 }
325332}
326333
327fn writeMemoryModel(spv: *SpvModule, target: std.Target) !void {
328 const gpa = spv.gpa;
334fn writeMemoryModel(spv: *SpvModule) !void {
335 const addressing_model: spec.AddressingModel = blk: {
336 if (spv.hasFeature(.Shader)) {
337 break :blk switch (spv.target.cpu.arch) {
338 .spirv32 => .Logical, // TODO: I don't think this will ever be implemented.
339 .spirv64 => .PhysicalStorageBuffer64,
340 else => unreachable,
341 };
342 } else if (spv.hasFeature(.Kernel)) {
343 break :blk switch (spv.target.cpu.arch) {
344 .spirv32 => .Physical32,
345 .spirv64 => .Physical64,
346 else => unreachable,
347 };
348 }
329349
330 const addressing_model: spec.AddressingModel = switch (target.os.tag) {
331 .opencl => switch (target.cpu.arch) {
332 .spirv32 => .Physical32,
333 .spirv64 => .Physical64,
334 else => unreachable,
335 },
336 .opengl, .vulkan => switch (target.cpu.arch) {
337 .spirv32 => .Logical, // TODO: I don't think this will ever be implemented.
338 .spirv64 => .PhysicalStorageBuffer64,
339 else => unreachable,
340 },
341 else => unreachable,
350 unreachable;
342351 };
343
344 const memory_model: spec.MemoryModel = switch (target.os.tag) {
352 const memory_model: spec.MemoryModel = switch (spv.target.os.tag) {
345353 .opencl => .OpenCL,
346 .opengl => .GLSL450,
347 .vulkan => .GLSL450,
354 .vulkan, .opengl => .GLSL450,
348355 else => unreachable,
349356 };
350
351 try spv.sections.memory_model.emit(gpa, .OpMemoryModel, .{
357 try spv.sections.memory_model.emit(spv.gpa, .OpMemoryModel, .{
352358 .addressing_model = addressing_model,
353359 .memory_model = memory_model,
354360 });