From de6df2bc12c1cec81bb3c562a9395098c92d8239 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 01:04:02 +0200 Subject: SPIR-V: Restructure codegen a bit --- src/codegen/spirv.zig | 64 +++++++++++++++++++++++++++++++-------------------- src/link/SpirV.zig | 36 +++++++++++++++++++++++------ 2 files changed, 68 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 077e71d4e1..9ceaf107d8 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -6,6 +6,7 @@ const spec = @import("spirv/spec.zig"); const Module = @import("../Module.zig"); const Decl = Module.Decl; const Type = @import("../type.zig").Type; +const LazySrcLoc = Module.LazySrcLoc; pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage); @@ -15,30 +16,24 @@ pub fn writeInstruction(code: *std.ArrayList(u32), instr: spec.Opcode, args: []c try code.appendSlice(args); } +/// This structure represents a SPIR-V binary module being compiled, and keeps track of relevant information +/// such as code for the different logical sections, and the next result-id. pub const SPIRVModule = struct { - next_result_id: u32 = 0, - - target: std.Target, - - types: TypeMap, - + next_result_id: u32, types_and_globals: std.ArrayList(u32), fn_decls: std.ArrayList(u32), - pub fn init(target: std.Target, allocator: *Allocator) SPIRVModule { + pub fn init(allocator: *Allocator) SPIRVModule { return .{ - .target = target, - .types = TypeMap.init(allocator), + .next_result_id = 0, .types_and_globals = std.ArrayList(u32).init(allocator), .fn_decls = std.ArrayList(u32).init(allocator), }; } pub fn deinit(self: *SPIRVModule) void { - self.fn_decls.deinit(); self.types_and_globals.deinit(); - self.types.deinit(); - self.* = undefined; + self.fn_decls.deinit(); } pub fn allocResultId(self: *SPIRVModule) u32 { @@ -49,21 +44,40 @@ pub const SPIRVModule = struct { pub fn resultIdBound(self: *SPIRVModule) u32 { return self.next_result_id; } +}; + +/// This structure is used to compile a declaration, and contains all relevant meta-information to deal with that. +pub const DeclGen = struct { + module: *Module, + spv: *SPIRVModule, + + types: TypeMap, + + decl: *Decl, + error_msg: ?*Module.ErrorMsg, + + fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } { + @setCold(true); + const src_loc = src.toSrcLocWithDecl(self.decl); + self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args); + return error.AnalysisFail; + } - pub fn getOrGenType(self: *SPIRVModule, t: Type) !u32 { + pub fn getOrGenType(self: *DeclGen, t: Type) !u32 { // We can't use getOrPut here so we can recursively generate types. if (self.types.get(t)) |already_generated| { return already_generated; } - const result = self.allocResultId(); + const result = self.spv.allocResultId(); switch (t.zigTypeTag()) { - .Void => try writeInstruction(&self.types_and_globals, .OpTypeVoid, &[_]u32{ result }), - .Bool => try writeInstruction(&self.types_and_globals, .OpTypeBool, &[_]u32{ result }), + .Void => try writeInstruction(&self.spv.types_and_globals, .OpTypeVoid, &[_]u32{ result }), + .Bool => try writeInstruction(&self.spv.types_and_globals, .OpTypeBool, &[_]u32{ result }), .Int => { - const int_info = t.intInfo(self.target); - try writeInstruction(&self.types_and_globals, .OpTypeInt, &[_]u32{ + const int_info = t.intInfo(self.module.getTarget()); + // TODO: Capabilities. + try writeInstruction(&self.spv.types_and_globals, .OpTypeInt, &[_]u32{ result, int_info.bits, switch (int_info.signedness) { @@ -72,8 +86,8 @@ pub const SPIRVModule = struct { }, }); }, - // TODO: Verify that floatBits() will be correct. - .Float => try writeInstruction(&self.types_and_globals, .OpTypeFloat, &[_]u32{ result, t.floatBits(self.target) }), + // TODO: Capabilities. + .Float => try writeInstruction(&self.spv.types_and_globals, .OpTypeFloat, &[_]u32{ result, t.floatBits(self.module.getTarget()) }), .Null, .Undefined, .EnumLiteral, @@ -84,23 +98,23 @@ pub const SPIRVModule = struct { .BoundFn => unreachable, // this type will be deleted from the language. - else => return error.TODO, + else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type with tag {}", .{ tag }), } try self.types.put(t, result); return result; } - pub fn gen(self: *SPIRVModule, decl: *Decl) !void { - const typed_value = decl.typed_value.most_recent.typed_value; + pub fn gen(self: *DeclGen) !void { + const typed_value = self.decl.typed_value.most_recent.typed_value; switch (typed_value.ty.zigTypeTag()) { .Fn => { - log.debug("Generating code for function '{s}'", .{ std.mem.spanZ(decl.name) }); + log.debug("Generating code for function '{s}'", .{ std.mem.spanZ(self.decl.name) }); _ = try self.getOrGenType(typed_value.ty.fnReturnType()); }, - else => return error.TODO, + else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: generate decl with tag {}", .{ tag }), } } }; diff --git a/src/link/SpirV.zig b/src/link/SpirV.zig index 95c747c170..8d5feafa5a 100644 --- a/src/link/SpirV.zig +++ b/src/link/SpirV.zig @@ -118,8 +118,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { const module = self.base.options.module.?; const target = comp.getTarget(); - var spirv_module = codegen.SPIRVModule.init(target, self.base.allocator); - defer spirv_module.deinit(); + var spv = codegen.SPIRVModule.init(self.base.allocator); + defer spv.deinit(); // Allocate an ID for every declaration before generating code, // so that we can access them before processing them. @@ -132,19 +132,41 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { if (decl.typed_value != .most_recent) continue; - decl.fn_link.spirv.id = spirv_module.allocResultId(); + decl.fn_link.spirv.id = spv.allocResultId(); log.debug("Allocating id {} to '{s}'", .{ decl.fn_link.spirv.id, std.mem.spanZ(decl.name) }); } } // Now, actually generate the code for all declarations. { + // We are just going to re-use this same DeclGen for every Decl, and we are just going to + // change the decl. Otherwise, we would have to keep a separate `types`, and re-construct this + // structure every time. + var decl_gen = codegen.DeclGen{ + .module = module, + .spv = &spv, + .types = codegen.TypeMap.init(self.base.allocator), + .decl = undefined, + .error_msg = undefined, + }; + + defer decl_gen.types.deinit(); + for (module.decl_table.items()) |entry| { const decl = entry.value; if (decl.typed_value != .most_recent) continue; - try spirv_module.gen(decl); + decl_gen.decl = decl; + decl_gen.error_msg = null; + + decl_gen.gen() catch |err| switch (err) { + error.AnalysisFail => { + try module.failed_decls.put(module.gpa, decl, decl_gen.error_msg.?); + return; + }, + else => |e| return e, + }; } } @@ -155,7 +177,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { spec.magic_number, (spec.version.major << 16) | (spec.version.minor << 8), 0, // TODO: Register Zig compiler magic number. - spirv_module.resultIdBound(), // ID bound. + spv.resultIdBound(), // ID bound. 0, // Schema (currently reserved for future use in the SPIR-V spec). }); @@ -166,8 +188,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { // follows the SPIR-V logical module format! var all_buffers = [_]std.os.iovec_const{ wordsToIovConst(binary.items), - wordsToIovConst(spirv_module.types_and_globals.items), - wordsToIovConst(spirv_module.fn_decls.items), + wordsToIovConst(spv.types_and_globals.items), + wordsToIovConst(spv.fn_decls.items), }; const file = self.base.file.?; -- cgit v1.2.3 From 458c338aeb0ce72e772c19efcfc633f908ee91b3 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 01:38:39 +0200 Subject: SPIR-V: Compute backing integer bits --- src/codegen/spirv.zig | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 9ceaf107d8..fd153533c8 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -2,6 +2,8 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const log = std.log.scoped(.codegen); +const Target = std.Target; + const spec = @import("spirv/spec.zig"); const Module = @import("../Module.zig"); const Decl = Module.Decl; @@ -63,6 +65,43 @@ pub const DeclGen = struct { return error.AnalysisFail; } + /// SPIR-V requires enabling specific integer sizes through capabilities, and so if they are not enabled, we need + /// to emulate them in other instructions/types. This function returns, given an integer bit width (signed or unsigned, sign + /// included), the width of the underlying type which represents it, given the enabled features for the current target. + /// If the result is `null`, the largest type the target platform supports natively is not able to perform computations using + /// that size. In this case, multiple elements of the largest type should be used. + /// The backing type will be chosen as the smallest supported integer larger or equal to it in number of bits. + /// The result is valid to be used with OpTypeInt. + /// TODO: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits). + /// TODO: This probably needs an ABI-version as well (especially in combination with SPV_INTEL_arbitrary_precision_integers). + fn backingIntBits(self: *DeclGen, bits: u32) ?u32 { + // TODO: Figure out what to do with u0/i0. + std.debug.assert(bits != 0); + + const target = self.module.getTarget(); + + // 8, 16 and 64-bit integers require the Int8, Int16 and Inr64 capabilities respectively. + const ints = [_]struct{ bits: u32, feature: ?Target.spirv.Feature } { + .{ .bits = 8, .feature = .Int8 }, + .{ .bits = 16, .feature = .Int16 }, + .{ .bits = 32, .feature = null }, + .{ .bits = 64, .feature = .Int64 }, + }; + + for (ints) |int| { + const has_feature = if (int.feature) |feature| + Target.spirv.featureSetHas(target.cpu.features, feature) + else + true; + + if (bits <= int.bits and has_feature) { + return int.bits; + } + } + + return null; + } + pub fn getOrGenType(self: *DeclGen, t: Type) !u32 { // We can't use getOrPut here so we can recursively generate types. if (self.types.get(t)) |already_generated| { @@ -76,10 +115,12 @@ pub const DeclGen = struct { .Bool => try writeInstruction(&self.spv.types_and_globals, .OpTypeBool, &[_]u32{ result }), .Int => { const int_info = t.intInfo(self.module.getTarget()); - // TODO: Capabilities. + const backing_bits = self.backingIntBits(int_info.bits) orelse + return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement fallback for integer of {} bits", .{ int_info.bits }); + try writeInstruction(&self.spv.types_and_globals, .OpTypeInt, &[_]u32{ result, - int_info.bits, + backing_bits, switch (int_info.signedness) { .unsigned => 0, .signed => 1, -- cgit v1.2.3 From 38cdfebad3889853e5393b9f7b63e3c85e9d793f Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 02:22:12 +0200 Subject: SPIR-V: Function prototype generation --- src/codegen/spirv.zig | 85 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 60 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index fd153533c8..076cce4a89 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -12,9 +12,13 @@ const LazySrcLoc = Module.LazySrcLoc; pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage); -pub fn writeInstruction(code: *std.ArrayList(u32), instr: spec.Opcode, args: []const u32) !void { - const word_count = @intCast(u32, args.len + 1); - try code.append((word_count << 16) | @enumToInt(instr)); +pub fn writeOpcode(code: *std.ArrayList(u32), opcode: spec.Opcode, arg_count: u32) !void { + const word_count = arg_count + 1; + try code.append((word_count << 16) | @enumToInt(opcode)); +} + +pub fn writeInstruction(code: *std.ArrayList(u32), opcode: spec.Opcode, args: []const u32) !void { + try writeOpcode(code, opcode, @intCast(u32, args.len)); try code.appendSlice(args); } @@ -58,7 +62,12 @@ pub const DeclGen = struct { decl: *Decl, error_msg: ?*Module.ErrorMsg, - fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } { + const Error = error{ + AnalysisFail, + OutOfMemory + }; + + fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) Error { @setCold(true); const src_loc = src.toSrcLocWithDecl(self.decl); self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args); @@ -102,24 +111,25 @@ pub const DeclGen = struct { return null; } - pub fn getOrGenType(self: *DeclGen, t: Type) !u32 { + fn getOrGenType(self: *DeclGen, ty: Type) Error!u32 { // We can't use getOrPut here so we can recursively generate types. - if (self.types.get(t)) |already_generated| { + if (self.types.get(ty)) |already_generated| { return already_generated; } - const result = self.spv.allocResultId(); + const code = &self.spv.types_and_globals; + const result_id = self.spv.allocResultId(); - switch (t.zigTypeTag()) { - .Void => try writeInstruction(&self.spv.types_and_globals, .OpTypeVoid, &[_]u32{ result }), - .Bool => try writeInstruction(&self.spv.types_and_globals, .OpTypeBool, &[_]u32{ result }), + switch (ty.zigTypeTag()) { + .Void => try writeInstruction(code, .OpTypeVoid, &[_]u32{ result_id }), + .Bool => try writeInstruction(code, .OpTypeBool, &[_]u32{ result_id }), .Int => { - const int_info = t.intInfo(self.module.getTarget()); + const int_info = ty.intInfo(self.module.getTarget()); const backing_bits = self.backingIntBits(int_info.bits) orelse return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement fallback for integer of {} bits", .{ int_info.bits }); - try writeInstruction(&self.spv.types_and_globals, .OpTypeInt, &[_]u32{ - result, + try writeInstruction(code, .OpTypeInt, &[_]u32{ + result_id, backing_bits, switch (int_info.signedness) { .unsigned => 0, @@ -128,7 +138,34 @@ pub const DeclGen = struct { }); }, // TODO: Capabilities. - .Float => try writeInstruction(&self.spv.types_and_globals, .OpTypeFloat, &[_]u32{ result, t.floatBits(self.module.getTarget()) }), + .Float => try writeInstruction(code, .OpTypeFloat, &[_]u32{ result_id, ty.floatBits(self.module.getTarget()) }), + .Fn => { + // We only support zig-calling-convention functions, no varargs. + if (ty.fnCallingConvention() != .Unspecified) + return self.fail(.{.node_offset = 0}, "Invalid calling convention for SPIR-V", .{}); + if (ty.fnIsVarArgs()) + return self.fail(.{.node_offset = 0}, "VarArgs are not supported for SPIR-V", .{}); + + // In order to avoid a temporary here, first generate all the required types and then simply look them up + // when generating the function type. + const params = ty.fnParamLen(); + var i: usize = 0; + while (i < params) : (i += 1) { + _ = try self.getOrGenType(ty.fnParamType(i)); + } + + const return_type_id = try self.getOrGenType(ty.fnReturnType()); + + // result id + result type id + parameter type ids. + try writeOpcode(code, .OpTypeFunction, 2 + @intCast(u32, ty.fnParamLen()) ); + try code.appendSlice(&.{ result_id, return_type_id }); + + i = 0; + while (i < params) : (i += 1) { + const param_type_id = self.types.get(ty.fnParamType(i)).?; + try code.append(param_type_id); + } + }, .Null, .Undefined, .EnumLiteral, @@ -139,23 +176,21 @@ pub const DeclGen = struct { .BoundFn => unreachable, // this type will be deleted from the language. - else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type with tag {}", .{ tag }), + else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type {}", .{ tag }), } - try self.types.put(t, result); - return result; + try self.types.put(ty, result_id); + return result_id; } pub fn gen(self: *DeclGen) !void { - const typed_value = self.decl.typed_value.most_recent.typed_value; - - switch (typed_value.ty.zigTypeTag()) { - .Fn => { - log.debug("Generating code for function '{s}'", .{ std.mem.spanZ(self.decl.name) }); + const tv = self.decl.typed_value.most_recent.typed_value; - _ = try self.getOrGenType(typed_value.ty.fnReturnType()); - }, - else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: generate decl with tag {}", .{ tag }), + if (tv.val.castTag(.function)) |func_payload| { + std.debug.assert(tv.ty.zigTypeTag() == .Fn); + _ = try self.getOrGenType(tv.ty); + } else { + return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: generate decl type {}", .{ tv.ty.zigTypeTag() }); } } }; -- cgit v1.2.3 From 4403f3598a97d93466c62a91cf3a5aacc6d113a6 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 02:39:58 +0200 Subject: SPIR-V: Proper floating point type generation --- src/codegen/spirv.zig | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 076cce4a89..b297b1181c 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -117,6 +117,7 @@ pub const DeclGen = struct { return already_generated; } + const target = self.module.getTarget(); const code = &self.spv.types_and_globals; const result_id = self.spv.allocResultId(); @@ -126,7 +127,7 @@ pub const DeclGen = struct { .Int => { const int_info = ty.intInfo(self.module.getTarget()); const backing_bits = self.backingIntBits(int_info.bits) orelse - return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement fallback for integer of {} bits", .{ int_info.bits }); + return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement fallback for {}", .{ ty }); try writeInstruction(code, .OpTypeInt, &[_]u32{ result_id, @@ -137,14 +138,32 @@ pub const DeclGen = struct { }, }); }, - // TODO: Capabilities. - .Float => try writeInstruction(code, .OpTypeFloat, &[_]u32{ result_id, ty.floatBits(self.module.getTarget()) }), + .Float => { + // We can (and want) not really emulate floating points with other floating point types like with the integer types, + // so if the float is not supported, just return an error. + const bits = ty.floatBits(target); + const supported = switch (bits) { + 16 => Target.spirv.featureSetHas(target.cpu.features, .Float16), + 32 => true, + 64 => Target.spirv.featureSetHas(target.cpu.features, .Float64), + else => false + }; + + if (!supported) { + return self.fail(.{.node_offset = 0}, "Floating point width of {} bits is not supported for the current SPIR-V feature set", .{ bits }); + } + + try writeInstruction(code, .OpTypeFloat, &.{ + result_id, + bits + }); + }, .Fn => { // We only support zig-calling-convention functions, no varargs. if (ty.fnCallingConvention() != .Unspecified) - return self.fail(.{.node_offset = 0}, "Invalid calling convention for SPIR-V", .{}); + return self.fail(.{.node_offset = 0}, "Unsupported calling convention for SPIR-V", .{}); if (ty.fnIsVarArgs()) - return self.fail(.{.node_offset = 0}, "VarArgs are not supported for SPIR-V", .{}); + return self.fail(.{.node_offset = 0}, "VarArgs unsupported for SPIR-V", .{}); // In order to avoid a temporary here, first generate all the required types and then simply look them up // when generating the function type. -- cgit v1.2.3 From 074cb9f1daff0f9d8c3bc5736b8990aa53eb8226 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 03:14:12 +0200 Subject: SPIR-V: OpFunction/OpFunctionEnd generation --- src/codegen/spirv.zig | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index b297b1181c..db4ddbd657 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -31,7 +31,7 @@ pub const SPIRVModule = struct { pub fn init(allocator: *Allocator) SPIRVModule { return .{ - .next_result_id = 0, + .next_result_id = 1, // 0 is an invalid SPIR-V result ID. .types_and_globals = std.ArrayList(u32).init(allocator), .fn_decls = std.ArrayList(u32).init(allocator), }; @@ -146,17 +146,14 @@ pub const DeclGen = struct { 16 => Target.spirv.featureSetHas(target.cpu.features, .Float16), 32 => true, 64 => Target.spirv.featureSetHas(target.cpu.features, .Float64), - else => false + else => false, }; if (!supported) { return self.fail(.{.node_offset = 0}, "Floating point width of {} bits is not supported for the current SPIR-V feature set", .{ bits }); } - try writeInstruction(code, .OpTypeFloat, &.{ - result_id, - bits - }); + try writeInstruction(code, .OpTypeFloat, &[_]u32{ result_id, bits }); }, .Fn => { // We only support zig-calling-convention functions, no varargs. @@ -195,7 +192,7 @@ pub const DeclGen = struct { .BoundFn => unreachable, // this type will be deleted from the language. - else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type {}", .{ tag }), + else => |tag| return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement type {}", .{ tag }), } try self.types.put(ty, result_id); @@ -203,11 +200,23 @@ pub const DeclGen = struct { } pub fn gen(self: *DeclGen) !void { + const result_id = self.decl.fn_link.spirv.id; const tv = self.decl.typed_value.most_recent.typed_value; if (tv.val.castTag(.function)) |func_payload| { std.debug.assert(tv.ty.zigTypeTag() == .Fn); - _ = try self.getOrGenType(tv.ty); + const prototype_id = try self.getOrGenType(tv.ty); + try writeInstruction(&self.spv.fn_decls, .OpFunction, &[_]u32{ + self.types.get(tv.ty.fnReturnType()).?, // This type should be generated along with the prototype. + result_id, + @bitCast(u32, spec.FunctionControl{}), // TODO: We can set inline here if the type requires it. + prototype_id, + }); + + // TODO: Parameters + // TODO: Body + + try writeInstruction(&self.spv.fn_decls, .OpFunctionEnd, &[_]u32{}); } else { return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: generate decl type {}", .{ tv.ty.zigTypeTag() }); } -- cgit v1.2.3 From da0cc732ea899d2284200faf54c3c12e8c798b7f Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 03:27:59 +0200 Subject: SPIR-V: Function parameter generation --- src/codegen/spirv.zig | 13 ++++++++++++- src/link/SpirV.zig | 5 ++++- 2 files changed, 16 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index db4ddbd657..a6b8216774 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -57,6 +57,7 @@ pub const DeclGen = struct { module: *Module, spv: *SPIRVModule, + args: std.ArrayList(u32), types: TypeMap, decl: *Decl, @@ -213,7 +214,17 @@ pub const DeclGen = struct { prototype_id, }); - // TODO: Parameters + const params = tv.ty.fnParamLen(); + var i: usize = 0; + + try self.args.ensureCapacity(params); + while (i < params) : (i += 1) { + const param_type_id = self.types.get(tv.ty.fnParamType(i)).?; + const arg_result_id = self.spv.allocResultId(); + try writeInstruction(&self.spv.fn_decls, .OpFunctionParameter, &[_]u32{ param_type_id, arg_result_id }); + self.args.appendAssumeCapacity(arg_result_id); + } + // TODO: Body try writeInstruction(&self.spv.fn_decls, .OpFunctionEnd, &[_]u32{}); diff --git a/src/link/SpirV.zig b/src/link/SpirV.zig index 8d5feafa5a..8bc0d9fe9f 100644 --- a/src/link/SpirV.zig +++ b/src/link/SpirV.zig @@ -140,23 +140,26 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { // Now, actually generate the code for all declarations. { // We are just going to re-use this same DeclGen for every Decl, and we are just going to - // change the decl. Otherwise, we would have to keep a separate `types`, and re-construct this + // change the decl. Otherwise, we would have to keep a separate `args` and `types`, and re-construct this // structure every time. var decl_gen = codegen.DeclGen{ .module = module, .spv = &spv, + .args = std.ArrayList(u32).init(self.base.allocator), .types = codegen.TypeMap.init(self.base.allocator), .decl = undefined, .error_msg = undefined, }; defer decl_gen.types.deinit(); + defer decl_gen.args.deinit(); for (module.decl_table.items()) |entry| { const decl = entry.value; if (decl.typed_value != .most_recent) continue; + decl_gen.args.items.len = 0; decl_gen.decl = decl; decl_gen.error_msg = null; -- cgit v1.2.3 From cbf5280f54509e7aa58d8fd14258274a12efeee1 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 09:43:57 +0200 Subject: SPIR-V: Some instructions + constant generation setup --- src/codegen/spirv.zig | 150 +++++++++++++++++++++++++++++++++++++++++++------- src/link/SpirV.zig | 6 +- 2 files changed, 135 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index a6b8216774..8be42627ff 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -1,16 +1,19 @@ const std = @import("std"); const Allocator = std.mem.Allocator; -const log = std.log.scoped(.codegen); - const Target = std.Target; +const log = std.log.scoped(.codegen); const spec = @import("spirv/spec.zig"); const Module = @import("../Module.zig"); const Decl = Module.Decl; const Type = @import("../type.zig").Type; +const Value = @import("../value.zig").Value; const LazySrcLoc = Module.LazySrcLoc; +const ir = @import("../ir.zig"); +const Inst = ir.Inst; pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage); +pub const ValueMap = std.AutoHashMap(*Inst, u32); pub fn writeOpcode(code: *std.ArrayList(u32), opcode: spec.Opcode, arg_count: u32) !void { const word_count = arg_count + 1; @@ -26,19 +29,19 @@ pub fn writeInstruction(code: *std.ArrayList(u32), opcode: spec.Opcode, args: [] /// such as code for the different logical sections, and the next result-id. pub const SPIRVModule = struct { next_result_id: u32, - types_and_globals: std.ArrayList(u32), + types_globals_constants: std.ArrayList(u32), fn_decls: std.ArrayList(u32), pub fn init(allocator: *Allocator) SPIRVModule { return .{ .next_result_id = 1, // 0 is an invalid SPIR-V result ID. - .types_and_globals = std.ArrayList(u32).init(allocator), + .types_globals_constants = std.ArrayList(u32).init(allocator), .fn_decls = std.ArrayList(u32).init(allocator), }; } pub fn deinit(self: *SPIRVModule) void { - self.types_and_globals.deinit(); + self.types_globals_constants.deinit(); self.fn_decls.deinit(); } @@ -58,7 +61,10 @@ pub const DeclGen = struct { spv: *SPIRVModule, args: std.ArrayList(u32), + next_arg_index: u32, + types: TypeMap, + values: ValueMap, decl: *Decl, error_msg: ?*Module.ErrorMsg, @@ -75,6 +81,14 @@ pub const DeclGen = struct { return error.AnalysisFail; } + fn resolve(self: *DeclGen, inst: *Inst) !u32 { + if (inst.value()) |val| { + return self.genConstant(inst.ty, val); + } + + return self.values.get(inst).?; // Instruction does not dominate all uses! + } + /// SPIR-V requires enabling specific integer sizes through capabilities, and so if they are not enabled, we need /// to emulate them in other instructions/types. This function returns, given an integer bit width (signed or unsigned, sign /// included), the width of the underlying type which represents it, given the enabled features for the current target. @@ -82,13 +96,16 @@ pub const DeclGen = struct { /// that size. In this case, multiple elements of the largest type should be used. /// The backing type will be chosen as the smallest supported integer larger or equal to it in number of bits. /// The result is valid to be used with OpTypeInt. + /// asserts `ty` is an integer. /// TODO: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits). /// TODO: This probably needs an ABI-version as well (especially in combination with SPV_INTEL_arbitrary_precision_integers). - fn backingIntBits(self: *DeclGen, bits: u32) ?u32 { - // TODO: Figure out what to do with u0/i0. - std.debug.assert(bits != 0); - + /// TODO: Should the result of this function be cached? + fn backingIntBits(self: *DeclGen, ty: Type) ?u32 { const target = self.module.getTarget(); + const int_info = ty.intInfo(target); + + // TODO: Figure out what to do with u0/i0. + std.debug.assert(int_info.bits != 0); // 8, 16 and 64-bit integers require the Int8, Int16 and Inr64 capabilities respectively. const ints = [_]struct{ bits: u32, feature: ?Target.spirv.Feature } { @@ -104,7 +121,7 @@ pub const DeclGen = struct { else true; - if (bits <= int.bits and has_feature) { + if (int_info.bits <= int.bits and has_feature) { return int.bits; } } @@ -112,6 +129,43 @@ pub const DeclGen = struct { return null; } + /// Return the amount of bits in the largest supported integer type. This is either 32 (always supported), or 64 (if + /// the Int64 capability is enabled). + /// Note: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits). + /// In theory that could also be used, but since the spec says that it only guarantees support up to 32-bit ints there + /// is no way of knowing whether those are actually supported. + /// TODO: Maybe this should be cached? + fn largestSupportedIntBits(self: *DeclGen) u32 { + const target = self.module.getTarget(); + return if (Target.spirv.featureSetHas(target.cpu.features, .Int64)) + 64 + else + 32; + } + + /// Generate a constant representing `val`. + /// TODO: Deduplication? + fn genConstant(self: *DeclGen, ty: Type, val: Value) Error!u32 { + const code = &self.spv.types_globals_constants; + const result_id = self.spv.allocResultId(); + const result_type_id = try self.getOrGenType(ty); + + if (val.isUndef()) { + try writeInstruction(code, .OpUndef, &[_]u32{ result_type_id, result_id }); + return result_id; + } + + switch (ty.zigTypeTag()) { + .Bool => { + const opcode: spec.Opcode = if (val.toBool()) .OpConstantTrue else .OpConstantFalse; + try writeInstruction(code, opcode, &[_]u32{ result_type_id, result_id }); + }, + else => return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: constant generation of type {s}\n", .{ ty.zigTypeTag() }), + } + + return result_id; + } + fn getOrGenType(self: *DeclGen, ty: Type) Error!u32 { // We can't use getOrPut here so we can recursively generate types. if (self.types.get(ty)) |already_generated| { @@ -119,24 +173,21 @@ pub const DeclGen = struct { } const target = self.module.getTarget(); - const code = &self.spv.types_and_globals; + const code = &self.spv.types_globals_constants; const result_id = self.spv.allocResultId(); switch (ty.zigTypeTag()) { .Void => try writeInstruction(code, .OpTypeVoid, &[_]u32{ result_id }), .Bool => try writeInstruction(code, .OpTypeBool, &[_]u32{ result_id }), .Int => { - const int_info = ty.intInfo(self.module.getTarget()); - const backing_bits = self.backingIntBits(int_info.bits) orelse + const backing_bits = self.backingIntBits(ty) orelse return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement fallback for {}", .{ ty }); + // TODO: If backing_bits != int_info.bits, a duplicate type might be generated here. try writeInstruction(code, .OpTypeInt, &[_]u32{ result_id, backing_bits, - switch (int_info.signedness) { - .unsigned => 0, - .signed => 1, - }, + @boolToInt(ty.isSignedInt()), }); }, .Float => { @@ -183,6 +234,15 @@ pub const DeclGen = struct { try code.append(param_type_id); } }, + .Vector => { + // Although not 100% the same, Zig vectors map quite neatly to SPIR-V vectors (including many integer and float operations + // which work on them), so simply use those. + // Note: SPIR-V vectors only support bools, ints and floats, so pointer vectors need to be supported another way. + // "big integers" (larger than the largest supported native type) can probably be represented by an array of vectors. + + // TODO: Vectors are not yet supported by the self-hosted compiler itself it seems. + return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement type Vector", .{}); + }, .Null, .Undefined, .EnumLiteral, @@ -193,10 +253,10 @@ pub const DeclGen = struct { .BoundFn => unreachable, // this type will be deleted from the language. - else => |tag| return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement type {}", .{ tag }), + else => |tag| return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement type {}s", .{ tag }), } - try self.types.put(ty, result_id); + try self.types.putNoClobber(ty, result_id); return result_id; } @@ -225,11 +285,61 @@ pub const DeclGen = struct { self.args.appendAssumeCapacity(arg_result_id); } - // TODO: Body + // TODO: This could probably be done in a better way... + const root_block_id = self.spv.allocResultId(); + _ = try writeInstruction(&self.spv.fn_decls, .OpLabel, &[_]u32{root_block_id}); + try self.genBody(func_payload.data.body); try writeInstruction(&self.spv.fn_decls, .OpFunctionEnd, &[_]u32{}); } else { return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: generate decl type {}", .{ tv.ty.zigTypeTag() }); } } + + fn genBody(self: *DeclGen, body: ir.Body) !void { + for (body.instructions) |inst| { + const maybe_result_id = try self.genInst(inst); + if (maybe_result_id) |result_id| + try self.values.putNoClobber(inst, result_id); + } + } + + fn genInst(self: *DeclGen, inst: *Inst) !?u32 { + return switch (inst.tag) { + .arg => self.genArg(), + // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them + // throughout the IR. + .breakpoint => null, + // TODO: What does this entail? + .dbg_stmt => null, + .ret => self.genRet(inst.castTag(.ret).?), + .retvoid => self.genRetVoid(), + .unreach => self.genUnreach(), + else => self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement inst {}", .{inst.tag}), + }; + } + + fn genArg(self: *DeclGen) u32 { + defer self.next_arg_index += 1; + return self.args.items[self.next_arg_index]; + } + + fn genRet(self: *DeclGen, inst: *Inst.UnOp) !?u32 { + const operand_id = try self.resolve(inst.operand); + // TODO: This instruction needs to be the last in a block. Is that guaranteed? + try writeInstruction(&self.spv.fn_decls, .OpReturnValue, &[_]u32{ operand_id }); + return null; + } + + fn genRetVoid(self: *DeclGen) !?u32 { + // TODO: This instruction needs to be the last in a block. Is that guaranteed? + try writeInstruction(&self.spv.fn_decls, .OpReturn, &[_]u32{}); + return null; + } + + fn genUnreach(self: *DeclGen) !?u32 { + // TODO: This instruction needs to be the last in a block. Is that guaranteed? + try writeInstruction(&self.spv.fn_decls, .OpUnreachable, &[_]u32{}); + return null; + } }; diff --git a/src/link/SpirV.zig b/src/link/SpirV.zig index 8bc0d9fe9f..96ed2d3e77 100644 --- a/src/link/SpirV.zig +++ b/src/link/SpirV.zig @@ -146,11 +146,14 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { .module = module, .spv = &spv, .args = std.ArrayList(u32).init(self.base.allocator), + .next_arg_index = undefined, .types = codegen.TypeMap.init(self.base.allocator), + .values = codegen.ValueMap.init(self.base.allocator), .decl = undefined, .error_msg = undefined, }; + defer decl_gen.values.deinit(); defer decl_gen.types.deinit(); defer decl_gen.args.deinit(); @@ -160,6 +163,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { continue; decl_gen.args.items.len = 0; + decl_gen.next_arg_index = 0; decl_gen.decl = decl; decl_gen.error_msg = null; @@ -191,7 +195,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void { // follows the SPIR-V logical module format! var all_buffers = [_]std.os.iovec_const{ wordsToIovConst(binary.items), - wordsToIovConst(spv.types_and_globals.items), + wordsToIovConst(spv.types_globals_constants.items), wordsToIovConst(spv.fn_decls.items), }; -- cgit v1.2.3 From ae2e21639a958b0bc8c085c8eac6733aaa933457 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sat, 15 May 2021 14:04:41 +0200 Subject: SPIR-V: Some initial floating point constant generation --- src/codegen/spirv.zig | 47 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 8be42627ff..f4f437a064 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -143,6 +143,13 @@ pub const DeclGen = struct { 32; } + /// Checks whether the type is "composite int", an integer consisting of multiple native integers. These are represented by + /// arrays of largestSupportedIntBits(). + /// Asserts `ty` is an integer. + fn isCompositeInt(self: *DeclGen, ty: Type) bool { + return self.backingIntBits(ty) == null; + } + /// Generate a constant representing `val`. /// TODO: Deduplication? fn genConstant(self: *DeclGen, ty: Type, val: Value) Error!u32 { @@ -160,6 +167,37 @@ pub const DeclGen = struct { const opcode: spec.Opcode = if (val.toBool()) .OpConstantTrue else .OpConstantFalse; try writeInstruction(code, opcode, &[_]u32{ result_type_id, result_id }); }, + .Float => { + // At this point we are guaranteed that the target floating point type is supported, otherwise the function + // would have exited at getOrGenType(ty). + + // f16 and f32 require one word of storage. f64 requires 2, low-order first. + + switch (val.tag()) { + .float_16 => try writeInstruction(code, .OpConstant, &[_]u32{ + result_type_id, + result_id, + @bitCast(u16, val.castTag(.float_16).?.data) + }), + .float_32 => try writeInstruction(code, .OpConstant, &[_]u32{ + result_type_id, + result_id, + @bitCast(u32, val.castTag(.float_32).?.data) + }), + .float_64 => { + const float_bits = @bitCast(u64, val.castTag(.float_64).?.data); + try writeInstruction(code, .OpConstant, &[_]u32{ + result_type_id, + result_id, + @truncate(u32, float_bits), + @truncate(u32, float_bits >> 32), + }); + }, + .float_128 => unreachable, // Filtered out in the call to getOrGenType. + // TODO: What tags do we need to handle here anyway? + else => return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: float constant generation of value {s}\n", .{ val.tag() }), + } + }, else => return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: constant generation of type {s}\n", .{ ty.zigTypeTag() }), } @@ -180,8 +218,10 @@ pub const DeclGen = struct { .Void => try writeInstruction(code, .OpTypeVoid, &[_]u32{ result_id }), .Bool => try writeInstruction(code, .OpTypeBool, &[_]u32{ result_id }), .Int => { - const backing_bits = self.backingIntBits(ty) orelse - return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement fallback for {}", .{ ty }); + const backing_bits = self.backingIntBits(ty) orelse { + // Integers too big for any native type are represented as "composite integers": An array of largestSupportedIntBits. + return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement composite ints {}", .{ ty }); + }; // TODO: If backing_bits != int_info.bits, a duplicate type might be generated here. try writeInstruction(code, .OpTypeInt, &[_]u32{ @@ -238,7 +278,7 @@ pub const DeclGen = struct { // Although not 100% the same, Zig vectors map quite neatly to SPIR-V vectors (including many integer and float operations // which work on them), so simply use those. // Note: SPIR-V vectors only support bools, ints and floats, so pointer vectors need to be supported another way. - // "big integers" (larger than the largest supported native type) can probably be represented by an array of vectors. + // "composite integers" (larger than the largest supported native type) can probably be represented by an array of vectors. // TODO: Vectors are not yet supported by the self-hosted compiler itself it seems. return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement type Vector", .{}); @@ -310,7 +350,6 @@ pub const DeclGen = struct { // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them // throughout the IR. .breakpoint => null, - // TODO: What does this entail? .dbg_stmt => null, .ret => self.genRet(inst.castTag(.ret).?), .retvoid => self.genRetVoid(), -- cgit v1.2.3 From 10678af8768a8d8cad7640837d0ec354dc8c07bc Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sun, 16 May 2021 13:09:32 +0200 Subject: SPIR-V: genBinOp setup --- src/codegen/spirv.zig | 118 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 111 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index f4f437a064..3272de47ae 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -74,6 +74,44 @@ pub const DeclGen = struct { OutOfMemory }; + /// This structure is used to return information about a type typically used for arithmetic operations. + /// These types may either be integers, floats, or a vector of these. Most scalar operations also work on vectors, + /// so we can easily represent those as arithmetic types. + /// If the type is a scalar, 'inner type' refers to the scalar type. Otherwise, if its a vector, it refers + /// to the vector's element type. + const ArithmeticTypeInfo = struct { + /// A classification of the inner type. + const Class = enum { + /// A regular, **native**, integer operation. + /// This is only returned when the backend supports this int as a native type (when + /// the relevant capability is enabled). + integer, + + /// A regular float. These are all required to be natively supported. Floating points for + /// which the relevant capability is not enabled are not emulated. + float, + + /// An integer of a 'strange' size (which' bit size is not the same as its backing type. **Note**: this + /// may **also** include power-of-2 integers for which the relevant capability is not enabled), but still + /// within the limits of the largest natively supported integer type. + strange_integer, + + /// An integer with more bits than the largest natively supported integer type. + composite_integer, + }; + + /// The number of bits in the inner type. + /// Note: this is the actual number of bits of the type, not the size of the backing integer. + bits: u32, + + /// Whether the type is a vector. + is_vector: bool, + + /// A classification of the inner type. These four scenarios + /// will all have to be handled slightly different. + class: Class, + }; + fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) Error { @setCold(true); const src_loc = src.toSrcLocWithDecl(self.decl); @@ -96,16 +134,14 @@ pub const DeclGen = struct { /// that size. In this case, multiple elements of the largest type should be used. /// The backing type will be chosen as the smallest supported integer larger or equal to it in number of bits. /// The result is valid to be used with OpTypeInt. - /// asserts `ty` is an integer. /// TODO: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits). /// TODO: This probably needs an ABI-version as well (especially in combination with SPV_INTEL_arbitrary_precision_integers). /// TODO: Should the result of this function be cached? - fn backingIntBits(self: *DeclGen, ty: Type) ?u32 { + fn backingIntBits(self: *DeclGen, bits: u32) ?u32 { const target = self.module.getTarget(); - const int_info = ty.intInfo(target); // TODO: Figure out what to do with u0/i0. - std.debug.assert(int_info.bits != 0); + std.debug.assert(bits != 0); // 8, 16 and 64-bit integers require the Int8, Int16 and Inr64 capabilities respectively. const ints = [_]struct{ bits: u32, feature: ?Target.spirv.Feature } { @@ -121,7 +157,7 @@ pub const DeclGen = struct { else true; - if (int_info.bits <= int.bits and has_feature) { + if (bits <= int.bits and has_feature) { return int.bits; } } @@ -150,6 +186,34 @@ pub const DeclGen = struct { return self.backingIntBits(ty) == null; } + fn arithmeticTypeInfo(self: *DeclGen, ty: Type) !ArithmeticTypeInfo { + const target = self.module.getTarget(); + + return switch (ty.zigTypeTag()) { + .Float => ArithmeticTypeInfo{ .bits = ty.floatBits(target), .is_vector = false, .class = .float }, + .Int => blk: { + const int_info = ty.intInfo(target); + // TODO: Maybe it's useful to also return this value. + const maybe_backing_bits = self.backingIntBits(int_info.bits); + break :blk ArithmeticTypeInfo{ + .bits = int_info.bits, + .is_vector = false, + .class = if (maybe_backing_bits) |backing_bits| + if (backing_bits == int_info.bits) + ArithmeticTypeInfo.Class.integer + else + ArithmeticTypeInfo.Class.strange_integer + else + .composite_integer + }; + }, + // As of yet, there is no vector support in the self-hosted compiler. + .Vector => self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement arithmeticTypeInfo for Vector", .{}), + // TODO: For which types is this the case? + else => self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement arithmeticTypeInfo for {}", .{ty}), + }; + } + /// Generate a constant representing `val`. /// TODO: Deduplication? fn genConstant(self: *DeclGen, ty: Type, val: Value) Error!u32 { @@ -218,7 +282,8 @@ pub const DeclGen = struct { .Void => try writeInstruction(code, .OpTypeVoid, &[_]u32{ result_id }), .Bool => try writeInstruction(code, .OpTypeBool, &[_]u32{ result_id }), .Int => { - const backing_bits = self.backingIntBits(ty) orelse { + const int_info = ty.intInfo(target); + const backing_bits = self.backingIntBits(int_info.bits) orelse { // Integers too big for any native type are represented as "composite integers": An array of largestSupportedIntBits. return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement composite ints {}", .{ ty }); }; @@ -227,7 +292,10 @@ pub const DeclGen = struct { try writeInstruction(code, .OpTypeInt, &[_]u32{ result_id, backing_bits, - @boolToInt(ty.isSignedInt()), + switch (int_info.signedness) { + .unsigned => 0, + .signed => 1, + }, }); }, .Float => { @@ -346,6 +414,7 @@ pub const DeclGen = struct { fn genInst(self: *DeclGen, inst: *Inst) !?u32 { return switch (inst.tag) { + .add => try self.genBinOp(inst.castTag(.add).?), .arg => self.genArg(), // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them // throughout the IR. @@ -358,6 +427,41 @@ pub const DeclGen = struct { }; } + fn genBinOp(self: *DeclGen, inst: *Inst.BinOp) !u32 { + // TODO: Will lhs and rhs have the same type? + const lhs_id = try self.resolve(inst.lhs); + const rhs_id = try self.resolve(inst.rhs); + + const binop_result_id = self.spv.allocResultId(); + const result_type_id = try self.getOrGenType(inst.base.ty); + + // TODO: Is the result the same as the argument types? + // This is supposed to be the case for SPIR-V. + std.debug.assert(inst.base.ty.eql(inst.lhs.ty) and inst.base.ty.eql(inst.rhs.ty)); + + // Binary operations are generally applicable to both scalar and vector operations in SPIR-V, but int and float + // versions of operations require different opcodes. + const info = try self.arithmeticTypeInfo(inst.base.ty); + + if (info.class == .composite_integer) + return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: binary operations for composite integers", .{}); + + // Fetch the integer and float opcodes for each operation. + // Doing it this way removes a bit of code clutter. + const opcodes: [2]spec.Opcode = switch (inst.base.tag) { + .add => .{.OpIAdd, .OpFAdd}, + else => unreachable, + }; + + const opcode = if (info.class == .float) opcodes[1] else opcodes[0]; + try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, binop_result_id, lhs_id, rhs_id }); + + if (info.class != .strange_integer) + return binop_result_id; + + return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: strange integer operation mask", .{}); + } + fn genArg(self: *DeclGen) u32 { defer self.next_arg_index += 1; return self.args.items[self.next_arg_index]; -- cgit v1.2.3 From 4735e95d1699c90e821655bdbe0afbb1044738ea Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sun, 16 May 2021 13:32:32 +0200 Subject: SPIR-V: More binary operations --- src/codegen/spirv.zig | 53 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 3272de47ae..c8bebbb70b 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -4,6 +4,8 @@ const Target = std.Target; const log = std.log.scoped(.codegen); const spec = @import("spirv/spec.zig"); +const Opcode = spec.Opcode; + const Module = @import("../Module.zig"); const Decl = Module.Decl; const Type = @import("../type.zig").Type; @@ -15,12 +17,12 @@ const Inst = ir.Inst; pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage); pub const ValueMap = std.AutoHashMap(*Inst, u32); -pub fn writeOpcode(code: *std.ArrayList(u32), opcode: spec.Opcode, arg_count: u32) !void { +pub fn writeOpcode(code: *std.ArrayList(u32), opcode: Opcode, arg_count: u32) !void { const word_count = arg_count + 1; try code.append((word_count << 16) | @enumToInt(opcode)); } -pub fn writeInstruction(code: *std.ArrayList(u32), opcode: spec.Opcode, args: []const u32) !void { +pub fn writeInstruction(code: *std.ArrayList(u32), opcode: Opcode, args: []const u32) !void { try writeOpcode(code, opcode, @intCast(u32, args.len)); try code.appendSlice(args); } @@ -102,11 +104,14 @@ pub const DeclGen = struct { /// The number of bits in the inner type. /// Note: this is the actual number of bits of the type, not the size of the backing integer. - bits: u32, + bits: u16, /// Whether the type is a vector. is_vector: bool, + /// Whether the inner type is signed. Only relevant for integers. + signedness: std.builtin.Signedness, + /// A classification of the inner type. These four scenarios /// will all have to be handled slightly different. class: Class, @@ -137,14 +142,14 @@ pub const DeclGen = struct { /// TODO: The extension SPV_INTEL_arbitrary_precision_integers allows any integer size (at least up to 32 bits). /// TODO: This probably needs an ABI-version as well (especially in combination with SPV_INTEL_arbitrary_precision_integers). /// TODO: Should the result of this function be cached? - fn backingIntBits(self: *DeclGen, bits: u32) ?u32 { + fn backingIntBits(self: *DeclGen, bits: u16) ?u16 { const target = self.module.getTarget(); // TODO: Figure out what to do with u0/i0. std.debug.assert(bits != 0); // 8, 16 and 64-bit integers require the Int8, Int16 and Inr64 capabilities respectively. - const ints = [_]struct{ bits: u32, feature: ?Target.spirv.Feature } { + const ints = [_]struct{ bits: u16, feature: ?Target.spirv.Feature } { .{ .bits = 8, .feature = .Int8 }, .{ .bits = 16, .feature = .Int16 }, .{ .bits = 32, .feature = null }, @@ -171,7 +176,7 @@ pub const DeclGen = struct { /// In theory that could also be used, but since the spec says that it only guarantees support up to 32-bit ints there /// is no way of knowing whether those are actually supported. /// TODO: Maybe this should be cached? - fn largestSupportedIntBits(self: *DeclGen) u32 { + fn largestSupportedIntBits(self: *DeclGen) u16 { const target = self.module.getTarget(); return if (Target.spirv.featureSetHas(target.cpu.features, .Int64)) 64 @@ -190,7 +195,12 @@ pub const DeclGen = struct { const target = self.module.getTarget(); return switch (ty.zigTypeTag()) { - .Float => ArithmeticTypeInfo{ .bits = ty.floatBits(target), .is_vector = false, .class = .float }, + .Float => ArithmeticTypeInfo{ + .bits = ty.floatBits(target), + .is_vector = false, + .signedness = .signed, // I guess technically it is. + .class = .float + }, .Int => blk: { const int_info = ty.intInfo(target); // TODO: Maybe it's useful to also return this value. @@ -198,6 +208,7 @@ pub const DeclGen = struct { break :blk ArithmeticTypeInfo{ .bits = int_info.bits, .is_vector = false, + .signedness = int_info.signedness, .class = if (maybe_backing_bits) |backing_bits| if (backing_bits == int_info.bits) ArithmeticTypeInfo.Class.integer @@ -228,7 +239,7 @@ pub const DeclGen = struct { switch (ty.zigTypeTag()) { .Bool => { - const opcode: spec.Opcode = if (val.toBool()) .OpConstantTrue else .OpConstantFalse; + const opcode: Opcode = if (val.toBool()) .OpConstantTrue else .OpConstantFalse; try writeInstruction(code, opcode, &[_]u32{ result_type_id, result_id }); }, .Float => { @@ -414,7 +425,10 @@ pub const DeclGen = struct { fn genInst(self: *DeclGen, inst: *Inst) !?u32 { return switch (inst.tag) { - .add => try self.genBinOp(inst.castTag(.add).?), + .add, .addwrap => try self.genBinOp(inst.castTag(.add).?), + .sub, .subwrap => try self.genBinOp(inst.castTag(.sub).?), + .mul, .mulwrap => try self.genBinOp(inst.castTag(.mul).?), + .div => try self.genBinOp(inst.castTag(.div).?), .arg => self.genArg(), // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them // throughout the IR. @@ -446,16 +460,27 @@ pub const DeclGen = struct { if (info.class == .composite_integer) return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: binary operations for composite integers", .{}); - // Fetch the integer and float opcodes for each operation. - // Doing it this way removes a bit of code clutter. - const opcodes: [2]spec.Opcode = switch (inst.base.tag) { - .add => .{.OpIAdd, .OpFAdd}, + const is_float = info.class == .float; + const is_signed = info.signedness == .signed; + // **Note**: All these operations must be valid for vectors of floats and integers as well! + const opcode = switch (inst.base.tag) { + // The regular integer operations are all defined for wrapping. Since theyre only relevant for integers, + // we can just switch on both cases here. + .add, .addwrap => if (is_float) Opcode.OpFAdd else Opcode.OpIAdd, + .sub, .subwrap => if (is_float) Opcode.OpFSub else Opcode.OpISub, + .mul, .mulwrap => if (is_float) Opcode.OpFMul else Opcode.OpIMul, + // TODO: Trap if divisor is 0? + // TODO: Figure out of OpSDiv for unsigned/OpUDiv for signed does anything useful. + .div => if (is_float) Opcode.OpFDiv else if (is_signed) Opcode.OpSDiv else Opcode.OpUDiv, + else => unreachable, }; - const opcode = if (info.class == .float) opcodes[1] else opcodes[0]; try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, binop_result_id, lhs_id, rhs_id }); + // TODO: Trap on overflow? Probably going to be annoying. + // TODO: Look into NoSignedWrap/NoUnsignedWrap extensions. + if (info.class != .strange_integer) return binop_result_id; -- cgit v1.2.3 From f14000c7e1bd9032185b3c0a2a28a73eec6c48f7 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sun, 16 May 2021 13:39:17 +0200 Subject: SPIR-V: More bitwise binary operations --- src/codegen/spirv.zig | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index c8bebbb70b..88d6f74a2d 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -84,7 +84,7 @@ pub const DeclGen = struct { const ArithmeticTypeInfo = struct { /// A classification of the inner type. const Class = enum { - /// A regular, **native**, integer operation. + /// A regular, **native**, integer. /// This is only returned when the backend supports this int as a native type (when /// the relevant capability is enabled). integer, @@ -112,7 +112,7 @@ pub const DeclGen = struct { /// Whether the inner type is signed. Only relevant for integers. signedness: std.builtin.Signedness, - /// A classification of the inner type. These four scenarios + /// A classification of the inner type. These scenarios /// will all have to be handled slightly different. class: Class, }; @@ -149,6 +149,7 @@ pub const DeclGen = struct { std.debug.assert(bits != 0); // 8, 16 and 64-bit integers require the Int8, Int16 and Inr64 capabilities respectively. + // 32-bit integers are always supported (see spec, 2.16.1, Data rules). const ints = [_]struct{ bits: u16, feature: ?Target.spirv.Feature } { .{ .bits = 8, .feature = .Int8 }, .{ .bits = 16, .feature = .Int16 }, @@ -198,8 +199,8 @@ pub const DeclGen = struct { .Float => ArithmeticTypeInfo{ .bits = ty.floatBits(target), .is_vector = false, - .signedness = .signed, // I guess technically it is. - .class = .float + .signedness = .signed, // Technically, but doesn't matter for this class. + .class = .float, }, .Int => blk: { const int_info = ty.intInfo(target); @@ -315,6 +316,7 @@ pub const DeclGen = struct { const bits = ty.floatBits(target); const supported = switch (bits) { 16 => Target.spirv.featureSetHas(target.cpu.features, .Float16), + // 32-bit floats are always supported (see spec, 2.16.1, Data rules). 32 => true, 64 => Target.spirv.featureSetHas(target.cpu.features, .Float64), else => false, @@ -358,6 +360,8 @@ pub const DeclGen = struct { // which work on them), so simply use those. // Note: SPIR-V vectors only support bools, ints and floats, so pointer vectors need to be supported another way. // "composite integers" (larger than the largest supported native type) can probably be represented by an array of vectors. + // TODO: The SPIR-V spec mentions that vector sizes may be quite restricted! look into which we can use, and whether OpTypeVector + // is adequate at all for this. // TODO: Vectors are not yet supported by the self-hosted compiler itself it seems. return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: implement type Vector", .{}); @@ -429,6 +433,9 @@ pub const DeclGen = struct { .sub, .subwrap => try self.genBinOp(inst.castTag(.sub).?), .mul, .mulwrap => try self.genBinOp(inst.castTag(.mul).?), .div => try self.genBinOp(inst.castTag(.div).?), + .bit_and => try self.genBinOp(inst.castTag(.bit_and).?), + .bit_or => try self.genBinOp(inst.castTag(.bit_or).?), + .xor => try self.genBinOp(inst.castTag(.xor).?), .arg => self.genArg(), // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them // throughout the IR. @@ -472,7 +479,10 @@ pub const DeclGen = struct { // TODO: Trap if divisor is 0? // TODO: Figure out of OpSDiv for unsigned/OpUDiv for signed does anything useful. .div => if (is_float) Opcode.OpFDiv else if (is_signed) Opcode.OpSDiv else Opcode.OpUDiv, - + // Only integer versions for these. + .bit_and => Opcode.OpBitwiseAnd, + .bit_or => Opcode.OpBitwiseOr, + .xor => Opcode.OpBitwiseXor, else => unreachable, }; -- cgit v1.2.3 From 585122b1ac51f9ac23bae537dfc40bbae1d7cb3c Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sun, 16 May 2021 14:46:58 +0200 Subject: SPIR-V: comparison and equality operations --- src/codegen/spirv.zig | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 88d6f74a2d..14511e287f 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -84,6 +84,9 @@ pub const DeclGen = struct { const ArithmeticTypeInfo = struct { /// A classification of the inner type. const Class = enum { + /// A boolean. + bool, + /// A regular, **native**, integer. /// This is only returned when the backend supports this int as a native type (when /// the relevant capability is enabled). @@ -196,6 +199,12 @@ pub const DeclGen = struct { const target = self.module.getTarget(); return switch (ty.zigTypeTag()) { + .Bool => ArithmeticTypeInfo{ + .bits = 1, // Doesn't matter for this class. + .is_vector = false, + .signedness = .unsigned, // Technically, but doesn't matter for this class. + .class = .bool, + }, .Float => ArithmeticTypeInfo{ .bits = ty.floatBits(target), .is_vector = false, @@ -436,6 +445,12 @@ pub const DeclGen = struct { .bit_and => try self.genBinOp(inst.castTag(.bit_and).?), .bit_or => try self.genBinOp(inst.castTag(.bit_or).?), .xor => try self.genBinOp(inst.castTag(.xor).?), + .cmp_eq => try self.genBinOp(inst.castTag(.cmp_eq).?), + .cmp_neq => try self.genBinOp(inst.castTag(.cmp_neq).?), + .cmp_gt => try self.genBinOp(inst.castTag(.cmp_gt).?), + .cmp_gte => try self.genBinOp(inst.castTag(.cmp_gte).?), + .cmp_lt => try self.genBinOp(inst.castTag(.cmp_lt).?), + .cmp_lte => try self.genBinOp(inst.castTag(.cmp_lte).?), .arg => self.genArg(), // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them // throughout the IR. @@ -458,18 +473,23 @@ pub const DeclGen = struct { // TODO: Is the result the same as the argument types? // This is supposed to be the case for SPIR-V. - std.debug.assert(inst.base.ty.eql(inst.lhs.ty) and inst.base.ty.eql(inst.rhs.ty)); + std.debug.assert(inst.rhs.ty.eql(inst.lhs.ty)); + std.debug.assert(inst.base.ty.tag() == .bool or inst.base.ty.eql(inst.lhs.ty)); // Binary operations are generally applicable to both scalar and vector operations in SPIR-V, but int and float // versions of operations require different opcodes. - const info = try self.arithmeticTypeInfo(inst.base.ty); + // For operations which produce bools, the information of inst.base.ty is not useful, so just pick either operand + // instead. + const info = try self.arithmeticTypeInfo(inst.lhs.ty); if (info.class == .composite_integer) return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: binary operations for composite integers", .{}); + const is_bool = info.class == .bool; const is_float = info.class == .float; const is_signed = info.signedness == .signed; - // **Note**: All these operations must be valid for vectors of floats and integers as well! + // **Note**: All these operations must be valid for vectors of floats, integers and bools as well! + // For floating points, we generally want ordered operations (which return false if either operand is nan). const opcode = switch (inst.base.tag) { // The regular integer operations are all defined for wrapping. Since theyre only relevant for integers, // we can just switch on both cases here. @@ -478,11 +498,24 @@ pub const DeclGen = struct { .mul, .mulwrap => if (is_float) Opcode.OpFMul else Opcode.OpIMul, // TODO: Trap if divisor is 0? // TODO: Figure out of OpSDiv for unsigned/OpUDiv for signed does anything useful. + // => Those are probably for divTrunc and divFloor, though the compiler does not yet generate those. + // => TODO: Figure out how those work on the SPIR-V side. + // => TODO: Test these. .div => if (is_float) Opcode.OpFDiv else if (is_signed) Opcode.OpSDiv else Opcode.OpUDiv, // Only integer versions for these. .bit_and => Opcode.OpBitwiseAnd, .bit_or => Opcode.OpBitwiseOr, .xor => Opcode.OpBitwiseXor, + // Int/bool/float -> bool operations. + .cmp_eq => if (is_float) Opcode.OpFOrdEqual else if (is_bool) Opcode.OpLogicalEqual else Opcode.OpIEqual, + .cmp_neq => if (is_float) Opcode.OpFOrdNotEqual else if (is_bool) Opcode.OpLogicalNotEqual else Opcode.OpINotEqual, + // Int/float -> bool operations. + // TODO: Verify that these OpFOrd type operations produce the right value. + // TODO: Is there a more fundamental difference between OpU and OpS operations here than just the type? + .cmp_gt => if (is_float) Opcode.OpFOrdGreaterThan else if (is_signed) Opcode.OpSGreaterThan else Opcode.OpUGreaterThan, + .cmp_gte => if (is_float) Opcode.OpFOrdGreaterThanEqual else if (is_signed) Opcode.OpSGreaterThanEqual else Opcode.OpUGreaterThanEqual, + .cmp_lt => if (is_float) Opcode.OpFOrdLessThan else if (is_signed) Opcode.OpSLessThan else Opcode.OpULessThan, + .cmp_lte => if (is_float) Opcode.OpFOrdLessThanEqual else if (is_signed) Opcode.OpSLessThanEqual else Opcode.OpULessThanEqual, else => unreachable, }; -- cgit v1.2.3 From 489b3ef7d47c877aa7e761ddf00763bfe1dc03a7 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sun, 16 May 2021 14:52:11 +0200 Subject: SPIR-V: bool binary operations --- src/codegen/spirv.zig | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 14511e287f..949e9fc6a2 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -451,6 +451,8 @@ pub const DeclGen = struct { .cmp_gte => try self.genBinOp(inst.castTag(.cmp_gte).?), .cmp_lt => try self.genBinOp(inst.castTag(.cmp_lt).?), .cmp_lte => try self.genBinOp(inst.castTag(.cmp_lte).?), + .bool_and => try self.genBinOp(inst.castTag(.bool_and).?), + .bool_or => try self.genBinOp(inst.castTag(.bool_or).?), .arg => self.genArg(), // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them // throughout the IR. @@ -468,7 +470,7 @@ pub const DeclGen = struct { const lhs_id = try self.resolve(inst.lhs); const rhs_id = try self.resolve(inst.rhs); - const binop_result_id = self.spv.allocResultId(); + const result_id = self.spv.allocResultId(); const result_type_id = try self.getOrGenType(inst.base.ty); // TODO: Is the result the same as the argument types? @@ -516,16 +518,19 @@ pub const DeclGen = struct { .cmp_gte => if (is_float) Opcode.OpFOrdGreaterThanEqual else if (is_signed) Opcode.OpSGreaterThanEqual else Opcode.OpUGreaterThanEqual, .cmp_lt => if (is_float) Opcode.OpFOrdLessThan else if (is_signed) Opcode.OpSLessThan else Opcode.OpULessThan, .cmp_lte => if (is_float) Opcode.OpFOrdLessThanEqual else if (is_signed) Opcode.OpSLessThanEqual else Opcode.OpULessThanEqual, + // Bool -> bool operations. + .bool_and => Opcode.OpLogicalAnd, + .bool_or => Opcode.OpLogicalOr, else => unreachable, }; - try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, binop_result_id, lhs_id, rhs_id }); + try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, result_id, lhs_id, rhs_id }); // TODO: Trap on overflow? Probably going to be annoying. // TODO: Look into NoSignedWrap/NoUnsignedWrap extensions. if (info.class != .strange_integer) - return binop_result_id; + return result_id; return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: strange integer operation mask", .{}); } -- cgit v1.2.3 From 880473dc3f08e2f8c0cef85777d50e25e4bcb062 Mon Sep 17 00:00:00 2001 From: Robin Voetter Date: Sun, 16 May 2021 14:55:09 +0200 Subject: SPIR-V: Unary not operation --- src/codegen/spirv.zig | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/codegen/spirv.zig b/src/codegen/spirv.zig index 949e9fc6a2..7992a7a465 100644 --- a/src/codegen/spirv.zig +++ b/src/codegen/spirv.zig @@ -453,6 +453,7 @@ pub const DeclGen = struct { .cmp_lte => try self.genBinOp(inst.castTag(.cmp_lte).?), .bool_and => try self.genBinOp(inst.castTag(.bool_and).?), .bool_or => try self.genBinOp(inst.castTag(.bool_or).?), + .not => try self.genUnOp(inst.castTag(.not).?), .arg => self.genArg(), // TODO: Breakpoints won't be supported in SPIR-V, but the compiler seems to insert them // throughout the IR. @@ -527,7 +528,7 @@ pub const DeclGen = struct { try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, result_id, lhs_id, rhs_id }); // TODO: Trap on overflow? Probably going to be annoying. - // TODO: Look into NoSignedWrap/NoUnsignedWrap extensions. + // TODO: Look into SPV_KHR_no_integer_wrap_decoration which provides NoSignedWrap/NoUnsignedWrap. if (info.class != .strange_integer) return result_id; @@ -535,6 +536,25 @@ pub const DeclGen = struct { return self.fail(.{.node_offset = 0}, "TODO: SPIR-V backend: strange integer operation mask", .{}); } + fn genUnOp(self: *DeclGen, inst: *Inst.UnOp) !u32 { + const operand_id = try self.resolve(inst.operand); + + const result_id = self.spv.allocResultId(); + const result_type_id = try self.getOrGenType(inst.base.ty); + + const info = try self.arithmeticTypeInfo(inst.operand.ty); + + const opcode = switch (inst.base.tag) { + // Bool -> bool + .not => Opcode.OpLogicalNot, + else => unreachable, + }; + + try writeInstruction(&self.spv.fn_decls, opcode, &[_]u32{ result_type_id, result_id, operand_id }); + + return result_id; + } + fn genArg(self: *DeclGen) u32 { defer self.next_arg_index += 1; return self.args.items[self.next_arg_index]; -- cgit v1.2.3 From fe1a166589db0f2371429c93e1e1e622c19378f1 Mon Sep 17 00:00:00 2001 From: LemonBoy Date: Mon, 17 May 2021 17:41:42 +0200 Subject: translate-c: Add `@truncate` where needed Make getLimitedValue API much easier to use with zig. Fixes the compilation on 32bit hosts. --- src/clang.zig | 5 ++++- src/translate_c.zig | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/clang.zig b/src/clang.zig index 256dbda1e1..b9e152aef4 100644 --- a/src/clang.zig +++ b/src/clang.zig @@ -1,3 +1,4 @@ +const std = @import("std"); pub const builtin = @import("builtin"); pub const SourceLocation = extern struct { @@ -115,7 +116,9 @@ pub const APFloatBaseSemantics = extern enum { }; pub const APInt = opaque { - pub const getLimitedValue = ZigClangAPInt_getLimitedValue; + pub fn getLimitedValue(self: *const APInt, comptime T: type) T { + return @truncate(T, ZigClangAPInt_getLimitedValue(self, std.math.maxInt(T))); + } extern fn ZigClangAPInt_getLimitedValue(*const APInt, limit: u64) u64; }; diff --git a/src/translate_c.zig b/src/translate_c.zig index 348e284db3..19aec279ec 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -2341,7 +2341,7 @@ fn transInitListExprArray( assert(@ptrCast(*const clang.Type, arr_type).isConstantArrayType()); const const_arr_ty = @ptrCast(*const clang.ConstantArrayType, arr_type); const size_ap_int = const_arr_ty.getSize(); - const all_count = size_ap_int.getLimitedValue(math.maxInt(usize)); + const all_count = size_ap_int.getLimitedValue(usize); const leftover_count = all_count - init_count; if (all_count == 0) { @@ -4266,7 +4266,7 @@ fn transType(c: *Context, scope: *Scope, ty: *const clang.Type, source_loc: clan const const_arr_ty = @ptrCast(*const clang.ConstantArrayType, ty); const size_ap_int = const_arr_ty.getSize(); - const size = size_ap_int.getLimitedValue(math.maxInt(usize)); + const size = size_ap_int.getLimitedValue(usize); const elem_type = try transType(c, scope, const_arr_ty.getElementType().getTypePtr(), source_loc); return Tag.array_type.create(c.arena, .{ .len = size, .elem_type = elem_type }); -- cgit v1.2.3 From 65cee0b3fd5f9b3f83b79cc8fd1b64d13f4dd0c4 Mon Sep 17 00:00:00 2001 From: joachimschmidt557 Date: Sun, 16 May 2021 12:54:51 +0800 Subject: stage2 ARM: correct spilling in genArmMul as well --- src/codegen.zig | 69 ++++++++++++++++++++++++++++++++++++++++------------- test/stage2/arm.zig | 49 +++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/codegen.zig b/src/codegen.zig index 9d344bf1d0..379a0f9b7d 100644 --- a/src/codegen.zig +++ b/src/codegen.zig @@ -1563,28 +1563,63 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type { const lhs = try self.resolveInst(op_lhs); const rhs = try self.resolveInst(op_rhs); + const lhs_is_register = lhs == .register; + const rhs_is_register = rhs == .register; + const reuse_lhs = lhs_is_register and self.reuseOperand(inst, 0, lhs); + const reuse_rhs = !reuse_lhs and rhs_is_register and self.reuseOperand(inst, 1, rhs); + // Destination must be a register // LHS must be a register // RHS must be a register var dst_mcv: MCValue = undefined; - var lhs_mcv: MCValue = undefined; - var rhs_mcv: MCValue = undefined; - if (self.reuseOperand(inst, 0, lhs)) { - // LHS is the destination - lhs_mcv = if (lhs != .register) try self.copyToNewRegister(inst, lhs) else lhs; - rhs_mcv = if (rhs != .register) try self.copyToNewRegister(inst, rhs) else rhs; - dst_mcv = lhs_mcv; - } else if (self.reuseOperand(inst, 1, rhs)) { - // RHS is the destination - lhs_mcv = if (lhs != .register) try self.copyToNewRegister(inst, lhs) else lhs; - rhs_mcv = if (rhs != .register) try self.copyToNewRegister(inst, rhs) else rhs; - dst_mcv = rhs_mcv; + var lhs_mcv: MCValue = lhs; + var rhs_mcv: MCValue = rhs; + + // Allocate registers for operands and/or destination + const branch = &self.branch_stack.items[self.branch_stack.items.len - 1]; + if (reuse_lhs) { + // Allocate 0 or 1 registers + if (!rhs_is_register) { + rhs_mcv = MCValue{ .register = try self.register_manager.allocReg(op_rhs, &.{lhs.register}) }; + branch.inst_table.putAssumeCapacity(op_rhs, rhs_mcv); + } + dst_mcv = lhs; + } else if (reuse_rhs) { + // Allocate 0 or 1 registers + if (!lhs_is_register) { + lhs_mcv = MCValue{ .register = try self.register_manager.allocReg(op_lhs, &.{rhs.register}) }; + branch.inst_table.putAssumeCapacity(op_lhs, lhs_mcv); + } + dst_mcv = rhs; } else { - // TODO save 1 copy instruction by directly allocating the destination register - // LHS is the destination - lhs_mcv = try self.copyToNewRegister(inst, lhs); - rhs_mcv = if (rhs != .register) try self.copyToNewRegister(inst, rhs) else rhs; - dst_mcv = lhs_mcv; + // Allocate 1 or 2 registers + if (lhs_is_register and rhs_is_register) { + dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{ lhs.register, rhs.register }) }; + } else if (lhs_is_register) { + // Move RHS to register + dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{lhs.register}) }; + rhs_mcv = dst_mcv; + } else if (rhs_is_register) { + // Move LHS to register + dst_mcv = MCValue{ .register = try self.register_manager.allocReg(inst, &.{rhs.register}) }; + lhs_mcv = dst_mcv; + } else { + // Move LHS and RHS to register + const regs = try self.register_manager.allocRegs(2, .{ inst, op_rhs }, &.{}); + lhs_mcv = MCValue{ .register = regs[0] }; + rhs_mcv = MCValue{ .register = regs[1] }; + dst_mcv = lhs_mcv; + + branch.inst_table.putAssumeCapacity(op_rhs, rhs_mcv); + } + } + + // Move the operands to the newly allocated registers + if (!lhs_is_register) { + try self.genSetReg(op_lhs.src, op_lhs.ty, lhs_mcv.register, lhs); + } + if (!rhs_is_register) { + try self.genSetReg(op_rhs.src, op_rhs.ty, rhs_mcv.register, rhs); } writeInt(u32, try self.code.addManyAsArray(4), Instruction.mul(.al, dst_mcv.register, lhs_mcv.register, rhs_mcv.register).toU32()); diff --git a/test/stage2/arm.zig b/test/stage2/arm.zig index 31b3c06dcd..02033005d1 100644 --- a/test/stage2/arm.zig +++ b/test/stage2/arm.zig @@ -510,5 +510,54 @@ pub fn addCases(ctx: *TestContext) !void { , "", ); + + case.addCompareOutput( + \\export fn _start() noreturn { + \\ assert(addMul(3, 4) == 357747496); + \\ exit(); + \\} + \\ + \\fn addMul(a: u32, b: u32) u32 { + \\ const x: u32 = blk: { + \\ const c = a + b; // 7 + \\ const d = a + c; // 10 + \\ const e = d + b; // 14 + \\ const f = d + e; // 24 + \\ const g = e + f; // 38 + \\ const h = f + g; // 62 + \\ const i = g + h; // 100 + \\ const j = i + d; // 110 + \\ const k = i + j; // 210 + \\ const l = k + c; // 217 + \\ const m = l * d; // 2170 + \\ const n = m + e; // 2184 + \\ const o = n * f; // 52416 + \\ const p = o + g; // 52454 + \\ const q = p * h; // 3252148 + \\ const r = q + i; // 3252248 + \\ const s = r * j; // 357747280 + \\ const t = s + k; // 357747490 + \\ break :blk t; + \\ }; + \\ const y = x + a; // 357747493 + \\ const z = y + a; // 357747496 + \\ return z; + \\} + \\ + \\fn assert(ok: bool) void { + \\ if (!ok) unreachable; + \\} + \\ + \\fn exit() noreturn { + \\ asm volatile ("svc #0" + \\ : + \\ : [number] "{r7}" (1), + \\ [arg1] "{r0}" (0) + \\ : "memory" + \\ ); + \\ unreachable; + \\} + , + "",); } } -- cgit v1.2.3