authorgravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2021-05-15 01:04:02+02:00
committergravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2021-05-16 14:13:23+02:00
logde6df2bc12c1cec81bb3c562a9395098c92d8239
treebb12821965274723ae2ddec27657650498967e9f
parent6461b9516371d22d347c27b5fcd2e8c22fafd03d

SPIR-V: Restructure codegen a bit


2 files changed, 68 insertions(+), 32 deletions(-)

src/codegen/spirv.zig+39-25
...@@ -6,6 +6,7 @@ const spec = @import("spirv/spec.zig");...@@ -6,6 +6,7 @@ const spec = @import("spirv/spec.zig");
6const Module = @import("../Module.zig");6const Module = @import("../Module.zig");
7const Decl = Module.Decl;7const Decl = Module.Decl;
8const Type = @import("../type.zig").Type;8const Type = @import("../type.zig").Type;
9const LazySrcLoc = Module.LazySrcLoc;
910
10pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage);11pub const TypeMap = std.HashMap(Type, u32, Type.hash, Type.eql, std.hash_map.default_max_load_percentage);
1112
...@@ -15,30 +16,24 @@ pub fn writeInstruction(code: *std.ArrayList(u32), instr: spec.Opcode, args: []c...@@ -15,30 +16,24 @@ pub fn writeInstruction(code: *std.ArrayList(u32), instr: spec.Opcode, args: []c
15 try code.appendSlice(args);16 try code.appendSlice(args);
16}17}
1718
19/// This structure represents a SPIR-V binary module being compiled, and keeps track of relevant information
20/// such as code for the different logical sections, and the next result-id.
18pub const SPIRVModule = struct {21pub const SPIRVModule = struct {
19 next_result_id: u32 = 0,22 next_result_id: u32,
20
21 target: std.Target,
22
23 types: TypeMap,
24
25 types_and_globals: std.ArrayList(u32),23 types_and_globals: std.ArrayList(u32),
26 fn_decls: std.ArrayList(u32),24 fn_decls: std.ArrayList(u32),
2725
28 pub fn init(target: std.Target, allocator: *Allocator) SPIRVModule {26 pub fn init(allocator: *Allocator) SPIRVModule {
29 return .{27 return .{
30 .target = target,28 .next_result_id = 0,
31 .types = TypeMap.init(allocator),
32 .types_and_globals = std.ArrayList(u32).init(allocator),29 .types_and_globals = std.ArrayList(u32).init(allocator),
33 .fn_decls = std.ArrayList(u32).init(allocator),30 .fn_decls = std.ArrayList(u32).init(allocator),
34 };31 };
35 }32 }
3633
37 pub fn deinit(self: *SPIRVModule) void {34 pub fn deinit(self: *SPIRVModule) void {
38 self.fn_decls.deinit();
39 self.types_and_globals.deinit();35 self.types_and_globals.deinit();
40 self.types.deinit();36 self.fn_decls.deinit();
41 self.* = undefined;
42 }37 }
4338
44 pub fn allocResultId(self: *SPIRVModule) u32 {39 pub fn allocResultId(self: *SPIRVModule) u32 {
...@@ -49,21 +44,40 @@ pub const SPIRVModule = struct {...@@ -49,21 +44,40 @@ pub const SPIRVModule = struct {
49 pub fn resultIdBound(self: *SPIRVModule) u32 {44 pub fn resultIdBound(self: *SPIRVModule) u32 {
50 return self.next_result_id;45 return self.next_result_id;
51 }46 }
47};
48
49/// This structure is used to compile a declaration, and contains all relevant meta-information to deal with that.
50pub const DeclGen = struct {
51 module: *Module,
52 spv: *SPIRVModule,
53
54 types: TypeMap,
55
56 decl: *Decl,
57 error_msg: ?*Module.ErrorMsg,
58
59 fn fail(self: *DeclGen, src: LazySrcLoc, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
60 @setCold(true);
61 const src_loc = src.toSrcLocWithDecl(self.decl);
62 self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args);
63 return error.AnalysisFail;
64 }
5265
53 pub fn getOrGenType(self: *SPIRVModule, t: Type) !u32 {66 pub fn getOrGenType(self: *DeclGen, t: Type) !u32 {
54 // We can't use getOrPut here so we can recursively generate types.67 // We can't use getOrPut here so we can recursively generate types.
55 if (self.types.get(t)) |already_generated| {68 if (self.types.get(t)) |already_generated| {
56 return already_generated;69 return already_generated;
57 }70 }
5871
59 const result = self.allocResultId();72 const result = self.spv.allocResultId();
6073
61 switch (t.zigTypeTag()) {74 switch (t.zigTypeTag()) {
62 .Void => try writeInstruction(&self.types_and_globals, .OpTypeVoid, &[_]u32{ result }),75 .Void => try writeInstruction(&self.spv.types_and_globals, .OpTypeVoid, &[_]u32{ result }),
63 .Bool => try writeInstruction(&self.types_and_globals, .OpTypeBool, &[_]u32{ result }),76 .Bool => try writeInstruction(&self.spv.types_and_globals, .OpTypeBool, &[_]u32{ result }),
64 .Int => {77 .Int => {
65 const int_info = t.intInfo(self.target);78 const int_info = t.intInfo(self.module.getTarget());
66 try writeInstruction(&self.types_and_globals, .OpTypeInt, &[_]u32{79 // TODO: Capabilities.
80 try writeInstruction(&self.spv.types_and_globals, .OpTypeInt, &[_]u32{
67 result,81 result,
68 int_info.bits,82 int_info.bits,
69 switch (int_info.signedness) {83 switch (int_info.signedness) {
...@@ -72,8 +86,8 @@ pub const SPIRVModule = struct {...@@ -72,8 +86,8 @@ pub const SPIRVModule = struct {
72 },86 },
73 });87 });
74 },88 },
75 // TODO: Verify that floatBits() will be correct.89 // TODO: Capabilities.
76 .Float => try writeInstruction(&self.types_and_globals, .OpTypeFloat, &[_]u32{ result, t.floatBits(self.target) }),90 .Float => try writeInstruction(&self.spv.types_and_globals, .OpTypeFloat, &[_]u32{ result, t.floatBits(self.module.getTarget()) }),
77 .Null,91 .Null,
78 .Undefined,92 .Undefined,
79 .EnumLiteral,93 .EnumLiteral,
...@@ -84,23 +98,23 @@ pub const SPIRVModule = struct {...@@ -84,23 +98,23 @@ pub const SPIRVModule = struct {
8498
85 .BoundFn => unreachable, // this type will be deleted from the language.99 .BoundFn => unreachable, // this type will be deleted from the language.
86100
87 else => return error.TODO,101 else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: implement type with tag {}", .{ tag }),
88 }102 }
89103
90 try self.types.put(t, result);104 try self.types.put(t, result);
91 return result;105 return result;
92 }106 }
93107
94 pub fn gen(self: *SPIRVModule, decl: *Decl) !void {108 pub fn gen(self: *DeclGen) !void {
95 const typed_value = decl.typed_value.most_recent.typed_value;109 const typed_value = self.decl.typed_value.most_recent.typed_value;
96110
97 switch (typed_value.ty.zigTypeTag()) {111 switch (typed_value.ty.zigTypeTag()) {
98 .Fn => {112 .Fn => {
99 log.debug("Generating code for function '{s}'", .{ std.mem.spanZ(decl.name) });113 log.debug("Generating code for function '{s}'", .{ std.mem.spanZ(self.decl.name) });
100114
101 _ = try self.getOrGenType(typed_value.ty.fnReturnType());115 _ = try self.getOrGenType(typed_value.ty.fnReturnType());
102 },116 },
103 else => return error.TODO,117 else => |tag| return self.fail(.{ .node_offset = 0 }, "TODO: SPIR-V backend: generate decl with tag {}", .{ tag }),
104 }118 }
105 }119 }
106};120};
src/link/SpirV.zig+29-7
...@@ -118,8 +118,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {...@@ -118,8 +118,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
118 const module = self.base.options.module.?;118 const module = self.base.options.module.?;
119 const target = comp.getTarget();119 const target = comp.getTarget();
120120
121 var spirv_module = codegen.SPIRVModule.init(target, self.base.allocator);121 var spv = codegen.SPIRVModule.init(self.base.allocator);
122 defer spirv_module.deinit();122 defer spv.deinit();
123123
124 // Allocate an ID for every declaration before generating code,124 // Allocate an ID for every declaration before generating code,
125 // so that we can access them before processing them.125 // so that we can access them before processing them.
...@@ -132,19 +132,41 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {...@@ -132,19 +132,41 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
132 if (decl.typed_value != .most_recent)132 if (decl.typed_value != .most_recent)
133 continue;133 continue;
134134
135 decl.fn_link.spirv.id = spirv_module.allocResultId();135 decl.fn_link.spirv.id = spv.allocResultId();
136 log.debug("Allocating id {} to '{s}'", .{ decl.fn_link.spirv.id, std.mem.spanZ(decl.name) });136 log.debug("Allocating id {} to '{s}'", .{ decl.fn_link.spirv.id, std.mem.spanZ(decl.name) });
137 }137 }
138 }138 }
139139
140 // Now, actually generate the code for all declarations.140 // Now, actually generate the code for all declarations.
141 {141 {
142 // We are just going to re-use this same DeclGen for every Decl, and we are just going to
143 // change the decl. Otherwise, we would have to keep a separate `types`, and re-construct this
144 // structure every time.
145 var decl_gen = codegen.DeclGen{
146 .module = module,
147 .spv = &spv,
148 .types = codegen.TypeMap.init(self.base.allocator),
149 .decl = undefined,
150 .error_msg = undefined,
151 };
152
153 defer decl_gen.types.deinit();
154
142 for (module.decl_table.items()) |entry| {155 for (module.decl_table.items()) |entry| {
143 const decl = entry.value;156 const decl = entry.value;
144 if (decl.typed_value != .most_recent)157 if (decl.typed_value != .most_recent)
145 continue;158 continue;
146159
147 try spirv_module.gen(decl);160 decl_gen.decl = decl;
161 decl_gen.error_msg = null;
162
163 decl_gen.gen() catch |err| switch (err) {
164 error.AnalysisFail => {
165 try module.failed_decls.put(module.gpa, decl, decl_gen.error_msg.?);
166 return;
167 },
168 else => |e| return e,
169 };
148 }170 }
149 }171 }
150172
...@@ -155,7 +177,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {...@@ -155,7 +177,7 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
155 spec.magic_number,177 spec.magic_number,
156 (spec.version.major << 16) | (spec.version.minor << 8),178 (spec.version.major << 16) | (spec.version.minor << 8),
157 0, // TODO: Register Zig compiler magic number.179 0, // TODO: Register Zig compiler magic number.
158 spirv_module.resultIdBound(), // ID bound.180 spv.resultIdBound(), // ID bound.
159 0, // Schema (currently reserved for future use in the SPIR-V spec).181 0, // Schema (currently reserved for future use in the SPIR-V spec).
160 });182 });
161183
...@@ -166,8 +188,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {...@@ -166,8 +188,8 @@ pub fn flushModule(self: *SpirV, comp: *Compilation) !void {
166 // follows the SPIR-V logical module format!188 // follows the SPIR-V logical module format!
167 var all_buffers = [_]std.os.iovec_const{189 var all_buffers = [_]std.os.iovec_const{
168 wordsToIovConst(binary.items),190 wordsToIovConst(binary.items),
169 wordsToIovConst(spirv_module.types_and_globals.items),191 wordsToIovConst(spv.types_and_globals.items),
170 wordsToIovConst(spirv_module.fn_decls.items),192 wordsToIovConst(spv.fn_decls.items),
171 };193 };
172194
173 const file = self.base.file.?;195 const file = self.base.file.?;