diff options
| author | Andrew Kelley <andrew@ziglang.org> | 2020-08-12 22:00:14 -0700 |
|---|---|---|
| committer | Andrew Kelley <andrew@ziglang.org> | 2020-08-12 22:00:14 -0700 |
| commit | e043396b242d727cd72fecda265bd4b78a86958a (patch) | |
| tree | 6634cf1996d5e9d406c20bb29aa16fc2fbdc6deb | |
| parent | de4f3f11f735708cf9ffe4bbdbbfa693b6b07916 (diff) | |
| parent | eec53d67abb3a3d894de945f549994a16cb92474 (diff) | |
| download | zig-e043396b242d727cd72fecda265bd4b78a86958a.tar.gz zig-e043396b242d727cd72fecda265bd4b78a86958a.zip | |
Merge branch 'pixelherodev-cbe'
closes #6007
| -rw-r--r-- | src-self-hosted/cbe.h | 15 | ||||
| -rw-r--r-- | src-self-hosted/codegen/c.zig | 239 | ||||
| -rw-r--r-- | src-self-hosted/link.zig | 3 | ||||
| -rw-r--r-- | src-self-hosted/test.zig | 4 | ||||
| -rw-r--r-- | src-self-hosted/value.zig | 75 | ||||
| -rw-r--r-- | test/stage2/cbe.zig | 89 |
6 files changed, 341 insertions, 84 deletions
diff --git a/src-self-hosted/cbe.h b/src-self-hosted/cbe.h index 66e7b8bd3e..854032227d 100644 --- a/src-self-hosted/cbe.h +++ b/src-self-hosted/cbe.h @@ -1,8 +1,15 @@ #if __STDC_VERSION__ >= 201112L -#define noreturn _Noreturn -#elif __GNUC__ && !__STRICT_ANSI__ -#define noreturn __attribute__ ((noreturn)) +#define zig_noreturn _Noreturn +#elif __GNUC__ +#define zig_noreturn __attribute__ ((noreturn)) +#elif _MSC_VER +#define zig_noreturn __declspec(noreturn) #else -#define noreturn +#define zig_noreturn #endif +#if __GNUC__ +#define zig_unreachable() __builtin_unreachable() +#else +#define zig_unreachable() +#endif diff --git a/src-self-hosted/codegen/c.zig b/src-self-hosted/codegen/c.zig index db9d9a1030..f0d3d8367a 100644 --- a/src-self-hosted/codegen/c.zig +++ b/src-self-hosted/codegen/c.zig @@ -17,40 +17,58 @@ fn map(allocator: *std.mem.Allocator, name: []const u8) ![]const u8 { return allocator.dupe(u8, name); } -fn renderType(file: *C, writer: std.ArrayList(u8).Writer, T: Type, src: usize) !void { - if (T.tag() == .usize) { - file.need_stddef = true; - try writer.writeAll("size_t"); - } else { - switch (T.zigTypeTag()) { - .NoReturn => { - file.need_noreturn = true; - try writer.writeAll("noreturn void"); - }, - .Void => try writer.writeAll("void"), - .Int => { - if (T.tag() == .u8) { - file.need_stdint = true; - try writer.writeAll("uint8_t"); - } else { - return file.fail(src, "TODO implement int types", .{}); - } - }, - else => |e| return file.fail(src, "TODO implement type {}", .{e}), - } +fn renderType(ctx: *Context, writer: std.ArrayList(u8).Writer, T: Type) !void { + switch (T.zigTypeTag()) { + .NoReturn => { + try writer.writeAll("zig_noreturn void"); + }, + .Void => try writer.writeAll("void"), + .Int => { + if (T.tag() == .u8) { + ctx.file.need_stdint = true; + try writer.writeAll("uint8_t"); + } else if (T.tag() == .usize) { + ctx.file.need_stddef = true; + try writer.writeAll("size_t"); + } else { + return ctx.file.fail(ctx.decl.src(), "TODO implement int types", .{}); + } + }, + else => |e| return ctx.file.fail(ctx.decl.src(), "TODO implement type {}", .{e}), } } -fn renderFunctionSignature(file: *C, writer: std.ArrayList(u8).Writer, decl: *Decl) !void { +fn renderValue(ctx: *Context, writer: std.ArrayList(u8).Writer, T: Type, val: Value) !void { + switch (T.zigTypeTag()) { + .Int => { + if (T.isSignedInt()) + return writer.print("{}", .{val.toSignedInt()}); + return writer.print("{}", .{val.toUnsignedInt()}); + }, + else => |e| return ctx.file.fail(ctx.decl.src(), "TODO implement value {}", .{e}), + } +} + +fn renderFunctionSignature(ctx: *Context, writer: std.ArrayList(u8).Writer, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; - try renderType(file, writer, tv.ty.fnReturnType(), decl.src()); - const name = try map(file.base.allocator, mem.spanZ(decl.name)); - defer file.base.allocator.free(name); + try renderType(ctx, writer, tv.ty.fnReturnType()); + const name = try map(ctx.file.base.allocator, mem.spanZ(decl.name)); + defer ctx.file.base.allocator.free(name); try writer.print(" {}(", .{name}); - if (tv.ty.fnParamLen() == 0) - try writer.writeAll("void)") - else - return file.fail(decl.src(), "TODO implement parameters", .{}); + var param_len = tv.ty.fnParamLen(); + if (param_len == 0) + try writer.writeAll("void") + else { + var index: usize = 0; + while (index < param_len) : (index += 1) { + if (index > 0) { + try writer.writeAll(", "); + } + try renderType(ctx, writer, tv.ty.fnParamType(index)); + try writer.print(" arg{}", .{index}); + } + } + try writer.writeByte(')'); } pub fn generate(file: *C, decl: *Decl) !void { @@ -78,11 +96,40 @@ fn genArray(file: *C, decl: *Decl) !void { return file.fail(decl.src(), "TODO non-byte arrays", .{}); } +const Context = struct { + file: *C, + decl: *Decl, + inst_map: std.AutoHashMap(*Inst, []u8), + argdex: usize = 0, + unnamed_index: usize = 0, + + fn name(self: *Context) ![]u8 { + const val = try std.fmt.allocPrint(self.file.base.allocator, "__temp_{}", .{self.unnamed_index}); + self.unnamed_index += 1; + return val; + } + + fn deinit(self: *Context) void { + for (self.inst_map.items()) |kv| { + self.file.base.allocator.free(kv.value); + } + self.inst_map.deinit(); + self.* = undefined; + } +}; + fn genFn(file: *C, decl: *Decl) !void { const writer = file.main.writer(); const tv = decl.typed_value.most_recent.typed_value; - try renderFunctionSignature(file, writer, decl); + var ctx = Context{ + .file = file, + .decl = decl, + .inst_map = std.AutoHashMap(*Inst, []u8).init(file.base.allocator), + }; + defer ctx.deinit(); + + try renderFunctionSignature(&ctx, writer, decl); try writer.writeAll(" {"); @@ -91,13 +138,19 @@ fn genFn(file: *C, decl: *Decl) !void { if (instructions.len > 0) { try writer.writeAll("\n"); for (instructions) |inst| { - switch (inst.tag) { - .assembly => try genAsm(file, inst.castTag(.assembly).?, decl), - .call => try genCall(file, inst.castTag(.call).?, decl), - .ret => try genRet(file, inst.castTag(.ret).?, decl, tv.ty.fnReturnType()), - .retvoid => try file.main.writer().print(" return;\n", .{}), - .dbg_stmt => try genDbgStmt(file, inst.castTag(.dbg_stmt).?, decl), + if (switch (inst.tag) { + .assembly => try genAsm(&ctx, inst.castTag(.assembly).?), + .call => try genCall(&ctx, inst.castTag(.call).?), + .ret => try genRet(&ctx, inst.castTag(.ret).?), + .retvoid => try genRetVoid(&ctx), + .arg => try genArg(&ctx), + .dbg_stmt => try genDbgStmt(&ctx, inst.castTag(.dbg_stmt).?), + .breakpoint => try genBreak(&ctx, inst.castTag(.breakpoint).?), + .unreach => try genUnreach(&ctx, inst.castTag(.unreach).?), + .intcast => try genIntCast(&ctx, inst.castTag(.intcast).?), else => |e| return file.fail(decl.src(), "TODO implement C codegen for {}", .{e}), + }) |name| { + try ctx.inst_map.putNoClobber(inst, name); } } } @@ -105,13 +158,40 @@ fn genFn(file: *C, decl: *Decl) !void { try writer.writeAll("}\n\n"); } -fn genRet(file: *C, inst: *Inst.UnOp, decl: *Decl, expected_return_type: Type) !void { - return file.fail(decl.src(), "TODO return {}", .{expected_return_type}); +fn genArg(ctx: *Context) !?[]u8 { + const name = try std.fmt.allocPrint(ctx.file.base.allocator, "arg{}", .{ctx.argdex}); + ctx.argdex += 1; + return name; } -fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { - const writer = file.main.writer(); - const header = file.header.writer(); +fn genRetVoid(ctx: *Context) !?[]u8 { + try ctx.file.main.writer().print(" return;\n", .{}); + return null; +} + +fn genRet(ctx: *Context, inst: *Inst.UnOp) !?[]u8 { + return ctx.file.fail(ctx.decl.src(), "TODO return", .{}); +} + +fn genIntCast(ctx: *Context, inst: *Inst.UnOp) !?[]u8 { + if (inst.base.isUnused()) + return null; + const op = inst.operand; + const writer = ctx.file.main.writer(); + const name = try ctx.name(); + const from = ctx.inst_map.get(op) orelse + return ctx.file.fail(ctx.decl.src(), "Internal error in C backend: intCast argument not found in inst_map", .{}); + try writer.writeAll(" const "); + try renderType(ctx, writer, inst.base.ty); + try writer.print(" {} = (", .{name}); + try renderType(ctx, writer, inst.base.ty); + try writer.print("){};\n", .{from}); + return name; +} + +fn genCall(ctx: *Context, inst: *Inst.Call) !?[]u8 { + const writer = ctx.file.main.writer(); + const header = ctx.file.header.writer(); try writer.writeAll(" "); if (inst.func.castTag(.constant)) |func_inst| { if (func_inst.val.cast(Value.Payload.Function)) |func_val| { @@ -122,52 +202,77 @@ fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { try writer.print("(void)", .{}); } const tname = mem.spanZ(target.name); - if (file.called.get(tname) == null) { - try file.called.put(tname, void{}); - try renderFunctionSignature(file, header, target); + if (ctx.file.called.get(tname) == null) { + try ctx.file.called.put(tname, void{}); + try renderFunctionSignature(ctx, header, target); try header.writeAll(";\n"); } - try writer.print("{}();\n", .{tname}); + try writer.print("{}(", .{tname}); + if (inst.args.len != 0) { + for (inst.args) |arg, i| { + if (i > 0) { + try writer.writeAll(", "); + } + if (arg.cast(Inst.Constant)) |con| { + try renderValue(ctx, writer, arg.ty, con.val); + } else { + return ctx.file.fail(ctx.decl.src(), "TODO call pass arg {}", .{arg}); + } + } + } + try writer.writeAll(");\n"); } else { - return file.fail(decl.src(), "TODO non-function call target?", .{}); - } - if (inst.args.len != 0) { - return file.fail(decl.src(), "TODO function arguments", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO non-function call target?", .{}); } } else { - return file.fail(decl.src(), "TODO non-constant call inst?", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO non-constant call inst?", .{}); } + return null; } -fn genDbgStmt(file: *C, inst: *Inst.NoOp, decl: *Decl) !void { +fn genDbgStmt(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { // TODO emit #line directive here with line number and filename + return null; } -fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl) !void { - const writer = file.main.writer(); +fn genBreak(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { + // TODO ?? + return null; +} + +fn genUnreach(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { + try ctx.file.main.writer().writeAll(" zig_unreachable();\n"); + return null; +} + +fn genAsm(ctx: *Context, as: *Inst.Assembly) !?[]u8 { + const writer = ctx.file.main.writer(); try writer.writeAll(" "); for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; + try writer.writeAll("register "); + try renderType(ctx, writer, arg.ty); + try writer.print(" {}_constant __asm__(\"{}\") = ", .{ reg, reg }); + // TODO merge constant handling into inst_map as well if (arg.castTag(.constant)) |c| { - if (c.val.tag() == .int_u64) { - try writer.writeAll("register "); - try renderType(file, writer, arg.ty, decl.src()); - try writer.print(" {}_constant __asm__(\"{}\") = {};\n ", .{ reg, reg, c.val.toUnsignedInt() }); - } else { - return file.fail(decl.src(), "TODO inline asm {} args", .{c.val.tag()}); - } + try renderValue(ctx, writer, arg.ty, c.val); + try writer.writeAll(";\n "); } else { - return file.fail(decl.src(), "TODO non-constant inline asm args", .{}); + const gop = try ctx.inst_map.getOrPut(arg); + if (!gop.found_existing) { + return ctx.file.fail(ctx.decl.src(), "Internal error in C backend: asm argument not found in inst_map", .{}); + } + try writer.print("{};\n ", .{gop.entry.value}); } } else { - return file.fail(decl.src(), "TODO non-explicit inline asm regs", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO non-explicit inline asm regs", .{}); } } try writer.print("__asm {} (\"{}\"", .{ if (as.is_volatile) @as([]const u8, "volatile") else "", as.asm_source }); if (as.output) |o| { - return file.fail(decl.src(), "TODO inline asm output", .{}); + return ctx.file.fail(ctx.decl.src(), "TODO inline asm output", .{}); } if (as.inputs.len > 0) { if (as.output == null) { @@ -181,12 +286,7 @@ fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl) !void { if (index > 0) { try writer.writeAll(", "); } - if (arg.castTag(.constant)) |c| { - try writer.print("\"\"({}_constant)", .{reg}); - } else { - // This is blocked by the earlier test - unreachable; - } + try writer.print("\"\"({}_constant)", .{reg}); } else { // This is blocked by the earlier test unreachable; @@ -194,4 +294,5 @@ fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl) !void { } } try writer.writeAll(");\n"); + return null; } diff --git a/src-self-hosted/link.zig b/src-self-hosted/link.zig index 431d510b01..7c5e645fb5 100644 --- a/src-self-hosted/link.zig +++ b/src-self-hosted/link.zig @@ -202,7 +202,6 @@ pub const File = struct { called: std.StringHashMap(void), need_stddef: bool = false, need_stdint: bool = false, - need_noreturn: bool = false, error_msg: *Module.ErrorMsg = undefined, pub fn openPath(allocator: *Allocator, dir: fs.Dir, sub_path: []const u8, options: Options) !*File { @@ -230,7 +229,7 @@ pub const File = struct { return &c_file.base; } - pub fn fail(self: *C, src: usize, comptime format: []const u8, args: anytype) !void { + pub fn fail(self: *C, src: usize, comptime format: []const u8, args: anytype) error{AnalysisFail, OutOfMemory} { self.error_msg = try Module.ErrorMsg.create(self.base.allocator, src, format, args); return error.AnalysisFail; } diff --git a/src-self-hosted/test.zig b/src-self-hosted/test.zig index 7d4cc7d563..265c26b2dc 100644 --- a/src-self-hosted/test.zig +++ b/src-self-hosted/test.zig @@ -478,6 +478,10 @@ pub const TestContext = struct { for (all_errors.list) |err| { std.debug.warn(":{}:{}: error: {}\n================\n", .{ err.line + 1, err.column + 1, err.msg }); } + if (case.cbe) { + const C = module.bin_file.cast(link.File.C).?; + std.debug.warn("Generated C: \n===============\n{}\n\n===========\n\n", .{C.main.items}); + } std.debug.warn("Test failed.\n", .{}); std.process.exit(1); } diff --git a/src-self-hosted/value.zig b/src-self-hosted/value.zig index e71805dc5b..b2fad9207d 100644 --- a/src-self-hosted/value.zig +++ b/src-self-hosted/value.zig @@ -568,6 +568,81 @@ pub const Value = extern union { } } + /// Asserts the value is an integer and it fits in a i64 + pub fn toSignedInt(self: Value) i64 { + switch (self.tag()) { + .ty, + .int_type, + .u8_type, + .i8_type, + .u16_type, + .i16_type, + .u32_type, + .i32_type, + .u64_type, + .i64_type, + .usize_type, + .isize_type, + .c_short_type, + .c_ushort_type, + .c_int_type, + .c_uint_type, + .c_long_type, + .c_ulong_type, + .c_longlong_type, + .c_ulonglong_type, + .c_longdouble_type, + .f16_type, + .f32_type, + .f64_type, + .f128_type, + .c_void_type, + .bool_type, + .void_type, + .type_type, + .anyerror_type, + .comptime_int_type, + .comptime_float_type, + .noreturn_type, + .null_type, + .undefined_type, + .fn_noreturn_no_args_type, + .fn_void_no_args_type, + .fn_naked_noreturn_no_args_type, + .fn_ccc_void_no_args_type, + .single_const_pointer_to_comptime_int_type, + .const_slice_u8_type, + .null_value, + .function, + .ref_val, + .decl_ref, + .elem_ptr, + .bytes, + .repeated, + .float_16, + .float_32, + .float_64, + .float_128, + .void_value, + .unreachable_value, + .empty_array, + => unreachable, + + .undef => unreachable, + + .zero, + .bool_false, + => return 0, + + .bool_true => return 1, + + .int_u64 => return @intCast(i64, self.cast(Payload.Int_i64).?.int), + .int_i64 => return self.cast(Payload.Int_i64).?.int, + .int_big_positive => return self.cast(Payload.IntBigPositive).?.asBigInt().to(i64) catch unreachable, + .int_big_negative => return self.cast(Payload.IntBigNegative).?.asBigInt().to(i64) catch unreachable, + } + } + pub fn toBool(self: Value) bool { return switch (self.tag()) { .bool_true => true, diff --git a/test/stage2/cbe.zig b/test/stage2/cbe.zig index 2c3f0631c8..5e2d56b5ed 100644 --- a/test/stage2/cbe.zig +++ b/test/stage2/cbe.zig @@ -12,7 +12,7 @@ pub fn addCases(ctx: *TestContext) !void { ctx.c("empty start function", linux_x64, \\export fn _start() noreturn {} , - \\noreturn void _start(void) {} + \\zig_noreturn void _start(void) {} \\ ); ctx.c("less empty start function", linux_x64, @@ -22,19 +22,19 @@ pub fn addCases(ctx: *TestContext) !void { \\ main(); \\} , - \\noreturn void main(void); + \\zig_noreturn void main(void); \\ - \\noreturn void _start(void) { + \\zig_noreturn void _start(void) { \\ main(); \\} \\ - \\noreturn void main(void) {} + \\zig_noreturn void main(void) {} \\ ); // TODO: implement return values // TODO: figure out a way to prevent asm constants from being generated ctx.c("inline asm", linux_x64, - \\fn exitGood() void { + \\fn exitGood() noreturn { \\ asm volatile ("syscall" \\ : \\ : [number] "{rax}" (231), @@ -48,21 +48,92 @@ pub fn addCases(ctx: *TestContext) !void { , \\#include <stddef.h> \\ - \\void exitGood(void); + \\zig_noreturn void exitGood(void); \\ \\const char *const exitGood__anon_0 = "{rax}"; \\const char *const exitGood__anon_1 = "{rdi}"; \\const char *const exitGood__anon_2 = "syscall"; \\ - \\noreturn void _start(void) { + \\zig_noreturn void _start(void) { \\ exitGood(); \\} \\ - \\void exitGood(void) { + \\zig_noreturn void exitGood(void) { \\ register size_t rax_constant __asm__("rax") = 231; \\ register size_t rdi_constant __asm__("rdi") = 0; \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); - \\ return; + \\} + \\ + ); + ctx.c("exit with parameter", linux_x64, + \\export fn _start() noreturn { + \\ exit(0); + \\} + \\ + \\fn exit(code: usize) noreturn { + \\ asm volatile ("syscall" + \\ : + \\ : [number] "{rax}" (231), + \\ [arg1] "{rdi}" (code) + \\ ); + \\ unreachable; + \\} + \\ + , + \\#include <stddef.h> + \\ + \\zig_noreturn void exit(size_t arg0); + \\ + \\const char *const exit__anon_0 = "{rax}"; + \\const char *const exit__anon_1 = "{rdi}"; + \\const char *const exit__anon_2 = "syscall"; + \\ + \\zig_noreturn void _start(void) { + \\ exit(0); + \\} + \\ + \\zig_noreturn void exit(size_t arg0) { + \\ register size_t rax_constant __asm__("rax") = 231; + \\ register size_t rdi_constant __asm__("rdi") = arg0; + \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); + \\ zig_unreachable(); + \\} + \\ + ); + ctx.c("exit with u8 parameter", linux_x64, + \\export fn _start() noreturn { + \\ exit(0); + \\} + \\ + \\fn exit(code: u8) noreturn { + \\ asm volatile ("syscall" + \\ : + \\ : [number] "{rax}" (231), + \\ [arg1] "{rdi}" (code) + \\ ); + \\ unreachable; + \\} + \\ + , + \\#include <stddef.h> + \\#include <stdint.h> + \\ + \\zig_noreturn void exit(uint8_t arg0); + \\ + \\const char *const exit__anon_0 = "{rax}"; + \\const char *const exit__anon_1 = "{rdi}"; + \\const char *const exit__anon_2 = "syscall"; + \\ + \\zig_noreturn void _start(void) { + \\ exit(0); + \\} + \\ + \\zig_noreturn void exit(uint8_t arg0) { + \\ const size_t __temp_0 = (size_t)arg0; + \\ register size_t rax_constant __asm__("rax") = 231; + \\ register size_t rdi_constant __asm__("rdi") = __temp_0; + \\ __asm volatile ("syscall" :: ""(rax_constant), ""(rdi_constant)); + \\ zig_unreachable(); \\} \\ ); |
