1source: []const u8,
2args: std.StringHashMapUnmanaged(Operand) = .empty,
3
4pub const Operand = union(enum) {
5 register: Register,
6 signed_imm: i64,
7 unsigned_imm: u64,
8};
9
10pub fn deinit(as: *Assemble, gpa: std.mem.Allocator) void {
11 as.args.deinit(gpa);
12}
13
14pub fn nextLine(as: *Assemble) []const u8 {
15 const line_len = std.mem.findScalar(u8, as.source, '\n') orelse {
16 const line = as.source;
17 as.source = "";
18 return line;
19 };
20 const line = as.source[0..line_len];
21 as.source = as.source[line_len + 1 ..];
22 return line;
23}
24
25pub fn parseLine(as: *Assemble, orig_line: []const u8) !?Instruction {
26 var line = orig_line;
27
28 // strip comment
29 if (std.mem.find(u8, line, "//")) |comment_i| line = line[comment_i..];
30
31 var token_it = std.mem.tokenizeAny(u8, line, " \t");
32 if (token_it.next()) |mnemonic_str| {
33 log.debug("- '{s}'", .{line});
34 log.debug(" - mnemonic: {s}", .{mnemonic_str});
35 var op_it: OperandIterator = .init(as, token_it.rest());
36 const instruction = parseInstruction(mnemonic_str, &op_it) orelse return error.InvalidSyntax;
37 if (!op_it.isEnd()) {
38 log.debug("find unrecognized operands", .{});
39 return error.InvalidSyntax;
40 }
41 return instruction;
42 } else return null;
43}
44
45const OperandIterator = struct {
46 as: *Assemble,
47 iter: std.mem.SplitIterator(u8, .scalar),
48
49 fn init(as: *Assemble, ops: []const u8) OperandIterator {
50 log.debug(" - operands: {s}", .{ops});
51 return .{
52 .as = as,
53 .iter = std.mem.splitScalar(u8, ops, ','),
54 };
55 }
56
57 fn isEnd(it: *OperandIterator) bool {
58 return it.iter.peek() == null;
59 }
60
61 fn next(it: *OperandIterator) ?[]const u8 {
62 if (it.iter.next()) |op| {
63 const res = std.mem.trim(u8, op, " \t");
64 log.debug(" - {s}", .{res});
65 return res;
66 }
67 return null;
68 }
69
70 fn tryResolveArg(it: *OperandIterator, tmpl: []const u8) !?*Operand {
71 if (tmpl.len < 2)
72 return null;
73 if (tmpl[0] == '%' and tmpl[1] == '[' and tmpl[tmpl.len - 1] == ']') {
74 const arg_name = tmpl[2..][0 .. tmpl.len - 3];
75 if (it.as.args.getPtr(arg_name)) |arg_op|
76 return arg_op;
77 }
78 return null;
79 }
80
81 fn nextReg(it: *OperandIterator) ?Register {
82 if (it.next()) |name| {
83 return if (try it.tryResolveArg(name)) |arg_op|
84 switch (arg_op.*) {
85 .register => |reg| reg,
86 else => null,
87 }
88 else
89 Register.parse(name);
90 }
91 return null;
92 }
93
94 fn nextImm(it: *OperandIterator, T: type) ?T {
95 if (it.next()) |imm_str| {
96 return if (try it.tryResolveArg(imm_str)) |arg_op|
97 switch (arg_op.*) {
98 inline .signed_imm, .unsigned_imm => |imm| if (std.math.cast(T, imm)) |imm_cast|
99 imm_cast
100 else
101 null,
102 else => null,
103 }
104 else
105 std.fmt.parseInt(T, imm_str, 0) catch null;
106 }
107 return null;
108 }
109};
110
111fn parseInstruction(mnemonic: []const u8, ops: *OperandIterator) ?Instruction {
112 @setEvalBranchQuota(3_000);
113
114 // find override matchers
115 inline for (@typeInfo(matcher_overrides).@"struct".decl_names) |decl| {
116 if (mnemonicEql(decl, mnemonic)) {
117 const matcher = @field(matcher_overrides, decl);
118 return switch (@typeInfo(@TypeOf(matcher))) {
119 .@"fn" => matcher(ops),
120 .enum_literal => defaultMatcher(@field(Mnemonic, decl), ops),
121 .null => return null,
122 else => unreachable,
123 };
124 }
125 }
126
127 // find default matchers
128 inline for (@typeInfo(@TypeOf(inst_formats.instructions)).@"struct".field_names) |decl| {
129 if (@hasDecl(matcher_overrides, decl)) continue;
130 if (mnemonicEql(decl, mnemonic))
131 return defaultMatcher(@field(Mnemonic, decl), ops);
132 }
133
134 log.debug(" unmatched mnemonic", .{});
135 return null;
136}
137
138fn mnemonicEql(mnemonic: []const u8, rhs: []const u8) bool {
139 if (mnemonic.len != rhs.len) return false;
140 for (mnemonic, rhs) |l, r| {
141 assert(!std.ascii.isUpper(l));
142 if (l != std.ascii.toLower(r)) return false;
143 }
144 return true;
145}
146
147fn defaultMatcher(comptime mnemonic: Mnemonic, ops: *OperandIterator) ?Instruction {
148 const inst_info = @field(inst_formats.instructions, @tagName(mnemonic));
149 const format = if (@hasField(@TypeOf(inst_info), "orig_format") and !@hasField(@TypeOf(inst_info), "orig_name"))
150 inst_info.orig_format
151 else
152 inst_info.format;
153 // TODO check features
154 return defaultMatcherFormat(@tagName(format), inst_info.word, ops);
155}
156
157fn defaultMatcherFormat(comptime format: []const u8, word: u32, ops: *OperandIterator) ?Instruction {
158 const format_info = @field(inst_formats.formats, format);
159 const encodeFn = @field(encoding.Instruction, "encode" ++ format);
160 const EncodeArgs = std.meta.ArgsTuple(@TypeOf(encodeFn));
161 var encode_args: EncodeArgs = undefined;
162 encode_args[0] = word;
163 inline for (format_info.slots, 1..) |slot, slot_i| {
164 const Slot = @TypeOf(slot);
165 if (@hasField(Slot, "reg")) {
166 const class = slot.reg.class;
167 const reg = ops.nextReg() orelse return null;
168 if (reg.class() != switch (class) {
169 .int => .int,
170 .fp, .lsx, .lasx => .fp,
171 .fcc => .fcc,
172 .lbt_scratch => .int,
173 else => unreachable,
174 })
175 return null;
176 encode_args[slot_i] = reg;
177 } else if (@hasField(Slot, "imm")) {
178 const signedness = @field(std.builtin.Signedness, @tagName(slot.imm.signedness));
179 const ImmValue = @Int(signedness, slot.imm.length);
180 encode_args[slot_i] = ops.nextImm(ImmValue) orelse return null;
181 } else {
182 @compileLog("Current slot:", slot);
183 @compileError("Invalid operand slot info");
184 }
185 }
186 return @call(.always_inline, encodeFn, encode_args);
187}
188
189const matcher_overrides = struct {
190 const b = null;
191 const bl = null;
192 const beqz = null;
193 const bnez = null;
194 const bceqz = null;
195 const bcnez = null;
196 const bgt = null;
197 const bgtu = null;
198 const ble = null;
199 const bleu = null;
200
201 const @"xxx.unknown.1" = null;
202 const csrrd = null;
203 const csrwr = null;
204 const gcsrrd = null;
205 const gcsrwr = null;
206 const csrxchg = null;
207 const cacop = null;
208 const invtlb = null;
209 const tlbinv = null;
210 const preld = null;
211 const preldx = null;
212 const dbcl = null;
213 const ertn = null;
214 const pcaddi = null;
215 const @"ext.w.b" = null;
216 const @"ext.w.h" = null;
217 const @"ldptr.w" = null;
218 const @"ldptr.d" = null;
219 const @"stptr.w" = null;
220 const @"stptr.d" = null;
221 const @"bitrev.w" = null;
222 const @"bitrev.d" = null;
223 const @"bitrev.4b" = null;
224 const @"bitrev.8b" = null;
225 const @"asrtle.d" = null;
226 const @"asrtgt.d" = null;
227 const @"lu32i.d" = null;
228 const lu52i = null;
229 const @"alsl.w" = null;
230 const @"alsl.wu" = null;
231 const @"alsl.d" = null;
232 const @"bytepick.w" = null;
233 const @"bytepick.d" = null;
234
235 pub fn move(ops: *OperandIterator) ?Instruction {
236 const rd = ops.nextReg() orelse return null;
237 const rj = ops.nextReg() orelse return null;
238 return .ori(rd, rj, 0);
239 }
240
241 pub fn nop(_: *OperandIterator) ?Instruction {
242 return .andi(.zero, .zero, 0);
243 }
244};
245
246const Assemble = @This();
247const assert = std.debug.assert;
248const encoding = @import("encoding.zig");
249const bits = @import("bits.zig");
250const Instruction = encoding.Instruction;
251const Mnemonic = encoding.Mnemonic;
252const Register = bits.Register;
253const std = @import("std");
254const log = std.log.scoped(.@"asm");
255const inst_formats = @import("inst_formats.zon");