authorgravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2020-08-19 01:48:09+02:00
committergravatar for mail@isaacfreund.comIsaac Freund <mail@isaacfreund.com> 2020-08-19 02:05:13+02:00
log6242ae35f37a6e67d9da514fa7a3508843515667
treea6c43da4312a4aba2d853908b5f6c1e4cb10bfe2
parentfe3aa4ccd0bc157e1dd9d84b7c57b0cb2f0a77a9
signaturelock-open Commit is signed but in an unrecognized format.

stage2/wasm: implement function calls

During codegen we do not yet know the indexes that will be used for called functions. Therefore, we store the offset into the in-memory code where the index is needed with a pointer to the Decl and use this data to insert the proper indexes while writing the binary in the flush function.

3 files changed, 110 insertions(+), 39 deletions(-)

src-self-hosted/codegen/wasm.zig+59-37
...@@ -62,58 +62,80 @@ pub fn genCode(buf: *ArrayList(u8), decl: *Decl) !void {...@@ -62,58 +62,80 @@ pub fn genCode(buf: *ArrayList(u8), decl: *Decl) !void {
62 // TODO: check for and handle death of instructions62 // TODO: check for and handle death of instructions
63 const tv = decl.typed_value.most_recent.typed_value;63 const tv = decl.typed_value.most_recent.typed_value;
64 const mod_fn = tv.val.cast(Value.Payload.Function).?.func;64 const mod_fn = tv.val.cast(Value.Payload.Function).?.func;
65 for (mod_fn.analysis.success.instructions) |inst| try genInst(writer, inst);65 for (mod_fn.analysis.success.instructions) |inst| try genInst(buf, decl, inst);
6666
67 // Write 'end' opcode67 // Write 'end' opcode
68 try writer.writeByte(0x0B);68 try writer.writeByte(0x0B);
6969
70 // Fill in the size of the generated code to the reserved space at the70 // Fill in the size of the generated code to the reserved space at the
71 // beginning of the buffer.71 // beginning of the buffer.
72 leb.writeUnsignedFixed(5, buf.items[0..5], @intCast(u32, buf.items.len - 5));72 const size = buf.items.len - 5 + decl.fn_link.wasm.?.idx_refs.items.len * 5;
73 leb.writeUnsignedFixed(5, buf.items[0..5], @intCast(u32, size));
73}74}
7475
75fn genInst(writer: ArrayList(u8).Writer, inst: *Inst) !void {76fn genInst(buf: *ArrayList(u8), decl: *Decl, inst: *Inst) !void {
76 return switch (inst.tag) {77 return switch (inst.tag) {
78 .call => genCall(buf, decl, inst.castTag(.call).?),
79 .constant => genConstant(buf, decl, inst.castTag(.constant).?),
77 .dbg_stmt => {},80 .dbg_stmt => {},
78 .ret => genRet(writer, inst.castTag(.ret).?),81 .ret => genRet(buf, decl, inst.castTag(.ret).?),
82 .retvoid => {},
79 else => error.TODOImplementMoreWasmCodegen,83 else => error.TODOImplementMoreWasmCodegen,
80 };84 };
81}85}
8286
83fn genRet(writer: ArrayList(u8).Writer, inst: *Inst.UnOp) !void {87fn genConstant(buf: *ArrayList(u8), decl: *Decl, inst: *Inst.Constant) !void {
84 switch (inst.operand.tag) {88 const writer = buf.writer();
85 .constant => {89 switch (inst.base.ty.tag()) {
86 const constant = inst.operand.castTag(.constant).?;90 .u32 => {
87 switch (inst.operand.ty.tag()) {91 try writer.writeByte(0x41); // i32.const
88 .u32 => {92 try leb.writeILEB128(writer, inst.val.toUnsignedInt());
89 try writer.writeByte(0x41); // i32.const93 },
90 try leb.writeILEB128(writer, constant.val.toUnsignedInt());94 .i32 => {
91 },95 try writer.writeByte(0x41); // i32.const
92 .i32 => {96 try leb.writeILEB128(writer, inst.val.toSignedInt());
93 try writer.writeByte(0x41); // i32.const97 },
94 try leb.writeILEB128(writer, constant.val.toSignedInt());98 .u64 => {
95 },99 try writer.writeByte(0x42); // i64.const
96 .u64 => {100 try leb.writeILEB128(writer, inst.val.toUnsignedInt());
97 try writer.writeByte(0x42); // i64.const101 },
98 try leb.writeILEB128(writer, constant.val.toUnsignedInt());102 .i64 => {
99 },103 try writer.writeByte(0x42); // i64.const
100 .i64 => {104 try leb.writeILEB128(writer, inst.val.toSignedInt());
101 try writer.writeByte(0x42); // i64.const
102 try leb.writeILEB128(writer, constant.val.toSignedInt());
103 },
104 .f32 => {
105 try writer.writeByte(0x43); // f32.const
106 // TODO: enforce LE byte order
107 try writer.writeAll(mem.asBytes(&constant.val.toFloat(f32)));
108 },
109 .f64 => {
110 try writer.writeByte(0x44); // f64.const
111 // TODO: enforce LE byte order
112 try writer.writeAll(mem.asBytes(&constant.val.toFloat(f64)));
113 },
114 else => return error.TODOImplementMoreWasmCodegen,
115 }
116 },105 },
106 .f32 => {
107 try writer.writeByte(0x43); // f32.const
108 // TODO: enforce LE byte order
109 try writer.writeAll(mem.asBytes(&inst.val.toFloat(f32)));
110 },
111 .f64 => {
112 try writer.writeByte(0x44); // f64.const
113 // TODO: enforce LE byte order
114 try writer.writeAll(mem.asBytes(&inst.val.toFloat(f64)));
115 },
116 .void => {},
117 else => return error.TODOImplementMoreWasmCodegen,117 else => return error.TODOImplementMoreWasmCodegen,
118 }118 }
119}119}
120
121fn genRet(buf: *ArrayList(u8), decl: *Decl, inst: *Inst.UnOp) !void {
122 try genInst(buf, decl, inst.operand);
123}
124
125fn genCall(buf: *ArrayList(u8), decl: *Decl, inst: *Inst.Call) !void {
126 const func_inst = inst.func.castTag(.constant).?;
127 const func_val = func_inst.val.cast(Value.Payload.Function).?;
128 const target = func_val.func.owner_decl;
129 const target_ty = target.typed_value.most_recent.typed_value.ty;
130
131 if (inst.args.len != 0) return error.TODOImplementMoreWasmCodegen;
132
133 try buf.append(0x10); // call
134
135 // The function index immediate argument will be filled in using this data
136 // in link.Wasm.flush().
137 try decl.fn_link.wasm.?.idx_refs.append(buf.allocator, .{
138 .offset = @intCast(u32, buf.items.len),
139 .decl = target,
140 });
141}
src-self-hosted/link/Wasm.zig+25-1
...@@ -36,6 +36,9 @@ pub const FnData = struct {...@@ -36,6 +36,9 @@ pub const FnData = struct {
36 functype: std.ArrayListUnmanaged(u8) = .{},36 functype: std.ArrayListUnmanaged(u8) = .{},
37 /// Generated code for the body of the function37 /// Generated code for the body of the function
38 code: std.ArrayListUnmanaged(u8) = .{},38 code: std.ArrayListUnmanaged(u8) = .{},
39 /// Locations in the generated code where function indexes must be filled in.
40 /// This must be kept ordered by offset.
41 idx_refs: std.ArrayListUnmanaged(struct { offset: u32, decl: *Module.Decl }) = .{},
39};42};
4043
41base: link.File,44base: link.File,
...@@ -74,6 +77,7 @@ pub fn deinit(self: *Wasm) void {...@@ -74,6 +77,7 @@ pub fn deinit(self: *Wasm) void {
74 for (self.funcs.items) |decl| {77 for (self.funcs.items) |decl| {
75 decl.fn_link.wasm.?.functype.deinit(self.base.allocator);78 decl.fn_link.wasm.?.functype.deinit(self.base.allocator);
76 decl.fn_link.wasm.?.code.deinit(self.base.allocator);79 decl.fn_link.wasm.?.code.deinit(self.base.allocator);
80 decl.fn_link.wasm.?.idx_refs.deinit(self.base.allocator);
77 }81 }
78 self.funcs.deinit(self.base.allocator);82 self.funcs.deinit(self.base.allocator);
79}83}
...@@ -87,6 +91,7 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {...@@ -87,6 +91,7 @@ pub fn updateDecl(self: *Wasm, module: *Module, decl: *Module.Decl) !void {
87 if (decl.fn_link.wasm) |*fn_data| {91 if (decl.fn_link.wasm) |*fn_data| {
88 fn_data.functype.items.len = 0;92 fn_data.functype.items.len = 0;
89 fn_data.code.items.len = 0;93 fn_data.code.items.len = 0;
94 fn_data.idx_refs.items.len = 0;
90 } else {95 } else {
91 decl.fn_link.wasm = .{};96 decl.fn_link.wasm = .{};
92 try self.funcs.append(self.base.allocator, decl);97 try self.funcs.append(self.base.allocator, decl);
...@@ -114,6 +119,7 @@ pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void {...@@ -114,6 +119,7 @@ pub fn freeDecl(self: *Wasm, decl: *Module.Decl) void {
114 _ = self.funcs.swapRemove(self.getFuncidx(decl).?);119 _ = self.funcs.swapRemove(self.getFuncidx(decl).?);
115 decl.fn_link.wasm.?.functype.deinit(self.base.allocator);120 decl.fn_link.wasm.?.functype.deinit(self.base.allocator);
116 decl.fn_link.wasm.?.code.deinit(self.base.allocator);121 decl.fn_link.wasm.?.code.deinit(self.base.allocator);
122 decl.fn_link.wasm.?.idx_refs.deinit(self.base.allocator);
117 decl.fn_link.wasm = null;123 decl.fn_link.wasm = null;
118}124}
119125
...@@ -190,7 +196,25 @@ pub fn flush(self: *Wasm, module: *Module) !void {...@@ -190,7 +196,25 @@ pub fn flush(self: *Wasm, module: *Module) !void {
190 // Code section196 // Code section
191 {197 {
192 const header_offset = try reserveVecSectionHeader(file);198 const header_offset = try reserveVecSectionHeader(file);
193 for (self.funcs.items) |decl| try file.writeAll(decl.fn_link.wasm.?.code.items);199 const writer = file.writer();
200 for (self.funcs.items) |decl| {
201 const fn_data = &decl.fn_link.wasm.?;
202
203 // Write the already generated code to the file, inserting
204 // function indexes where required.
205 var current: u32 = 0;
206 for (fn_data.idx_refs.items) |idx_ref| {
207 try writer.writeAll(fn_data.code.items[current..idx_ref.offset]);
208 current = idx_ref.offset;
209 // Use a fixed width here to make calculating the code size
210 // in codegen.wasm.genCode() simpler.
211 var buf: [5]u8 = undefined;
212 leb.writeUnsignedFixed(5, &buf, self.getFuncidx(idx_ref.decl).?);
213 try writer.writeAll(&buf);
214 }
215
216 try writer.writeAll(fn_data.code.items[current..]);
217 }
194 try writeVecSectionHeader(218 try writeVecSectionHeader(
195 file,219 file,
196 header_offset,220 header_offset,
test/stage2/compare_output.zig+26-1
...@@ -546,28 +546,53 @@ pub fn addCases(ctx: *TestContext) !void {...@@ -546,28 +546,53 @@ pub fn addCases(ctx: *TestContext) !void {
546 }546 }
547547
548 {548 {
549 var case = ctx.exe("wasm returns", wasi);549 var case = ctx.exe("wasm function calls", wasi);
550550
551 case.addCompareOutput(551 case.addCompareOutput(
552 \\export fn _start() u32 {552 \\export fn _start() u32 {
553 \\ foo();
554 \\ bar();
553 \\ return 42;555 \\ return 42;
554 \\}556 \\}
557 \\fn foo() void {
558 \\ bar();
559 \\ bar();
560 \\}
561 \\fn bar() void {}
555 ,562 ,
556 "42\n",563 "42\n",
557 );564 );
558565
559 case.addCompareOutput(566 case.addCompareOutput(
560 \\export fn _start() i64 {567 \\export fn _start() i64 {
568 \\ bar();
569 \\ foo();
570 \\ foo();
571 \\ bar();
572 \\ foo();
573 \\ bar();
561 \\ return 42;574 \\ return 42;
562 \\}575 \\}
576 \\fn foo() void {
577 \\ bar();
578 \\}
579 \\fn bar() void {}
563 ,580 ,
564 "42\n",581 "42\n",
565 );582 );
566583
567 case.addCompareOutput(584 case.addCompareOutput(
568 \\export fn _start() f32 {585 \\export fn _start() f32 {
586 \\ bar();
587 \\ foo();
569 \\ return 42.0;588 \\ return 42.0;
570 \\}589 \\}
590 \\fn foo() void {
591 \\ bar();
592 \\ bar();
593 \\ bar();
594 \\}
595 \\fn bar() void {}
571 ,596 ,
572 // This is what you get when you take the bits of the IEE-754597 // This is what you get when you take the bits of the IEE-754
573 // representation of 42.0 and reinterpret them as an unsigned598 // representation of 42.0 and reinterpret them as an unsigned