authorgravatar for luuk@degram.devLuuk de Gram <luuk@degram.dev> 2021-01-15 23:24:47+01:00
committergravatar for luuk@degram.devLuuk de Gram <luuk@degram.dev> 2021-01-15 23:27:38+01:00
log4b2538f72c9190b12c11c45a6d18cdc831b41015
treea17d40caaaba49fe6a08ff24f1f019443d9cb809
parentbb74f72e97f3d503c4801bb7ca3d6412ad01b28c
signaturelock-open Commit is signed but in an unrecognized format.

Cleanup and 'add' instruction for bigger test area


2 files changed, 63 insertions(+), 59 deletions(-)

src/codegen/wasm.zig+57-53
......@@ -18,16 +18,16 @@ const WValue = union(enum) {
1818 none: void,
1919 /// Index of the local variable
2020 local: u32,
21 /// A constant instruction
21 /// Instruction holding a constant `Value`
2222 constant: *Inst,
23 /// Each newly created wasm block have a label
24 /// in the form of an index.
23 /// Block label
2524 block_idx: u32,
2625};
2726
28pub const ValueTable = std.AutoArrayHashMap(*Inst, WValue);
27/// Hashmap to store generated `WValue` for each `Inst`
28pub const ValueTable = std.AutoHashMap(*Inst, WValue);
2929
30/// Using a given Zig type, returns the corresponding wasm value type
30/// Using a given `Type`, returns the corresponding wasm value type
3131fn genValtype(ty: Type) ?u8 {
3232 return switch (ty.tag()) {
3333 .f32 => 0x7D,
......@@ -40,24 +40,22 @@ fn genValtype(ty: Type) ?u8 {
4040
4141/// Code represents the `Code` section of wasm that
4242/// belongs to a function
43pub const Code = struct {
43pub const Context = struct {
4444 /// Reference to the function declaration the code
4545 /// section belongs to
4646 decl: *Decl,
4747 gpa: *mem.Allocator,
4848 /// Table to save `WValue`'s generated by an `Inst`
4949 values: ValueTable,
50 /// `bytes` contains the wasm instructions that have been emitted
51 /// this is what will be emitted after codegen to write the wasm binary
50 /// `bytes` contains the wasm bytecode belonging to the 'code' section.
5251 bytes: ArrayList(u8),
5352 /// Contains the generated function type bytecode for the current function
53 /// found in `decl`
5454 func_type_data: ArrayList(u8),
5555 /// The index the next local generated will have
5656 /// NOTE: arguments share the index with locals therefore the first variable
5757 /// will have the index that comes after the last argument's index
5858 local_index: u32 = 0,
59 /// The index the next argument generated will have
60 arg_index: u32 = 0,
6159 /// If codegen fails, an error messages will be allocated and saved
6260 /// in `err_msg`
6361 err_msg: *Compilation.ErrorMsg,
......@@ -67,14 +65,15 @@ pub const Code = struct {
6765 CodegenFail,
6866 };
6967
70 fn fail(self: *Code, src: usize, comptime fmt: []const u8, args: anytype) InnerError {
68 /// Sets `err_msg` on `Context` and returns `error.CodegemFail` which is caught in link/Wasm.zig
69 fn fail(self: *Context, src: usize, comptime fmt: []const u8, args: anytype) InnerError {
7170 self.err_msg = try Compilation.ErrorMsg.create(self.gpa, src, fmt, args);
7271 return error.CodegenFail;
7372 }
7473
75 /// Returns the `WValue` for the given `inst`
76 /// creates a new WValue for constants and returns that instead
77 fn resolveInst(self: Code, inst: *Inst) !WValue {
74 /// Resolves the `WValue` for the given instruction `inst`
75 /// When the given instruction has a `Value`, it returns a constant instead
76 fn resolveInst(self: Context, inst: *Inst) WValue {
7877 if (inst.value()) |_| {
7978 return WValue{ .constant = inst };
8079 }
......@@ -83,23 +82,19 @@ pub const Code = struct {
8382 }
8483
8584 /// Writes the bytecode depending on the given `WValue` in `val`
86 fn emitWValue(self: *Code, val: WValue) !void {
85 fn emitWValue(self: *Context, val: WValue) InnerError!void {
8786 const writer = self.bytes.writer();
8887 switch (val) {
89 .none => unreachable,
90 .block_idx => unreachable,
91 // loads the local onto the stack at the given index
88 .none, .block_idx => {},
9289 .local => |idx| {
93 // local.set
94 try writer.writeByte(0x20);
90 try writer.writeByte(0x20); // local.get
9591 try leb.writeULEB128(writer, idx);
9692 },
97 // creates a new constant onto the stack
98 .constant => |inst| try self.emitConstant(inst.castTag(.constant).?),
93 .constant => |inst| try self.emitConstant(inst.castTag(.constant).?), // creates a new constant onto the stack
9994 }
10095 }
10196
102 fn genFunctype(self: *Code) !void {
97 fn genFunctype(self: *Context) InnerError!void {
10398 const ty = self.decl.typed_value.most_recent.typed_value.ty;
10499 const writer = self.func_type_data.writer();
105100
......@@ -114,7 +109,7 @@ pub const Code = struct {
114109 ty.fnParamTypes(params);
115110 for (params) |param_type| {
116111 const val_type = genValtype(param_type) orelse
117 return self.fail(self.decl.src(), "TODO: Wasm generate wasm type value for type '{s}'", .{param_type.tag()});
112 return self.fail(self.decl.src(), "TODO: Wasm codegen - arg type value for type '{s}'", .{param_type.tag()});
118113 try writer.writeByte(val_type);
119114 }
120115 }
......@@ -126,14 +121,14 @@ pub const Code = struct {
126121 else => |ret_type| {
127122 try leb.writeULEB128(writer, @as(u32, 1));
128123 const val_type = genValtype(return_type) orelse
129 return self.fail(self.decl.src(), "TODO: Wasm generate wasm return type value for type '{s}'", .{ret_type});
124 return self.fail(self.decl.src(), "TODO: Wasm codegen - return type value for type '{s}'", .{ret_type});
130125 try writer.writeByte(val_type);
131126 },
132127 }
133128 }
134129
135130 /// Generates the wasm bytecode for the given `code`
136 pub fn gen(self: *Code) !void {
131 pub fn gen(self: *Context) InnerError!void {
137132 assert(self.bytes.items.len == 0);
138133 try self.genFunctype();
139134 const writer = self.bytes.writer();
......@@ -156,7 +151,7 @@ pub const Code = struct {
156151 const elem_type = alloc.base.ty.elemType();
157152
158153 const wasm_type = genValtype(elem_type) orelse
159 return self.fail(inst.src, "TODO: Wasm generate wasm type value for type '{s}'", .{elem_type.tag()});
154 return self.fail(inst.src, "TODO: Wasm codegen - valtype for type '{s}'", .{elem_type.tag()});
160155
161156 try locals.append(wasm_type);
162157 }
......@@ -169,16 +164,9 @@ pub const Code = struct {
169164 try leb.writeULEB128(writer, local); // valtype
170165 }
171166
172 for (mod_fn.body.instructions) |inst| {
173 const result = try self.genInst(inst);
174
175 if (result != .none) {
176 try self.values.putNoClobber(inst, result);
177 }
178 }
167 try self.genBody(mod_fn.body);
179168
180 // Write 'end' opcode
181 try writer.writeByte(0x0B);
169 try writer.writeByte(0x0B); // end
182170
183171 // Fill in the size of the generated code to the reserved space at the
184172 // beginning of the buffer.
......@@ -186,8 +174,9 @@ pub const Code = struct {
186174 leb.writeUnsignedFixed(5, self.bytes.items[0..5], @intCast(u32, size));
187175 }
188176
189 fn genInst(self: *Code, inst: *Inst) !WValue {
177 fn genInst(self: *Context, inst: *Inst) InnerError!WValue {
190178 return switch (inst.tag) {
179 .add => self.genAdd(inst.castTag(.add).?),
191180 .alloc => self.genAlloc(inst.castTag(.alloc).?),
192181 .arg => self.genArg(inst.castTag(.arg).?),
193182 .call => self.genCall(inst.castTag(.call).?),
......@@ -201,20 +190,27 @@ pub const Code = struct {
201190 };
202191 }
203192
204 fn genRet(self: *Code, inst: *Inst.UnOp) !WValue {
205 const operand = try self.resolveInst(inst.operand);
193 fn genBody(self: *Context, body: ir.Body) InnerError!void {
194 for (body.instructions) |inst| {
195 const result = try self.genInst(inst);
196 try self.values.putNoClobber(inst, result);
197 }
198 }
199
200 fn genRet(self: *Context, inst: *Inst.UnOp) InnerError!WValue {
201 const operand = self.resolveInst(inst.operand);
206202 try self.emitWValue(operand);
207203 return WValue.none;
208204 }
209205
210 fn genCall(self: *Code, inst: *Inst.Call) !WValue {
206 fn genCall(self: *Context, inst: *Inst.Call) InnerError!WValue {
211207 const func_inst = inst.func.castTag(.constant).?;
212208 const func = func_inst.val.castTag(.function).?.data;
213209 const target = func.owner_decl;
214210 const target_ty = target.typed_value.most_recent.typed_value.ty;
215211
216212 for (inst.args) |arg| {
217 const arg_val = try self.resolveInst(arg);
213 const arg_val = self.resolveInst(arg);
218214 try self.emitWValue(arg_val);
219215 }
220216
......@@ -230,39 +226,47 @@ pub const Code = struct {
230226 return WValue.none;
231227 }
232228
233 fn genAlloc(self: *Code, inst: *Inst.NoOp) !WValue {
229 fn genAlloc(self: *Context, inst: *Inst.NoOp) InnerError!WValue {
234230 defer self.local_index += 1;
235231 return WValue{ .local = self.local_index };
236232 }
237233
238 fn genStore(self: *Code, inst: *Inst.BinOp) !WValue {
234 fn genStore(self: *Context, inst: *Inst.BinOp) InnerError!WValue {
239235 const writer = self.bytes.writer();
240236
241 const lhs = try self.resolveInst(inst.lhs);
242
243 const rhs = try self.resolveInst(inst.rhs);
237 const lhs = self.resolveInst(inst.lhs);
238 const rhs = self.resolveInst(inst.rhs);
244239 try self.emitWValue(rhs);
245240
246241 try writer.writeByte(0x21); // local.set
247242 try leb.writeULEB128(writer, lhs.local);
248
249243 return WValue.none;
250244 }
251245
252 fn genLoad(self: *Code, inst: *Inst.UnOp) !WValue {
246 fn genLoad(self: *Context, inst: *Inst.UnOp) InnerError!WValue {
253247 const operand = self.resolveInst(inst.operand);
254
255 // ensure index to local
256 return WValue{ .local = operand.local };
248 try self.emitWValue(operand);
249 return WValue.none;
257250 }
258251
259 fn genArg(self: *Code, inst: *Inst.Arg) !WValue {
252 fn genArg(self: *Context, inst: *Inst.Arg) InnerError!WValue {
260253 // arguments share the index with locals
261254 defer self.local_index += 1;
262255 return WValue{ .local = self.local_index };
263256 }
264257
265 fn emitConstant(self: *Code, inst: *Inst.Constant) !void {
258 fn genAdd(self: *Context, inst: *Inst.BinOp) InnerError!WValue {
259 const lhs = self.resolveInst(inst.lhs);
260 const rhs = self.resolveInst(inst.rhs);
261
262 try self.emitWValue(lhs);
263 try self.emitWValue(rhs);
264
265 try self.bytes.append(0x6A); // i32.add
266 return WValue.none;
267 }
268
269 fn emitConstant(self: *Context, inst: *Inst.Constant) InnerError!void {
266270 const writer = self.bytes.writer();
267271 switch (inst.base.ty.tag()) {
268272 .u32 => {
src/link/Wasm.zig+6-6
......@@ -119,7 +119,7 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
119119 var managed_functype = fn_data.functype.toManaged(self.base.allocator);
120120 var managed_code = fn_data.code.toManaged(self.base.allocator);
121121
122 var code = codegen.Code{
122 var context = codegen.Context{
123123 .gpa = self.base.allocator,
124124 .values = codegen.ValueTable.init(self.base.allocator),
125125 .bytes = managed_code,
......@@ -127,20 +127,20 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
127127 .decl = decl,
128128 .err_msg = undefined,
129129 };
130 defer code.values.deinit();
130 defer context.values.deinit();
131131
132132 // generate the 'code' section for the function declaration
133 code.gen() catch |err| switch (err) {
133 context.gen() catch |err| switch (err) {
134134 error.CodegenFail => {
135135 decl.analysis = .codegen_failure;
136 try module.failed_decls.put(module.gpa, decl, code.err_msg);
136 try module.failed_decls.put(module.gpa, decl, context.err_msg);
137137 return;
138138 },
139139 else => |e| return err,
140140 };
141141
142 fn_data.functype = code.func_type_data.toUnmanaged();
143 fn_data.code = code.bytes.toUnmanaged();
142 fn_data.functype = context.func_type_data.toUnmanaged();
143 fn_data.code = context.bytes.toUnmanaged();
144144}
145145
146146pub fn updateDeclExports(