MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
emit.cpp
Go to the documentation of this file.
1#include "mim/plug/x86/emit.h"
2
3#include <bit>
4#include <map>
5#include <print>
6#include <ranges>
7
8#include <mim/plugin.h>
9
10#include <mim/plug/mach/emit.h>
11#include <mim/plug/math/math.h>
12
13#include "mim/plug/x86/insn.h"
14#include "mim/plug/x86/target.h"
15#include "mim/plug/x86/x86.h"
16
17namespace mim::plug::x86 {
18
19using namespace std::string_literals;
20using mach::Reg;
21using mach::Src;
22
23namespace {
24
25using Names = std::array<std::string_view, 4>;
26
27// clang-format off
28constexpr std::array<Names, 16> names = {{
29 {"%al", "%ax", "%eax", "%rax"}, {"%cl", "%cx", "%ecx", "%rcx"},
30 {"%dl", "%dx", "%edx", "%rdx"}, {"%bl", "%bx", "%ebx", "%rbx"},
31 {"%spl", "%sp", "%esp", "%rsp"}, {"%bpl", "%bp", "%ebp", "%rbp"},
32 {"%sil", "%si", "%esi", "%rsi"}, {"%dil", "%di", "%edi", "%rdi"},
33 {"%r8b", "%r8w", "%r8d", "%r8" }, {"%r9b", "%r9w", "%r9d", "%r9" },
34 {"%r10b", "%r10w", "%r10d", "%r10"}, {"%r11b", "%r11w", "%r11d", "%r11"},
35 {"%r12b", "%r12w", "%r12d", "%r12"}, {"%r13b", "%r13w", "%r13d", "%r13"},
36 {"%r14b", "%r14w", "%r14d", "%r14"}, {"%r15b", "%r15w", "%r15d", "%r15"},
37}};
38// clang-format on
39
40constexpr std::array<std::string_view, 16> ccs
41 = {"o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"};
42
43/// Per `x86.fcmp` subtag: the `setcc` after `ucomiss`, and the result of an unordered comparison where `setcc` errs.
44/// An unordered `ucomiss` sets ZF, PF, and CF; isel swaps operands so that only `e` and `une` need the fixup.
45constexpr std::array<std::pair<std::string_view, std::optional<bool>>, 16> fccs = {{
46 // clang-format off
47 {"", {}}, {"e", false}, {"b", false}, {"be", false}, {"a", {}}, {"ae", {}}, {"ne", {}}, {"np", {}},
48 {"p", {}}, {"e", {}}, {"b", {}}, {"be", {}}, {"a", true}, {"ae", true}, {"ne", true}, {"", {}},
49 // clang-format on
50}};
51constexpr size_t Fcmp_T = 15;
52
53size_t log_bytes(nat_t w) { return std::countr_zero(w / 8); }
54std::string_view name(size_t r, nat_t w) { return names[r][log_bytes(w)]; }
55char suffix(nat_t w) { return "bwlq"[log_bytes(w)]; }
56/// An 8- or 16-bit write would merge with the stale upper bits, so whatever ignores them writes 32 bits.
57nat_t wide(nat_t w) { return std::max<nat_t>(w, 32); }
58std::string xmm(size_t r) { return std::format("%xmm{}", r); }
59/// The single/double suffix of a floating-point mnemonic.
60std::string_view fsz(nat_t w) { return w == 64 ? "sd" : "ss"; }
61
62/// Mnemonic of a floating-point arithmetic instruction without its single/double suffix.
63std::string_view farith(flags_t id) {
64 if (id == Annex::Base<fadd>) return "add";
65 if (id == Annex::Base<fsub>) return "sub";
66 if (id == Annex::Base<fmul>) return "mul";
67 return "div";
68}
69
70/// Mnemonic of a two-address ALU instruction.
71std::string_view alu(flags_t id) {
72 // clang-format off
73 if (id == Annex::Base<add>) return "add";
74 if (id == Annex::Base<sub>) return "sub";
75 if (id == Annex::Base<and_>) return "and";
76 if (id == Annex::Base<or_>) return "or";
77 if (id == Annex::Base<xor_>) return "xor";
78 if (id == Annex::Base<imul>) return "imul";
79 // clang-format on
80 return {};
81}
82
83/// Width of the register holding a value of @p type; a spill slot is as wide as its value.
84nat_t width(const Def* type) {
85 if (auto w = math::isa_f(type)) return *w;
86 if (auto spill = Axm::isa<mach::Spill>(type)) return width(spill->arg());
87 return std::bit_ceil(std::max<nat_t>(Idx::expect_bitwidth(type, "an integer"), 8));
88}
89
90/// Writes one function in AT&T syntax.
91class Emitter : public mach::Emitter {
92public:
93 Emitter(std::ostream& os, Emit& emit, Lam* fun)
94 : mach::Emitter(emit.target(), os, emit, fun)
95 , emit_(emit) {}
96
97private:
98 std::string slot(size_t i, size_t off = 0) const {
99 return std::format("{}(%rbp)", int64_t(off) - int64_t(8 * (saved(Target::Gpr).size() + i + 1)));
100 }
101 /// An operand that is a register or an immediate.
102 std::string src(const Def* def, nat_t w) const;
103 /// src() of a register at wide() width.
104 std::string wide_src(const Def* def, nat_t w) const {
105 return Lit::isa(def) ? imm(def, w) : std::string(name(use_reg(def), wide(w)));
106 }
107 std::string imm(const Def* lit, nat_t w) const;
108 std::string addr(const Def*) const;
109 /// A 16-byte constant in the `.rodata` pool, by its two halves.
110 std::string pool(u64 lo, u64 hi);
111 /// The `andps`/`andpd` mask that clears the sign bit of a value @p w bits wide.
112 std::string abs_mask(nat_t w) {
113 return w == 64 ? pool(0x7fff'ffff'ffff'ffff, 0x7fff'ffff'ffff'ffff)
114 : pool(0x7fff'ffff'7fff'ffff, 0x7fff'ffff'7fff'ffff);
115 }
116 /// The `f64` 2^32, which turns a signed `i32` into an unsigned one.
117 std::string two32() { return pool(std::bit_cast<u64>(4294967296.0), 0); }
118 /// A fresh label for an instruction's own fixup.
119 std::string local(std::string_view what) {
120 return std::format("{}{}.{}{}", target().local_prefix(), fun()->unique_name(), what, sel_++);
121 }
122 /// `ucomiss src, a` and the `setcc` of the `x86.fcmp` subtag @p sub into @p dst.
123 void ucomi(size_t sub, nat_t w, std::string_view src, size_t a, size_t dst);
124 /// The `x86.fsqrt` or conversion @p id of the operand @p src, @p ws bits wide, into the result @p res.
125 void unary(flags_t id, std::string_view src, nat_t ws, const Def* res);
126 void insn(const Def* res, const Def* f, const Def* x);
127
128 void step(const App*) final;
129 void move(Reg dst, Reg src) final;
130 /// Swaps the contents of @p a and @p b; the XMM registers have no `xchg`.
131 void swap(Reg a, Reg b) final;
132 void mov_imm(Reg dst, const Def* lit) final;
133 void push_slot(size_t i) final { line("pushq {}", slot(i)); }
134 void pop_slot(size_t i) final { line("popq {}", slot(i)); }
135 void spill(Src src, const Def* type, size_t i) final;
136 void reload(Reg dst, const Def* type, size_t i) final;
137 void load_arg(Reg dst, const Def* type, size_t i) final;
138 void load_from(Reg dst, const Def* type, std::string_view src);
139 /// The area grows down from `rbp`, so its address is that of its last slot.
140 void slot_addr(size_t dst, size_t first, size_t n) final {
141 line("leaq {}, {}", slot(first + n - 1), name(dst, 64));
142 }
143 void jmp(std::string_view label) final { line("jmp {}", label); }
144 void branch_cc(size_t cc, std::string_view label) final { line("j{} {}", ccs[cc], label); }
145 void branch_if(size_t r, std::string_view label, bool unless) final {
146 auto n = name(r, 8);
147 line("testb {}, {}", n, n);
148 line("{} {}", unless ? "je" : "jne", label);
149 }
150 void call_insn(std::string_view sym, std::optional<std::array<size_t, Target::Num_Classes>> num_args) final {
151 // A variadic callee reads the number of vector registers used from `al`.
152 if (num_args) line("movl ${}, %eax", (*num_args)[Target::Fpr]);
153 line("call {}", sym);
154 }
155 void prologue(std::ostream& os) final;
156 void leave() final;
157
158 Emit& emit_;
159 size_t sel_ = 0;
160};
161
162std::string Emitter::imm(const Def* lit, nat_t w) const {
163 auto l = *Lit::isa(lit);
164 auto s = std::bit_cast<int64_t>(l << (64 - w)) >> (64 - w);
165 if (s < INT32_MIN || s > INT32_MAX)
166 lit->blame("{} backend: literal `{}` does not fit an immediate", backend(), lit).bail();
167 return std::format("${}", s);
168}
169
170std::string Emitter::src(const Def* def, nat_t w) const {
171 if (Lit::isa(def)) return imm(def, w);
172 return std::string(name(use_reg(def), w));
173}
174
175std::string Emitter::addr(const Def* a) const {
176 auto ix = Axm::isa<x86::index>(a);
177 auto [disp, base] = Axm::as<x86::addr>(ix ? ix->decurry()->arg() : a)->args<2>();
178 auto d = std::bit_cast<int32_t>(u32(nat(disp)));
179 if (auto l = Lit::isa(base); l && *l != 0) base->blame("{} backend: literal base `{}`", backend(), base).bail();
180 auto has_base = !Lit::isa(base);
181 if (!has_base && !ix) return std::to_string(d);
182
183 auto res = d != 0 ? std::to_string(d) : ""s;
184 res += "(";
185 if (has_base) res += name(use_reg(base), 64);
186 if (ix) {
187 auto [index, scale] = ix->args<2>();
188 res += std::format(",{},{}", name(use_reg(index), 64), 1 << nat(scale));
189 }
190 return res + ")";
191}
192
193std::string Emitter::pool(u64 lo, u64 hi) {
194 return std::format("{}pool{}(%rip)", target().local_prefix(), emit_.pool(lo, hi));
195}
196
197void Emitter::move(Reg dst, Reg src) {
198 if (dst.cls == Target::Fpr)
199 line("movaps {}, {}", xmm(src.num), xmm(dst.num));
200 else
201 line("movq {}, {}", name(src.num, 64), name(dst.num, 64));
202}
203
204/// Swaps the contents of @p a and @p b; the XMM registers have no `xchg`.
205void Emitter::swap(Reg a, Reg b) {
206 if (a.cls == Target::Gpr) return line("xchgq {}, {}", name(a.num, 64), name(b.num, 64));
207 line("xorps {}, {}", xmm(a.num), xmm(b.num));
208 line("xorps {}, {}", xmm(b.num), xmm(a.num));
209 line("xorps {}, {}", xmm(a.num), xmm(b.num));
210}
211
212void Emitter::mov_imm(Reg dst, const Def* lit) {
213 auto w = width(lit->type());
214 auto l = *Lit::isa(lit);
215 if (dst.cls == Target::Fpr) {
216 if (w != 32 && w != 64) lit->blame("{} backend: `math.F` of {} bits is not supported", backend(), w).bail();
217 return line("mov{} {}, {}", fsz(w), pool(l, w == 64 ? 0 : l), xmm(dst.num));
218 }
219 // `xorl` clobbers the flags, so only use it while none are pending.
220 if (l == 0 && flags_clobbered()) return line("xorl {}, {}", name(dst.num, 32), name(dst.num, 32));
221 if (w < 64) return line("movl ${}, {}", l, name(dst.num, 32));
222 auto s = std::bit_cast<int64_t>(l);
223 if (s < INT32_MIN || s > INT32_MAX)
224 line("movabsq ${}, {}", s, name(dst.num, 64));
225 else
226 line("movq ${}, {}", s, name(dst.num, 64));
227}
228
229void Emitter::insn(const Def* res, const Def* f, const Def* x) {
230 auto axm = std::get<0>(Axm::get(f));
231 auto id = axm->base();
232 auto keep = id == Annex::Base<mov> || id == Annex::Base<lea> || id == Annex::Base<add3> || id == Annex::Base<movzx>
233 || id == Annex::Base<zero> || id == Annex::Base<movsx> || id == Annex::Base<cc>
235 || id == Annex::Base<fsub> || id == Annex::Base<fmul> || id == Annex::Base<fdiv>
237 || id == Annex::Base<f2u> || id == Annex::Base<f2f>;
238 if (!keep) clobber_flags();
239
240 auto binary = [&](std::string_view mnemonic) {
241 auto [a, b] = x->projs<2>();
242 auto w = width(res->type());
243 auto dst = def_reg(res);
244 assert(use_reg(a) == dst);
245 line("{}{} {}, {}", mnemonic, suffix(wide(w)), wide_src(b, w), name(dst, wide(w)));
246 };
247 auto shift = [&](std::string_view mnemonic) {
248 auto [a, b] = x->projs<2>();
249 auto w = width(res->type());
250 auto dst = def_reg(res);
251 assert(use_reg(a) == dst);
252 // Only `shl` leaves the low bits independent of the upper ones.
253 auto wd = mnemonic == "shl" ? wide(w) : w;
254 if (auto l = Lit::isa(b))
255 line("{}{} ${}, {}", mnemonic, suffix(wd), *l % w, name(dst, wd));
256 else
257 line("{}{} %cl, {}", mnemonic, suffix(wd), name(dst, wd));
258 };
259 auto divide = [&](bool sign) {
260 auto [a, b] = x->projs<2>();
261 auto w = width(a->type());
262 assert(use_reg(a) == encoding(reg::rax));
263 if (!sign)
264 line("xorl %edx, %edx");
265 else
266 line("{}", w == 64 ? "cqto" : w == 32 ? "cltd" : "cwtd");
267 line("{}div{} {}", sign ? "i" : "", suffix(w), name(use_reg(b), w));
268 };
269 auto extend = [&](char kind) {
270 auto ws = width(x->type());
271 auto wd = width(res->type());
272 auto rs = use_reg(x);
273 auto rd = def_reg(res);
274 if (ws < wd && !(kind == 'z' && ws == 32))
275 line("mov{}{}{} {}, {}", kind, suffix(ws), suffix(wd), name(rs, ws), name(rd, wd));
276 else if (ws < wd)
277 line("movl {}, {}", name(rs, 32), name(rd, 32));
278 else if (rs != rd)
279 line("movq {}, {}", name(rs, 64), name(rd, 64));
280 };
281
282 // clang-format off
283 if (auto mn = alu(id); !mn.empty()) binary(mn);
284 else if (id == Annex::Base<div>) divide(false);
285 else if (id == Annex::Base<idiv>) divide(true);
286 else if (id == Annex::Base<shl>) shift("shl");
287 else if (id == Annex::Base<shr>) shift("shr");
288 else if (id == Annex::Base<sar>) shift("sar");
289 else if (id == Annex::Base<movzx>) extend('z');
290 else if (id == Annex::Base<movsx>) extend('s');
291 // clang-format on
292 else if (id == Annex::Base<mov>) {
293 if (!Lit::isa(x)) x->blame("{} backend: `x86.mov` of `{}`, which is no literal", backend(), x).bail();
294 mov_imm(Reg{def_reg(res), Target::Gpr}, x);
295 } else if (id == Annex::Base<zero>) {
296 auto w = width(x->type());
297 auto rs = use_reg(x);
298 auto rd = def_reg(res);
299 if (w < 32)
300 line("movz{}l {}, {}", suffix(w), name(rs, w), name(rd, 32));
301 else if (w == 32)
302 line("movl {}, {}", name(rs, 32), name(rd, 32));
303 else if (rs != rd)
304 line("movq {}, {}", name(rs, 64), name(rd, 64));
305 } else if (id == Annex::Base<lea>) {
306 line("leaq {}, {}", addr(x), name(def_reg(res), 64));
307 } else if (id == Annex::Base<imul3>) {
308 auto [a, b] = x->projs<2>();
309 auto w = width(res->type());
310 line("imul{} {}, {}, {}", suffix(wide(w)), imm(b, w), name(use_reg(a), wide(w)), name(def_reg(res), wide(w)));
311 } else if (id == Annex::Base<rsub>) {
312 auto [a, b] = x->projs<2>();
313 auto w = width(res->type());
314 auto dst = def_reg(res);
315 assert(use_reg(b) == dst);
316 line("neg{} {}", suffix(wide(w)), name(dst, wide(w)));
317 line("add{} {}, {}", suffix(wide(w)), wide_src(a, w), name(dst, wide(w)));
318 } else if (id == Annex::Base<add3>) {
319 auto [a, b] = x->projs<2>();
320 auto w = width(res->type());
321 auto wd = wide(w);
322 auto ra = name(use_reg(a), 64);
323 if (Lit::isa(b))
324 line("lea{} {}({}), {}", suffix(wd), imm(b, w).substr(1), ra, name(def_reg(res), wd));
325 else
326 line("lea{} ({},{}), {}", suffix(wd), ra, name(use_reg(b), 64), name(def_reg(res), wd));
327 } else if (id == Annex::Base<trunc>) {
328 auto w = width(res->type());
329 auto rs = use_reg(x);
330 auto rd = def_reg(res);
331 auto n = *Idx::isa_lit(res->type());
332 auto full = w == 64 ? 0 : 1_n << w;
333 if (n != 0 && !std::has_single_bit(n)) {
334 // Nothing reserves rax, rcx, and rdx for the division, so save them around it.
335 auto save = fe::Vector<size_t>();
336 for (auto r : {encoding(reg::rax), encoding(reg::rcx), encoding(reg::rdx)})
337 if (r != rd) save.emplace_back(r);
338 for (auto r : save)
339 line("pushq {}", name(r, 64));
340 auto wx = width(x->type());
341 auto ws = std::max<nat_t>(wx, 32);
342 if (wx < 32)
343 line("movz{}l {}, %eax", suffix(wx), name(rs, wx));
344 else
345 line("mov{} {}, {}", suffix(ws), name(rs, ws), name(encoding(reg::rax), ws));
346 line("xorl %edx, %edx");
347 line("mov{} ${}, {}", suffix(ws), n, name(encoding(reg::rcx), ws));
348 line("div{} {}", suffix(ws), name(encoding(reg::rcx), ws));
349 if (rd != encoding(reg::rdx)) line("movq %rdx, {}", name(rd, 64));
350 for (auto r : save | std::views::reverse)
351 line("popq {}", name(r, 64));
352 } else {
353 if (rs != rd) line("movq {}, {}", name(rs, 64), name(rd, 64));
354 if (std::has_single_bit(n) && n != full) line("and{} ${}, {}", suffix(wide(w)), n - 1, name(rd, wide(w)));
355 }
356 } else if (id == Annex::Base<cmp> || id == Annex::Base<test>) {
357 auto [a, b] = x->projs<2>();
358 auto w = width(a->type());
359 line("{}{} {}, {}", id == Annex::Base<cmp> ? "cmp" : "test", suffix(w), src(b, w), name(use_reg(a), w));
360 set_flags(res);
361 } else if (id == Annex::Base<cc>) {
362 use_flags(x);
363 // A condition that only a branch consumes has no register.
364 if (auto r = isa_reg(res)) line("set{} {}", ccs[axm->sub()], name(*r, 8));
365 } else if (id == Annex::Base<cmovcc>) {
366 auto [fl, a, b] = x->projs<3>();
367 auto w = width(res->type());
368 auto dst = def_reg(res);
369 assert(use_reg(a) == dst);
370 use_flags(fl);
371 line("cmov{} {}, {}", ccs[axm->sub()], name(use_reg(b), wide(w)), name(dst, wide(w)));
372 } else if (id == Annex::Base<fadd> || id == Annex::Base<fsub> || id == Annex::Base<fmul>
373 || id == Annex::Base<fdiv>) {
374 auto [a, b] = x->projs<2>();
375 auto w = width(res->type());
376 auto dst = def_reg(res);
377 assert(use_reg(a) == dst);
378 line("{}{} {}, {}", farith(id), fsz(w), xmm(use_reg(b)), xmm(dst));
379 } else if (id == Annex::Base<fsqrt> || id == Annex::Base<i2f> || id == Annex::Base<f2i> || id == Annex::Base<f2u>
380 || id == Annex::Base<f2f>) {
381 auto ws = width(x->type());
382 auto r = use_reg(x);
383 unary(id, math::isa_f(x->type()) ? xmm(r) : std::string(name(r, ws)), ws, res);
384 } else if (id == Annex::Base<fabs>) {
385 auto w = width(res->type());
386 auto dst = def_reg(res);
387 assert(use_reg(x) == dst);
388 line("and{} {}, {}", w == 64 ? "pd" : "ps", abs_mask(w), xmm(dst));
389 } else if (id == Annex::Base<fmov>) {
390 if (!Lit::isa(x)) x->blame("{} backend: `x86.fmov` of `{}`, which is no literal", backend(), x).bail();
391 mov_imm(Reg{def_reg(res), Target::Fpr}, x);
392 } else if (id == Annex::Base<fcmp>) {
393 auto [a, b] = x->projs<2>();
394 ucomi(axm->sub(), width(a->type()), xmm(use_reg(b)), use_reg(a), def_reg(res));
395 } else if (id == Annex::Base<fsel>) {
396 auto [c, a, b] = x->projs<3>();
397 auto dst = def_reg(res);
398 assert(use_reg(a) == dst);
399 auto l = local("fsel");
400 line("testb {}, {}", name(use_reg(c), 8), name(use_reg(c), 8));
401 line("je {}", l);
402 line("movaps {}, {}", xmm(use_reg(b)), xmm(dst));
403 label_here(l);
404 } else if (id == Annex::Base<u2f>) {
405 auto ws = width(x->type());
406 auto wr = width(res->type());
407 if (ws == 64) f->blame("{} backend: `x86.u2f` from `i64` is not supported yet", backend()).bail();
408 auto src = name(use_reg(x), 32);
409 auto dst = xmm(def_reg(res));
410 auto l = local("u2f");
411 // Exact in `f64`, so an `f32` result rounds only once.
412 line("cvtsi2sdl {}, {}", src, dst);
413 line("testl {}, {}", src, src);
414 line("jns {}", l);
415 line("addsd {}, {}", two32(), dst);
416 label_here(l);
417 if (wr == 32) line("cvtsd2ss {}, {}", dst, dst);
418 } else {
419 f->blame("{} backend: cannot emit `{}`", backend(), axm).bail();
420 }
421}
422
423void Emitter::ucomi(size_t sub, nat_t w, std::string_view src, size_t a, size_t dst) {
424 auto [cc, unordered] = fccs[sub];
425 if (cc.empty()) return line("movl ${}, {}", sub == Fcmp_T ? 1 : 0, name(dst, 32));
426 line("ucomi{} {}, {}", fsz(w), src, xmm(a));
427 line("set{} {}", cc, name(dst, 8));
428 if (!unordered) return;
429 auto l = local("fcmp");
430 line("jnp {}", l);
431 line("movl ${}, {}", *unordered ? 1 : 0, name(dst, 32));
432 label_here(l);
433}
434
435void Emitter::unary(flags_t id, std::string_view src, nat_t ws, const Def* res) {
436 auto wr = width(res->type());
437 auto dst = def_reg(res);
438 if (id == Annex::Base<movsx>)
439 return line("movs{}{} {}, {}", suffix(ws), suffix(wide(wr)), src, name(dst, wide(wr)));
440 if (id == Annex::Base<fsqrt>) return line("sqrt{} {}, {}", fsz(wr), src, xmm(dst));
441 if (id == Annex::Base<i2f>) return line("cvtsi2{}{} {}, {}", fsz(wr), ws == 64 ? "q" : "l", src, xmm(dst));
442 if (id == Annex::Base<f2i>) return line("cvtt{}2si{} {}, {}", fsz(ws), wr == 64 ? "q" : "l", src, name(dst, wr));
443 if (id == Annex::Base<f2f>) return line("cvt{}2{} {}, {}", fsz(ws), fsz(wr), src, xmm(dst));
444 if (wr == 64) res->blame("{} backend: `x86.f2u` to `i64` is not supported yet", backend()).bail();
445 line("cvtt{}2siq {}, {}", fsz(ws), src, name(dst, 64));
446 line("movl {}, {}", name(dst, 32), name(dst, 32));
447}
448
449void Emitter::step(const App* app) {
450 if (Axm::isa<mach::sched>(app)) return insn(app->proj(2, 1), Target::sched_insn(app), app->arg());
451
452 auto ext = Axm::isa<rm1>(app) && insn::op(app) == Annex::Base<movsx>;
453 if (!ext && !Axm::isa<load>(app) && !Axm::isa<store>(app) && !Axm::isa<fload>(app) && !Axm::isa<fstore>(app))
454 clobber_flags();
455
456 if (auto op = Axm::isa<rm>(app)) {
457 auto [_, a, p] = app->args<3>();
458 auto w = width(a->type());
459 auto dst = def_reg(app->proj(2, 1));
460 auto insn = op->decurry()->arg()->as<App>()->axm();
461 if (insn->base() == Annex::Base<fcmp>) return ucomi(insn->sub(), w, addr(p), use_reg(a), dst);
462 assert(use_reg(a) == dst);
463 if (math::isa_f(a->type()))
464 line("{}{} {}, {}", farith(insn->base()), fsz(w), addr(p), xmm(dst));
465 else
466 line("{}{} {}, {}", alu(insn->flags()), suffix(w), addr(p), name(dst, w));
467 return;
468 }
469
470 if (Axm::isa<rm1>(app)) {
471 auto [_, p] = app->args<2>();
472 auto f = app->callee()->as<App>()->arg();
473 return unary(insn::op(app), addr(p), width(f->type()->as<Pi>()->dom()), app->proj(2, 1));
474 }
475
476 if (auto op = Axm::isa<mr>(app)) {
477 auto [_, p, b] = app->args<3>();
478 auto w = width(b->type());
479 line("{}{} {}, {}", alu(op->decurry()->arg()->as<App>()->axm()->flags()), suffix(w), src(b, w), addr(p));
480 return;
481 }
482
483 if (Axm::isa<load>(app)) {
484 auto [_, p] = app->args<2>();
485 auto res = app->proj(2, 1);
486 auto w = width(res->type());
487 // A load into a partial register would merge with its stale upper bits.
488 if (w < 32)
489 line("movz{}l {}, {}", suffix(w), addr(p), name(def_reg(res), 32));
490 else
491 line("mov{} {}, {}", suffix(w), addr(p), name(def_reg(res), w));
492 return;
493 }
494
495 if (Axm::isa<fload>(app)) {
496 auto [_, p] = app->args<2>();
497 auto res = app->proj(2, 1);
498 auto w = width(res->type());
499 line("mov{} {}, {}", fsz(w), addr(p), xmm(def_reg(res)));
500 return;
501 }
502
503 if (Axm::isa<fstore>(app)) {
504 auto [_, p, v] = app->args<3>();
505 auto w = width(v->type());
506 line("mov{} {}, {}", fsz(w), xmm(use_reg(v)), addr(p));
507 return;
508 }
509
510 auto [_, p, v] = app->args<3>();
511 auto w = width(v->type());
512 line("mov{} {}, {}", suffix(w), src(v, w), addr(p));
513}
514
515void Emitter::spill(Src src, const Def* type, size_t i) {
516 if (src.reg.cls != Target::Fpr) {
517 auto s = src.imm ? imm(src.imm, 64) : std::string(name(src.reg.num, 64));
518 return line("movq {}, {}", s, slot(i));
519 }
520 auto w = width(type);
521 if (src.imm) {
522 auto l = *Lit::isa(src.imm);
523 line("movl ${}, {}", u32(l), slot(i));
524 if (w == 64) line("movl ${}, {}", u32(l >> 32), slot(i, 4));
525 } else {
526 line("mov{} {}, {}", fsz(w), xmm(src.reg.num), slot(i));
527 }
528}
529
530void Emitter::load_from(Reg dst, const Def* type, std::string_view src) {
531 if (dst.cls == Target::Fpr)
532 line("mov{} {}, {}", fsz(width(type)), src, xmm(dst.num));
533 else
534 line("movq {}, {}", src, name(dst.num, 64));
535}
536
537void Emitter::reload(Reg dst, const Def* type, size_t i) { load_from(dst, type, slot(i)); }
538
539// Above `rbp` are the caller's `rbp` and the return address, then the arguments in 8-byte slots.
540void Emitter::load_arg(Reg dst, const Def* type, size_t i) {
541 load_from(dst, type, std::format("{}(%rbp)", 16 + 8 * i));
542}
543
544void Emitter::leave() {
545 if (saved(Target::Gpr).empty()) {
546 line("leave");
547 } else {
548 line("leaq -{}(%rbp), %rsp", 8 * saved(Target::Gpr).size());
549 for (auto r : saved(Target::Gpr) | std::views::reverse)
550 line("popq {}", name(r, 64));
551 line("popq %rbp");
552 }
553}
554
555void Emitter::prologue(std::ostream& os) {
556 auto frame = frame_size() - 8 * saved(Target::Gpr).size();
557 std::println(os, "\tpushq %rbp");
558 std::println(os, "\tmovq %rsp, %rbp");
559 for (auto r : saved(Target::Gpr))
560 std::println(os, "\tpushq {}", name(r, 64));
561 if (frame != 0) std::println(os, "\tsubq ${}, %rsp", frame);
562}
563
564} // namespace
565
566void Emit::emit(std::ostream& os, Lam* fun, bool global) { Emitter(os, *this, fun).emit(global); }
567
568void Emit::finish(std::ostream& os) {
569 if (pool_.empty()) return;
570 auto constants = fe::Vector<std::pair<u64, u64>>(pool_.size());
571 for (auto& [c, i] : pool_)
572 constants[i] = c;
573 std::println(os, "\t{}", Target::is_elf() ? ".section .rodata" : ".section __TEXT,__const");
574 std::println(os, "\t.p2align 4");
575 for (size_t i = 0; i != constants.size(); ++i) {
576 std::println(os, "{}pool{}:", Target::local_prefix(), i);
577 std::println(os, "\t.quad 0x{:016x}", constants[i].first);
578 std::println(os, "\t.quad 0x{:016x}", constants[i].second);
579 }
580}
581
582} // namespace mim::plug::x86
static auto isa(const Def *def)
Definition axm.h:112
static auto as(const Def *def)
Definition axm.h:134
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of def.
Definition axm.cpp:38
static std::optional< nat_t > isa_lit(const Def *def)
Definition def.cpp:689
static nat_t expect_bitwidth(const Def *type, fe::cite_string< Args... > fmt, Args &&... args)
Yields the bit width of the Idx type or bails if type is not an Idx; see Def::expect.
Definition def.h:1045
A function.
Definition lam.h:91
static std::optional< T > isa(const Def *def)
Definition def.h:974
static const Def * sched_insn(const App *app)
Definition target.h:204
static constexpr std::string_view local_prefix()
The prefix of an assembler-local label.
Definition target.h:72
static constexpr bool is_elf()
Definition target.h:62
void finish(std::ostream &os) final
Writes what all functions together need after them, e.g. a constant pool.
Definition emit.cpp:568
void emit(std::ostream &os, Lam *fun, bool global) final
Definition emit.cpp:566
std::optional< nat_t > isa_f(const Def *def)
Definition math.h:55
flags_t op(const App *app)
The operation f of the memory form x86.rm f, x86.rm1 f, or x86.mr f app.
Definition insn.h:40
The x86 Plugin
Definition emit.h:9
const Def * imm
Definition emit.h:34
constexpr size_t encoding(Reg r)
The hardware encoding of the register r of a backend's module reg, whose subtags are in encoding orde...
Definition mach.h:15
u64 nat_t
Definition types.h:37
u64 flags_t
Definition types.h:39
uint32_t u32
Definition types.h:27
uint64_t u64
Definition types.h:27
@ App
Definition def.h:123
static constexpr flags_t Base
Definition plugin.h:276
Target::Class cls
Definition emit.h:27
Target::Class cls
Definition emit.h:27