Merge pull request #5864 from pixelherodev/cbe

CBE: get basic returns working
This commit is contained in:
Andrew Kelley 2020-07-13 07:07:27 +00:00 committed by GitHub
commit 1cab40d783
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 271 additions and 153 deletions

View File

@ -989,14 +989,22 @@ pub fn performAllTheWork(self: *Module) error{OutOfMemory}!void {
error.AnalysisFail => {
decl.analysis = .dependency_failure;
},
error.CGenFailure => {
// Error is handled by CBE, don't try adding it again
},
else => {
try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
self.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
self.gpa,
decl.src(),
"unable to codegen: {}",
.{@errorName(err)},
));
const result = self.failed_decls.getOrPutAssumeCapacity(decl);
if (result.found_existing) {
std.debug.panic("Internal error: attempted to override error '{}' with 'unable to codegen: {}'", .{ result.entry.value.msg, @errorName(err) });
} else {
result.entry.value = try ErrorMsg.create(
self.gpa,
decl.src(),
"unable to codegen: {}",
.{@errorName(err)},
);
}
decl.analysis = .codegen_failure_retryable;
},
};
@ -1300,6 +1308,20 @@ fn astGenExpr(self: *Module, scope: *Scope, ast_node: *ast.Node) InnerError!*zir
fn astGenInfixOp(self: *Module, scope: *Scope, infix_node: *ast.Node.InfixOp) InnerError!*zir.Inst {
switch (infix_node.op) {
.Assign => {
if (infix_node.lhs.id == .Identifier) {
const ident = @fieldParentPtr(ast.Node.Identifier, "base", infix_node.lhs);
const tree = scope.tree();
const ident_name = tree.tokenSlice(ident.token);
if (std.mem.eql(u8, ident_name, "_")) {
return self.astGenExpr(scope, infix_node.rhs);
} else {
return self.failNode(scope, &infix_node.base, "TODO implement infix operator assign", .{});
}
} else {
return self.failNode(scope, &infix_node.base, "TODO implement infix operator assign", .{});
}
},
.Add => {
const lhs = try self.astGenExpr(scope, infix_node.lhs);
const rhs = try self.astGenExpr(scope, infix_node.rhs);

View File

@ -1,9 +1,11 @@
const link = @import("link.zig");
const Module = @import("Module.zig");
const ir = @import("ir.zig");
const std = @import("std");
const Inst = @import("ir.zig").Inst;
const Value = @import("value.zig").Value;
const Type = @import("type.zig").Type;
const std = @import("std");
const C = link.File.C;
const Decl = Module.Decl;
@ -26,6 +28,14 @@ fn renderType(file: *C, writer: std.ArrayList(u8).Writer, T: Type, src: usize) !
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}),
}
}
@ -37,132 +47,159 @@ fn renderFunctionSignature(file: *C, writer: std.ArrayList(u8).Writer, decl: *De
const name = try map(file.allocator, mem.spanZ(decl.name));
defer file.allocator.free(name);
try writer.print(" {}(", .{name});
if (tv.ty.fnParamLen() == 0) {
try writer.writeAll("void)");
} else {
if (tv.ty.fnParamLen() == 0)
try writer.writeAll("void)")
else
return file.fail(decl.src(), "TODO implement parameters", .{});
}
}
pub fn generate(file: *C, decl: *Decl) !void {
const writer = file.main.writer();
const header = file.header.writer();
const tv = decl.typed_value.most_recent.typed_value;
switch (tv.ty.zigTypeTag()) {
.Fn => {
try renderFunctionSignature(file, writer, decl);
try writer.writeAll(" {");
const func: *Module.Fn = tv.val.cast(Value.Payload.Function).?.func;
const instructions = func.analysis.success.instructions;
if (instructions.len > 0) {
for (instructions) |inst| {
try writer.writeAll("\n\t");
switch (inst.tag) {
.assembly => {
const as = inst.cast(ir.Inst.Assembly).?.args;
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];
if (arg.cast(ir.Inst.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\t", .{ reg, reg, c.val.toUnsignedInt() });
} else {
return file.fail(decl.src(), "TODO inline asm {} args", .{c.val.tag()});
}
} else {
return file.fail(decl.src(), "TODO non-constant inline asm args", .{});
}
} else {
return file.fail(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", .{});
}
if (as.inputs.len > 0) {
if (as.output == null) {
try writer.writeAll(" :");
}
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];
if (index > 0) {
try writer.writeAll(", ");
}
if (arg.cast(ir.Inst.Constant)) |c| {
try writer.print("\"\"({}_constant)", .{reg});
} else {
// This is blocked by the earlier test
unreachable;
}
} else {
// This is blocked by the earlier test
unreachable;
}
}
}
try writer.writeAll(");");
},
.call => {
const call = inst.cast(ir.Inst.Call).?.args;
if (call.func.cast(ir.Inst.Constant)) |func_inst| {
if (func_inst.val.cast(Value.Payload.Function)) |func_val| {
const target = func_val.func.owner_decl;
const tname = mem.spanZ(target.name);
if (file.called.get(tname) == null) {
try file.called.put(tname, void{});
try renderFunctionSignature(file, header, target);
try header.writeAll(";\n");
}
try writer.print("{}();", .{tname});
} else {
return file.fail(decl.src(), "TODO non-function call target?", .{});
}
if (call.args.len != 0) {
return file.fail(decl.src(), "TODO function arguments", .{});
}
} else {
return file.fail(decl.src(), "TODO non-constant call inst?", .{});
}
},
else => |e| {
return file.fail(decl.src(), "TODO {}", .{e});
},
}
}
try writer.writeAll("\n");
}
try writer.writeAll("}\n\n");
},
.Array => {
// TODO: prevent inline asm constants from being emitted
const name = try map(file.allocator, mem.span(decl.name));
defer file.allocator.free(name);
if (tv.val.cast(Value.Payload.Bytes)) |payload| {
if (tv.ty.arraySentinel()) |sentinel| {
if (sentinel.toUnsignedInt() == 0) {
try file.constants.writer().print("const char *const {} = \"{}\";\n", .{ name, payload.data });
} else {
return file.fail(decl.src(), "TODO byte arrays with non-zero sentinels", .{});
}
} else {
return file.fail(decl.src(), "TODO byte arrays without sentinels", .{});
}
} else {
return file.fail(decl.src(), "TODO non-byte arrays", .{});
}
},
else => |e| {
return file.fail(decl.src(), "TODO {}", .{e});
},
switch (decl.typed_value.most_recent.typed_value.ty.zigTypeTag()) {
.Fn => try genFn(file, decl),
.Array => try genArray(file, decl),
else => |e| return file.fail(decl.src(), "TODO {}", .{e}),
}
}
fn genArray(file: *C, decl: *Decl) !void {
const tv = decl.typed_value.most_recent.typed_value;
// TODO: prevent inline asm constants from being emitted
const name = try map(file.allocator, mem.span(decl.name));
defer file.allocator.free(name);
if (tv.val.cast(Value.Payload.Bytes)) |payload|
if (tv.ty.arraySentinel()) |sentinel|
if (sentinel.toUnsignedInt() == 0)
try file.constants.writer().print("const char *const {} = \"{}\";\n", .{ name, payload.data })
else
return file.fail(decl.src(), "TODO byte arrays with non-zero sentinels", .{})
else
return file.fail(decl.src(), "TODO byte arrays without sentinels", .{})
else
return file.fail(decl.src(), "TODO non-byte arrays", .{});
}
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);
try writer.writeAll(" {");
const func: *Module.Fn = tv.val.cast(Value.Payload.Function).?.func;
const instructions = func.analysis.success.instructions;
if (instructions.len > 0) {
for (instructions) |inst| {
try writer.writeAll("\n\t");
switch (inst.tag) {
.assembly => try genAsm(file, inst.cast(Inst.Assembly).?, decl),
.call => try genCall(file, inst.cast(Inst.Call).?, decl),
.ret => try genRet(file, inst.cast(Inst.Ret).?, decl, tv.ty.fnReturnType()),
else => |e| return file.fail(decl.src(), "TODO {}", .{e}),
}
}
try writer.writeAll("\n");
}
try writer.writeAll("}\n\n");
}
fn genRet(file: *C, inst: *Inst.Ret, decl: *Decl, expected_return_type: Type) !void {
const writer = file.main.writer();
const ret_value = inst.args.operand;
const value = ret_value.value().?;
if (expected_return_type.eql(ret_value.ty))
return file.fail(decl.src(), "TODO return {}", .{expected_return_type})
else if (expected_return_type.isInt() and ret_value.ty.tag() == .comptime_int)
if (value.intFitsInType(expected_return_type, file.options.target))
if (expected_return_type.intInfo(file.options.target).bits <= 64)
try writer.print("return {};", .{value.toUnsignedInt()})
else
return file.fail(decl.src(), "TODO return ints > 64 bits", .{})
else
return file.fail(decl.src(), "comptime int {} does not fit in {}", .{ value.toUnsignedInt(), expected_return_type })
else
return file.fail(decl.src(), "return type mismatch: expected {}, found {}", .{ expected_return_type, ret_value.ty });
}
fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void {
const writer = file.main.writer();
const header = file.header.writer();
if (inst.args.func.cast(Inst.Constant)) |func_inst| {
if (func_inst.val.cast(Value.Payload.Function)) |func_val| {
const target = func_val.func.owner_decl;
const target_ty = target.typed_value.most_recent.typed_value.ty;
const ret_ty = target_ty.fnReturnType().tag();
if (target_ty.fnReturnType().hasCodeGenBits() and inst.base.isUnused()) {
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);
try header.writeAll(";\n");
}
try writer.print("{}();", .{tname});
} else {
return file.fail(decl.src(), "TODO non-function call target?", .{});
}
if (inst.args.args.len != 0) {
return file.fail(decl.src(), "TODO function arguments", .{});
}
} else {
return file.fail(decl.src(), "TODO non-constant call inst?", .{});
}
}
fn genAsm(file: *C, inst: *Inst.Assembly, decl: *Decl) !void {
const as = inst.args;
const writer = file.main.writer();
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];
if (arg.cast(Inst.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\t", .{ reg, reg, c.val.toUnsignedInt() });
} else {
return file.fail(decl.src(), "TODO inline asm {} args", .{c.val.tag()});
}
} else {
return file.fail(decl.src(), "TODO non-constant inline asm args", .{});
}
} else {
return file.fail(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", .{});
}
if (as.inputs.len > 0) {
if (as.output == null) {
try writer.writeAll(" :");
}
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];
if (index > 0) {
try writer.writeAll(", ");
}
if (arg.cast(Inst.Constant)) |c| {
try writer.print("\"\"({}_constant)", .{reg});
} else {
// This is blocked by the earlier test
unreachable;
}
} else {
// This is blocked by the earlier test
unreachable;
}
}
}
try writer.writeAll(");");
}

