MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
emit.cpp
Go to the documentation of this file.
1#include "mim/plug/arm/emit.h"
2
3#include <print>
4
5#include <mim/plugin.h>
6
9
10#include "mim/plug/arm/target.h"
11
12namespace mim::plug::arm {
13
14using mach::Reg;
15using mach::Src;
16
17namespace {
18
19/// The AAPCS64 condition codes in hardware order; `arm.cc`'s subtag indexes this table.
20constexpr std::array<std::string_view, 16> ccs
21 = {"eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", "nv"};
22
23/// Are the @p bits of a float of width @p w the 8-bit immediate of `fmov`, i.e. `a:¬b:b…b:cdefgh:0…0`?
24bool is_fimm8(u64 bits, nat_t w) {
25 auto [zeros, exp] = w == 64 ? std::pair{48, (bits >> 54) & 0x1ff} : std::pair{19, (bits >> 25) & 0x3f};
26 auto b1 = w == 64 ? 0x0ffu : 0x1fu;
27 return (bits & ((u64(1) << zeros) - 1)) == 0 && (exp == b1 || exp == b1 + 1);
28}
29
30/// `x17` holds a literal operand; `x16` holds a second one, breaks a copy cycle, or carries a spill slot.
31constexpr size_t Scratch = encoding(reg::x16), Scratch2 = encoding(reg::x17);
32
33/// The bit width of the register holding a value of @p type.
34nat_t width(const Def* type) {
35 if (auto w = math::isa_f(type)) return *w;
36 return Idx::expect_bitwidth(type, "an integer");
37}
38
39/// The `b`/`h` suffix of a load or store of width @p w.
40std::string_view suffix(nat_t w) { return w <= 8 ? "b" : w <= 16 ? "h" : ""; }
41
42/// The prefix of a whole 64-bit register of class @p cls.
43char wide(Target::Class cls) { return cls == Target::Fpr ? 'd' : 'x'; }
44
45std::string reg(size_t r, nat_t w) { return std::format("{}{}", w == 64 ? 'x' : 'w', r); }
46/// The `w`/`x` or `s`/`d` name of the register @p r holding a value of @p type.
47std::string name(size_t r, const Def* type) {
48 if (!math::isa_f(type)) return reg(r, width(type));
49 return std::format("{}{}", width(type) == 64 ? 'd' : 's', r);
50}
51
52/// Writes one function in AArch64 syntax.
53class Emitter : public mach::Emitter {
54public:
55 Emitter(std::ostream& os, Emit& emit, Lam* fun)
56 : mach::Emitter(emit.target(), os, emit, fun) {}
57
58private:
59 /// The frame address @p off bytes above `sp`, also while push_slot() moved `sp` down.
60 std::string at(size_t off) const { return std::format("[sp, #{}]", off + pushed_); }
61 std::string slot(size_t i) const { return at(8 * (num_saved() + i)); }
62 /// The saved registers in frame order.
63 fe::Vector<Reg> saved_regs() const;
64 /// The register operand @p def of width @p w; a literal goes into @p scratch.
65 std::string operand(const Def* def, nat_t w, size_t scratch);
66 /// The second operand @p b after @p a: an immediate below @p limit, otherwise a register.
67 std::string operand(const Def* a, const Def* b, nat_t w, nat_t limit);
68 void insn(const Def* res, const Def* f, const Def* x);
69 void fmov_imm(size_t dst, const Def* lit);
70
71 void step(const App*) final;
72 void move(Reg dst, Reg src) final {
73 auto c = wide(dst.cls);
74 if (dst != src) line("{} {}{}, {}{}", c == 'd' ? "fmov" : "mov", c, dst.num, c, src.num);
75 }
76 std::optional<Reg> scratch(Target::Class cls) const final {
77 return cls == Target::Fpr ? Reg{Fpr_Scratch, Target::Fpr} : Reg{Scratch};
78 }
79 void mov_imm(Reg dst, const Def* lit) final {
80 if (dst.cls == Target::Fpr) return fmov_imm(dst.num, lit);
81 line("ldr {}, ={}", reg(dst.num, width(lit->type())), *Lit::isa(lit));
82 }
83 void push_slot(size_t i) final {
84 line("ldr x{}, {}", Scratch, slot(i));
85 line("str x{}, [sp, #-16]!", Scratch);
86 pushed_ += 16;
87 }
88 void pop_slot(size_t i) final {
89 line("ldr x{}, [sp], #16", Scratch);
90 pushed_ -= 16;
91 line("str x{}, {}", Scratch, slot(i));
92 }
93 void jmp(std::string_view label) final { line("b {}", label); }
94 void branch_cc(size_t cc, std::string_view label) final { line("b.{} {}", ccs[cc], label); }
95 void branch_if(size_t r, std::string_view label, bool unless) final {
96 line("{} w{}, {}", unless ? "cbz" : "cbnz", r, label);
97 }
98 void call_insn(std::string_view sym, std::optional<std::array<size_t, Target::Num_Classes>>) final {
99 line("bl {}", sym);
100 }
101 void spill(Src src, const Def*, size_t i) final {
102 if (src.imm) return line("str {}, {}", operand(src.imm, 64, Scratch2), slot(i));
103 line("str {}{}, {}", wide(src.reg.cls), src.reg.num, slot(i));
104 }
105 void reload(Reg dst, const Def*, size_t i) final { line("ldr {}{}, {}", wide(dst.cls), dst.num, slot(i)); }
106 /// Above `x29` are the caller's `x29` and `x30`, then the arguments in 8-byte slots (AAPCS64, not Apple's).
107 void load_arg(Reg dst, const Def*, size_t i) final {
108 line("ldr {}{}, [x29, #{}]", wide(dst.cls), dst.num, 16 + 8 * i);
109 }
110 void slot_addr(size_t dst, size_t first, size_t) final;
111 void prologue(std::ostream& os) final;
112 void leave() final;
113 std::string_view function_type() const final { return "%function"; }
114
115 size_t pushed_ = 0;
116};
117
118std::string Emitter::operand(const Def* def, nat_t w, size_t scratch) {
119 if (!Lit::isa(def)) return reg(use_reg(def), w);
120 mov_imm(Reg{scratch}, def);
121 return reg(scratch, w);
122}
123
124std::string Emitter::operand(const Def* a, const Def* b, nat_t w, nat_t limit) {
125 if (auto l = Lit::isa(b); l && *l < limit) return std::format("#{}", *l);
126 return operand(b, w, Lit::isa(a) ? Scratch : Scratch2);
127}
128
129void Emitter::insn(const Def* res, const Def* f, const Def* x) {
130 auto [axm, curry, _] = Axm::get(f);
131 auto id = axm->base();
132
133 auto three = [&](std::string_view mnemonic, nat_t limit) {
134 auto [a, b] = x->projs<2>();
135 auto w = width(res->type());
136 auto lhs = operand(a, w, Scratch2);
137 auto rhs = operand(a, b, w, limit);
138 line("{} {}, {}, {}", mnemonic, reg(def_reg(res), w), lhs, rhs);
139 };
140 auto fthree = [&](std::string_view mnemonic) {
141 auto [a, b] = x->projs<2>();
142 auto t = res->type();
143 line("{} {}, {}, {}", mnemonic, name(def_reg(res), t), name(use_reg(a), t), name(use_reg(b), t));
144 };
145 auto two = [&](std::string_view mnemonic) {
146 line("{} {}, {}", mnemonic, name(def_reg(res), res->type()), name(use_reg(x), x->type()));
147 };
148 constexpr nat_t Imm12 = 4096;
149
150 if (id == Annex::Base<add>)
151 three("add", Imm12);
152 else if (id == Annex::Base<sub>)
153 three("sub", Imm12);
154 else if (id == Annex::Base<and_>)
155 three("and", 0);
156 else if (id == Annex::Base<or_>)
157 three("orr", 0);
158 else if (id == Annex::Base<xor_>)
159 three("eor", 0);
160 else if (id == Annex::Base<mul>)
161 three("mul", 0);
162 else if (id == Annex::Base<madd>) {
163 auto w = width(res->type());
164 auto scratch = std::array{Scratch2, Scratch};
165 auto next = size_t(0);
166 auto ops = x->projs<3>([&](const Def* op) { return operand(op, w, scratch[Lit::isa(op) ? next++ : 0]); });
167 line("madd {}, {}, {}, {}", reg(def_reg(res), w), ops[0], ops[1], ops[2]);
168 } else if (id == Annex::Base<udiv>)
169 three("udiv", 0);
170 else if (id == Annex::Base<sdiv>)
171 three("sdiv", 0);
172 else if (id == Annex::Base<shl>)
173 three("lsl", width(res->type()));
174 else if (id == Annex::Base<shr>)
175 three("lsr", width(res->type()));
176 else if (id == Annex::Base<sar>)
177 three("asr", width(res->type()));
178 else if (id == Annex::Base<sext>) {
179 auto ws = width(x->type());
180 auto wd = width(res->type());
181 auto rs = use_reg(x);
182 auto rd = def_reg(res);
183 if (ws == 64) return move(Reg{rd}, Reg{rs});
184 line("sbfx {}, {}, #0, #{}", reg(rd, wd), reg(rs, wd), ws);
185 } else if (id == Annex::Base<zero>) {
186 auto w = width(x->type());
187 auto rs = use_reg(x);
188 auto rd = def_reg(res);
189 if (w < 32)
190 line("ubfx {}, {}, #0, #{}", reg(rd, 32), reg(rs, 32), w);
191 else if (w == 32)
192 line("mov {}, {}", reg(rd, 32), reg(rs, 32));
193 else
194 move(Reg{rd}, Reg{rs});
195 } else if (id == Annex::Base<trunc>) {
196 move(Reg{def_reg(res)}, Reg{use_reg(x)});
197 } else if (id == Annex::Base<cmp>) {
198 auto [a, b] = x->projs<2>();
199 auto w = width(a->type());
200 auto lhs = operand(a, w, Scratch2);
201 auto rhs = operand(a, b, w, Imm12);
202 line("cmp {}, {}", lhs, rhs);
203 set_flags(res);
204 } else if (id == Annex::Base<cc>) {
205 use_flags(x);
206 if (auto r = isa_reg(res)) line("cset w{}, {}", *r, ccs[axm->sub()]);
207 } else if (id == Annex::Base<csel>) {
208 auto [fl, a, b] = x->projs<3>();
209 use_flags(fl);
210 auto w = width(res->type());
211 auto ra = operand(a, w, Scratch2);
212 auto rb = operand(a, b, w, 0);
213 line("csel {}, {}, {}, {}", reg(def_reg(res), w), rb, ra, ccs[axm->sub()]);
214 } else if (id == Annex::Base<fadd>)
215 fthree("fadd");
216 else if (id == Annex::Base<fsub>)
217 fthree("fsub");
218 else if (id == Annex::Base<fmul>)
219 fthree("fmul");
220 else if (id == Annex::Base<fdiv>)
221 fthree("fdiv");
222 else if (id == Annex::Base<fsqrt>)
223 two("fsqrt");
224 else if (id == Annex::Base<fabs>)
225 two("fabs");
226 else if (id == Annex::Base<i2f>)
227 two("scvtf");
228 else if (id == Annex::Base<u2f>)
229 two("ucvtf");
230 else if (id == Annex::Base<f2i>)
231 two("fcvtzs");
232 else if (id == Annex::Base<f2u>)
233 two("fcvtzu");
234 else if (id == Annex::Base<f2f>)
235 two("fcvt");
236 else if (id == Annex::Base<fmov>)
237 mov_imm(Reg{def_reg(res), Target::Fpr}, x);
238 else if (id == Annex::Base<fcmp>) {
239 auto [a, b] = x->projs<2>();
240 line("fcmp {}, {}", name(use_reg(a), a->type()), name(use_reg(b), b->type()));
241 set_flags(res);
242 } else if (id == Annex::Base<fcsel>) {
243 auto [fl, a, b] = x->projs<3>();
244 use_flags(fl);
245 auto t = res->type();
246 line("fcsel {}, {}, {}, {}", name(def_reg(res), t), name(use_reg(b), t), name(use_reg(a), t), ccs[axm->sub()]);
247 } else {
248 f->blame("{} backend: cannot emit `{}`", backend(), axm).bail();
249 }
250}
251
252void Emitter::fmov_imm(size_t dst, const Def* lit) {
253 auto w = width(lit->type());
254 auto bits = *Lit::isa(lit);
255 auto d = name(dst, lit->type());
256 if (bits == 0) return line("fmov {}, {}", d, w == 64 ? "xzr" : "wzr");
257 if (is_fimm8(bits, w)) {
258 auto imm = std::format("{}", w == 64 ? std::bit_cast<f64>(bits) : f64(std::bit_cast<f32>(u32(bits))));
259 if (imm.find('.') == std::string::npos) imm += ".0";
260 return line("fmov {}, #{}", d, imm);
261 }
262 line("ldr {}, ={}", reg(Scratch2, w), w == 64 ? bits : u32(bits));
263 line("fmov {}, {}", d, reg(Scratch2, w));
264}
265
266void Emitter::step(const App* app) {
267 if (Axm::isa<mach::sched>(app)) return insn(app->proj(2, 1), Target::sched_insn(app), app->arg());
268
269 if (Axm::isa<load>(app) || Axm::isa<fload>(app)) {
270 auto [_, p] = app->args<2>();
271 auto res = app->proj(2, 1);
272 line("ldr{} {}, [x{}]", suffix(width(res->type())), name(def_reg(res), res->type()), use_reg(p));
273 return;
274 }
275
276 if (Axm::isa<store>(app) || Axm::isa<fstore>(app)) {
277 auto [_, p, v] = app->args<3>();
278 auto w = width(v->type());
279 auto src = Lit::isa(v) ? operand(v, w, Scratch2) : name(use_reg(v), v->type());
280 line("str{} {}, [x{}]", suffix(w), src, use_reg(p));
281 return;
282 }
283
284 app->blame("{} backend: cannot emit `{}`", backend(), app).bail();
285}
286
287void Emitter::slot_addr(size_t dst, size_t first, size_t) {
288 auto off = 8 * (num_saved() + first);
289 if (off <= 4095) return line("add x{}, sp, #{}", dst, off);
290 line("ldr x{}, ={}", Scratch2, off);
291 line("add x{}, sp, x{}", dst, Scratch2);
292}
293
294fe::Vector<Reg> Emitter::saved_regs() const {
295 auto regs = fe::Vector<Reg>();
296 for (auto cls : {Target::Gpr, Target::Fpr})
297 for (auto r : saved(cls))
298 regs.emplace_back(r, cls);
299 return regs;
300}
301
302void Emitter::prologue(std::ostream& os) {
303 auto frame = frame_size();
304 std::println(os, "\tstp x29, x30, [sp, #-16]!");
305 std::println(os, "\tmov x29, sp");
306 if (frame != 0) std::println(os, "\tsub sp, sp, #{}", frame);
307 auto regs = saved_regs();
308 for (size_t i = 0; i != regs.size(); ++i)
309 std::println(os, "\tstr {}{}, {}", wide(regs[i].cls), regs[i].num, at(8 * i));
310}
311
312void Emitter::leave() {
313 auto regs = saved_regs();
314 for (size_t i = 0; i != regs.size(); ++i)
315 line("ldr {}{}, {}", wide(regs[i].cls), regs[i].num, at(8 * i));
316 line("mov sp, x29");
317 line("ldp x29, x30, [sp], #16");
318}
319
320} // namespace
321
322void Emit::emit(std::ostream& os, Lam* fun, bool global) { Emitter(os, *this, fun).emit(global); }
323
324} // namespace mim::plug::arm
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
void emit(std::ostream &os, Lam *fun, bool global) final
Definition emit.cpp:322
Class
The register classes; Stack values live in a spill slot and are unbounded.
Definition target.h:48
The ARM Plugin
Definition arm.h:11
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
constexpr size_t Fpr_Scratch
d31 breaks a copy cycle, so allocation leaves it alone.
Definition arm.h:46
std::optional< nat_t > isa_f(const Def *def)
Definition math.h:55
u64 nat_t
Definition types.h:37
uint32_t u32
Definition types.h:27
uint64_t u64
Definition types.h:27