View File

@ -921,6 +921,11 @@ pub const Type = extern union {
};
}
/// Returns true if and only if the type is a fixed-width integer.
pub fn isInt(self: Type) bool {
return self.isSignedInt() or self.isUnsignedInt();
}
/// Returns true if and only if the type is a fixed-width, signed integer.
pub fn isSignedInt(self: Type) bool {
return switch (self.tag()) {
@ -975,6 +980,60 @@ pub const Type = extern union {
};
}
/// Returns true if and only if the type is a fixed-width, unsigned integer.
pub fn isUnsignedInt(self: Type) bool {
return switch (self.tag()) {
.f16,
.f32,
.f64,
.f128,
.c_longdouble,
.c_void,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.@"null",
.@"undefined",
.fn_noreturn_no_args,
.fn_void_no_args,
.fn_naked_noreturn_no_args,
.fn_ccc_void_no_args,
.function,
.array,
.single_const_pointer,
.single_const_pointer_to_comptime_int,
.array_u8_sentinel_0,
.const_slice_u8,
.int_signed,
.i8,
.isize,
.c_short,
.c_int,
.c_long,
.c_longlong,
.i16,
.i32,
.i64,
=> false,
.int_unsigned,
.u8,
.usize,
.c_ushort,
.c_uint,
.c_ulong,
.c_ulonglong,
.u16,
.u32,
.u64,
=> true,
};
}
/// Asserts the type is an integer.
pub fn intInfo(self: Type, target: Target) struct { signed: bool, bits: u16 } {
return switch (self.tag()) {

View File

@ -65,26 +65,26 @@ pub fn addCases(ctx: *TestContext) !void {
\\}
\\
);
//ctx.c("basic return", linux_x64,
// \\fn main() u8 {
// \\ return 103;
// \\}
// \\
// \\export fn _start() noreturn {
// \\ _ = main();
// \\}
//,
// \\#include <stdint.h>
// \\
// \\uint8_t main(void);
// \\
// \\noreturn void _start(void) {
// \\ (void)main();
// \\}
// \\
// \\uint8_t main(void) {
// \\ return 103;
// \\}
// \\
//);
ctx.c("basic return", linux_x64,
\\fn main() u8 {
\\ return 103;
\\}
\\
\\export fn _start() noreturn {
\\ _ = main();
\\}
,
\\#include <stdint.h>
\\
\\uint8_t main(void);
\\
\\noreturn void _start(void) {
\\ (void)main();
\\}
\\
\\uint8_t main(void) {
\\ return 103;
\\}
\\
);
}