MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
emit.cpp
Go to the documentation of this file.
2
3#include <ranges>
4
6
7namespace mim::plug::mach {
8
9namespace {
10
11/// Groups the spilled values that may share a slot: a memory φ joins its argument unless their groups interfere.
12fe::Vector<DefVec> slot_groups(const Target& target, const Liveness& live) {
13 auto keep = [&](const Def* v) { return target.cls(v) == Target::Stack; };
14 auto interfere = DefMap<DefSet>();
15 for (const auto& block : live.blocks())
16 interferences(live, block, keep, [&](const Def* a, const Def* b) {
17 interfere[a].emplace(b);
18 interfere[b].emplace(a);
19 });
20
21 auto root = Def2Def();
22 auto members = DefMap<DefVec>();
23 auto order = DefVec();
24 auto find = [&](const Def* v) {
25 auto [i, ins] = root.emplace(v, v);
26 if (ins) members[v] = {v}, order.emplace_back(v);
27 while (root[v] != v)
28 v = root[v];
29 return v;
30 };
31 auto unite = [&](const Def* a, const Def* b) {
32 a = find(a), b = find(b);
33 if (a == b) return;
34 for (auto x : members[a])
35 if (auto is = fe::lookup(interfere, x))
36 for (auto y : members[b])
37 if (is->contains(y)) return;
38 root[b] = a;
39 auto& ms = members[a];
40 ms.insert(ms.end(), members[b].begin(), members[b].end());
41 members.erase(b);
42 };
43
44 for (const auto& block : live.blocks()) {
45 for (auto insn : block.insns)
46 for (auto d : live.defs(insn))
47 if (keep(d)) find(d);
48 for (auto x : block.params)
49 if (keep(x)) find(x);
50 auto term = block.lam->body()->as<App>();
51 for_each_succ(term, [&](Lam* s) {
52 auto n = s->num_vars();
53 if (term->num_args() != n) return;
54 for (size_t i = 0; i != n; ++i)
55 if (auto x = s->var(n, i), a = term->arg(n, i); keep(x) && live.local(a) && keep(a)) unite(x, a);
56 });
57 }
58
59 auto res = fe::Vector<DefVec>();
60 for (auto v : order)
61 if (auto ms = fe::lookup(members, v)) res.emplace_back(std::move(*ms));
62 return res;
63}
64
65void collect(const Def* def, DefSet& done, DefMap<size_t>& regs) {
66 if (def->isa_mut() || def->is_closed() || Target::is_mem(def) || !done.emplace(def).second) return;
67 if (Target::is_in(def)) {
68 regs.emplace(Target::strip(def), Target::in_reg(def));
69 return;
70 }
71 for (auto op : def->ops())
72 collect(op, done, regs);
73}
74
75DefMap<size_t> collect(const Liveness& live) {
76 auto regs = DefMap<size_t>();
77 auto done = DefSet();
78 for (const auto& b : live.blocks()) {
79 for (auto insn : b.insns) {
80 collect(insn->callee(), done, regs);
81 collect(insn->arg(), done, regs);
82 }
83 collect(b.lam->body(), done, regs);
84 }
85 return regs;
86}
87
88} // namespace
89
90const ParamRegs* Emitter::params(Lam* lam) {
91 if (!emit_.known().contains(lam)) return nullptr;
92 auto res = fe::lookup(emit_.params(), lam);
93 assert(res && "a known function is emitted before its callers");
94 return res;
95}
96
97/// Sequentializes the parallel copies @p moves between registers and @p slot_moves between spill slots.
98void Emitter::parallel(Moves moves, fe::Vector<std::pair<size_t, size_t>> slot_moves) {
99 std::erase_if(slot_moves, [](auto m) { return m.first == m.second; });
100 for (auto [_, from] : slot_moves)
101 push_slot(from);
102 for (auto [to, _] : slot_moves | std::views::reverse)
103 pop_slot(to);
104
105 auto imms = Moves();
106 for (auto& m : moves)
107 if (m.second.imm) imms.emplace_back(m);
108 std::erase_if(moves, [](const auto& m) { return m.second.imm || m.first == m.second.reg; });
109
110 while (!moves.empty()) {
111 auto free = std::ranges::find_if(moves, [&](const auto& m) {
112 return std::ranges::none_of(moves, [&](const auto& n) { return n.second.reg == m.first; });
113 });
114 if (free != moves.end()) {
115 move(free->first, free->second.reg);
116 moves.erase(free);
117 continue;
118 }
119 // Only cycles are left.
120 auto [d, s] = moves.back();
121 moves.pop_back();
122 if (auto tmp = scratch(d.cls)) {
123 move(*tmp, d);
124 for (auto& [_, from] : moves)
125 if (from.reg == d) from.reg = *tmp;
126 move(d, s.reg);
127 } else {
128 swap(s.reg, d);
129 for (auto& [_, from] : moves)
130 if (from.reg == d)
131 from.reg = s.reg;
132 else if (from.reg == s.reg)
133 from.reg = d;
134 std::erase_if(moves, [](const auto& m) { return m.first == m.second.reg; });
135 }
136 }
137
138 for (auto [dst, s] : imms)
139 mov_imm(dst, s.imm);
140}
141
142std::pair<Moves, Emitter::SlotMoves> Emitter::moves(Lam* target, const Def* arg) {
143 auto moves = Moves();
144 auto slot_moves = SlotMoves();
145 auto n = target->num_vars();
146 for (size_t i = 0; i != n; ++i) {
147 auto x = target->var(n, i);
148 auto a = arg->proj(n, i);
149 if (Target::is_mem(x)) continue;
150 if (auto cls = target_.cls(x); cls == Target::Stack) {
151 if (auto from = spill_slot(a), to = spill_slot(x); from != to) slot_moves.emplace_back(to, from);
152 } else if (auto r = fe::lookup(regs_, x)) {
153 if (auto src = source(a); src.imm || src.reg != Reg{*r, cls}) moves.emplace_back(Reg{*r, cls}, src);
154 }
155 }
156 return {std::move(moves), std::move(slot_moves)};
157}
158
159void Emitter::copy(Lam* target, const Def* arg) {
160 auto [moves, slot_moves] = this->moves(target, arg);
161 parallel(std::move(moves), std::move(slot_moves));
162}
163
164void Emitter::jump(Lam* target) {
165 target = forward(target);
166 fell_ = target == next_;
167 if (!fell_) jmp(label(target));
168}
169
170std::array<size_t, Target::Num_Classes> Emitter::pass(const Def* arg, size_t num_args, const ParamRegs* conv) {
171 auto n = arg->num_projs();
172 auto locs = arg_locs(target_, arg, n, num_args, conv);
173 auto moves = Moves();
174 auto num = std::array<size_t, Target::Num_Classes>{};
175 for (size_t i = 0; i != num_args; ++i) {
176 auto x = arg->proj(n, i);
177 auto cls = target_.cls(Target::strip(x));
178 if (locs[i].stack) arg->blame("{} backend: too many arguments are not supported yet", backend()).bail();
179 if (auto r = locs[i].reg) moves.emplace_back(Reg{*r, cls}, source(x)), ++num[cls];
180 }
181 parallel(std::move(moves), {});
182 return num;
183}
184
185void Emitter::call(Lam* callee, const Def* arg) {
186 auto n = arg->num_projs();
187 auto conv = params(callee);
188 auto num = pass(arg, n - 1, conv);
189 call_insn(symbol(callee), conv ? std::nullopt : std::optional(num));
191
192 auto ret = arg->proj(n, n - 1);
193 if (ret == ret_) return epilogue();
194
195 auto k = Lam::isa_mut_basicblock(ret);
196 auto m = k->num_vars();
197 auto back = Moves();
198 for (size_t i = 0; i != m; ++i)
199 if (auto x = k->var(m, i); !Target::is_mem(x)) {
200 auto cls = target_.cls(x);
201 if (auto r = fe::lookup(regs_, x)) back.emplace_back(Reg{*r, cls}, Src{.reg = {target_.ret_reg(cls), cls}});
202 }
203 parallel(std::move(back), {});
204 jump(k);
205}
206
207void Emitter::insn(const App* app) {
208 if (Axm::isa<sched>(app)) {
209 auto f = Target::sched_insn(app);
210 auto res = app->proj(2, 1);
211 if (Axm::isa<mach::spill, 1>(f)) return spill(source(app->arg()), app->arg()->type(), spill_slot(res));
213 return reload(Reg{def_reg(res), target_.cls(res)}, res->type(), spill_slot(app->arg()));
214 } else if (Axm::isa<slot>(app)) {
215 auto first = alloc_slots(nat(app->callee()->as<App>()->arg()));
216 return slot_addr(def_reg(app->proj(2, 1)), first, num_slots_ - first);
217 }
218 step(app);
219}
220
221void Emitter::block(Lam* lam, const fe::Vector<const App*>& insns) {
222 for (auto app : insns)
223 insn(app);
224
225 auto term = lam->body()->as<App>();
226 auto arg = term->arg();
227 auto callee = term->callee();
228 if (callee == ret_) {
229 auto moves = Moves();
230 for (auto a : term->args()) {
231 if (Target::is_mem(a)) continue;
232 auto cls = target_.cls(Target::strip(a));
233 moves.emplace_back(Reg{target_.ret_reg(cls), cls}, source(a));
234 }
235 if (moves.size() > 1) lam->blame("{} backend: `{}` returns more than one value", backend(), lam).bail();
236 parallel(std::move(moves), {});
237 epilogue();
238 } else if (auto f = Lam::isa_mut_returning(callee)) {
239 call(f, arg);
240 } else if (auto ex = callee->isa<Extract>()) {
241 auto targets = ex->tuple();
242 if (targets->num_projs() != 2)
243 lam->blame("{} backend: only two-way branches are supported yet", backend()).bail();
244 auto [e, t] = targets->projs<2>([](const Def* d) { return Lam::isa_mut_basicblock(d); });
245 if (!e || !t) lam->blame("{} backend: `{}` branches to something other than blocks", backend(), lam).bail();
246 auto c = ex->index();
247 // Branch away from the block that comes next.
248 auto flip = forward(t) == next_ && forward(e) != next_;
249 auto taken = label(forward(flip ? e : t));
250 if (auto app = target_.isa_sched_cc(c)) {
251 use_flags(app->arg());
252 auto cc = std::get<0>(Axm::get(Target::sched_insn(app)))->sub();
253 branch_cc(flip ? target_.negate_cc(cc) : cc, taken);
254 } else if (Lit::isa(c)) {
255 c->blame("{} backend: a branch on the literal `{}`", backend(), c).bail();
256 } else {
257 branch_if(use_reg(c), taken, flip);
258 }
259 jump(flip ? t : e);
260 } else if (auto bb = Lam::isa_mut_basicblock(callee); bb && live_->block(bb)) {
261 copy(bb, arg);
262 // A jump to a small block that ends in a branch emits that block instead, which rotates a loop's test into its
263 // latch.
264 auto to = forward(bb);
265 auto b = live_->block(to);
266 if (to != next_ && to != fun_ && !inlining_ && b->insns.size() <= 4
267 && Select(to->body()->as<App>()->callee())) {
268 auto _ = fe::Restore(inlining_, true);
269 flags_ = nullptr;
270 block(to, b->insns);
271 } else {
272 jump(bb);
273 }
274 } else if (bb) {
275 // Another function or a bodyless one; this function's frame is dead from here on.
276 auto conv = params(bb);
277 pass(arg, arg->num_projs(), conv);
278 leave();
279 jmp(symbol(bb));
280 } else {
281 lam->blame("{} backend: cannot emit the jump to `{}`", backend(), callee).bail();
282 }
283}
284
285void Emitter::run(bool global) {
286 auto live = Liveness(emit_, fun_);
287 live_ = &live;
288 for (const auto& group : slot_groups(target_, live)) {
289 for (auto v : group)
290 slots_[v] = num_slots_;
291 ++num_slots_;
292 }
293
294 regs_ = collect(live);
295 for (const auto& b : live.blocks())
296 for (auto insn : b.insns)
297 for (auto [j, r] : target_.constraint(insn).results)
298 regs_.emplace(Target::result(insn, j), r);
299 auto used = std::array<fe::Vector<bool>, Target::Num_Classes>{};
300 for (size_t c = 0; c != Target::Num_Classes; ++c)
301 used[c].resize(target_.num_regs(Target::Class(c)));
302 for (auto [def, r] : regs_)
303 if (auto& u = used[target_.cls(def)]; r < u.size()) u[r] = true;
304 for (size_t c = 0; c != Target::Num_Classes; ++c) {
305 auto cls = Target::Class(c);
306 for (size_t r = 0; r != used[c].size(); ++r)
307 if (used[c][r] && !target_.caller_saved(cls, r) && !target_.reserved(cls, r)) saved_[c].emplace_back(r);
308 }
309
310 for (const auto& b : live.blocks() | std::views::drop(1)) {
311 auto term = b.lam->body()->as<App>();
312 auto bb = Lam::isa_mut_basicblock(term->callee());
313 if (b.insns.empty() && bb && live.block(bb)) {
314 auto [moves, slot_moves] = this->moves(bb, term->arg());
315 if (moves.empty() && slot_moves.empty()) forward_[b.lam] = bb;
316 }
317 }
318 // Resolve chains; a cycle of such blocks is an endless loop that keeps its jumps.
319 for (auto& [from, to] : forward_) {
320 if (!forward_.contains(to)) continue;
321 auto seen = LamSet{from};
322 while (auto next = fe::lookup(forward_, to)) {
323 if (!seen.emplace(to).second) break;
324 to = next;
325 }
326 }
327 std::erase_if(forward_, [&](const auto& p) { return forward_.contains(p.second); });
328
329 auto order = layout(live, forward_);
330
331 auto n = fun_->num_vars();
332 auto moves = Moves();
333 if (emit_.known().contains(fun_)) emit_.params()[fun_] = param_regs(target_, fun_, regs_);
334 auto locs = arg_locs(target_, fun_->var(), n, num_params(fun_), params(fun_));
335 auto loads = fe::Vector<std::tuple<Reg, const Def*, size_t>>();
336 for (size_t i = 0; i != locs.size(); ++i) {
337 auto x = fun_->var(n, i);
338 auto r = fe::lookup(regs_, x);
339 if (!r) continue;
340 auto cls = target_.cls(x);
341 if (auto a = locs[i].reg)
342 moves.emplace_back(Reg{*r, cls}, Src{.reg = {*a, cls}});
343 else if (auto s = locs[i].stack)
344 loads.emplace_back(Reg{*r, cls}, x->type(), *s);
345 }
346 parallel(std::move(moves), {});
347 // The argument registers are free once their parameters are in place.
348 for (auto [dst, type, i] : loads)
349 load_arg(dst, type, i);
350
351 for (size_t i = 0; i != order.size(); ++i) {
352 auto b = order[i];
353 next_ = i + 1 != order.size() ? order[i + 1]->lam : nullptr;
354 if (i != 0) label_here(label(b->lam));
355 // A `mach.constrain` segment that follows its single predecessor reads the flags set before its split.
356 auto reads = [&](const App* insn) { return std::ranges::contains(Target::operands(insn), flags_); };
357 if (!fell_ || !std::ranges::any_of(b->insns, reads)) flags_ = nullptr;
358 fell_ = false;
359 block(b->lam, b->insns);
360 }
361
362 auto sym = symbol(fun_);
363 if (global) std::println(os_, "\t.globl {}", sym);
364 if (Target::is_elf()) std::println(os_, "\t.type {}, {}", sym, function_type());
365 std::println(os_, "{}:", sym);
366 prologue(os_);
367 os_ << body_.view();
368 if (Target::is_elf()) std::println(os_, "\t.size {}, .-{}", sym, sym);
369}
370
371void mim_mach_emit(Emitter& emitter, bool global) { emitter.run(global); }
372
373} // namespace mim::plug::mach
static auto isa(const Def *def)
Definition axm.h:112
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of def.
Definition axm.cpp:38
static Lam * isa_mut_basicblock(const Def *d)
Definition lam.h:130
static Lam * isa_mut_returning(const Def *d)
Definition lam.h:129
static std::optional< T > isa(const Def *def)
Definition def.h:974
virtual void spill(Src src, const Def *type, size_t i)=0
Stores src, a value of type, into the spill slot i.
virtual void mov_imm(Reg dst, const Def *lit)=0
virtual void prologue(std::ostream &os)=0
The code between the function's label and its body; slots() and saved() are final by then.
size_t spill_slot(const Def *def)
Definition emit.h:146
std::string label(Lam *lam) const
Definition emit.h:103
Src source(const Def *def) const
Definition emit.h:125
virtual void pop_slot(size_t i)=0
virtual void branch_if(size_t r, std::string_view label, bool unless=false)=0
Branches to label if the Bool in register r is set, or with unless, if it is clear.
const Target & target() const
Definition emit.h:100
virtual void reload(Reg dst, const Def *type, size_t i)=0
Loads the spill slot i, a value of type, into dst.
void use_flags(const Def *fl) const
Rejects a use of the flags fl if something clobbered them since.
Definition emit.h:137
virtual std::string_view function_type() const
The argument of .type, e.g. @function.
Definition emit.h:90
virtual void jmp(std::string_view label)=0
friend void mim_mach_emit(Emitter &, bool)
Emitter::emit, compiled once into libmim_mach; Emitter reaches it via GET_FUN_PTR.
Definition emit.cpp:371
virtual void push_slot(size_t i)=0
Pushes the spill slot i; the pops come in reverse order.
virtual void move(Reg dst, Reg src)=0
virtual void swap(Reg, Reg)
Exchanges two registers of one class; only called if there is no scratch().
Definition emit.h:63
size_t use_reg(const Def *def) const
The register of the operand def, a Target::in, possibly under a Target::is_view.
Definition emit.h:116
virtual void slot_addr(size_t dst, size_t first, size_t n)=0
Puts the address of the n slots from first on into the register dst.
virtual void leave()=0
Tears down the frame that prologue() built.
virtual void step(const App *app)=0
virtual void branch_cc(size_t cc, std::string_view label)=0
Branches to label if the condition code cc holds.
nat_t nat(const Def *def) const
Definition emit.h:105
virtual std::optional< Reg > scratch(Target::Class) const
A register of class cls that breaks a copy cycle instead of swap(), if any.
Definition emit.h:65
std::string symbol(Lam *lam)
Definition emit.h:104
size_t def_reg(const Def *def) const
The register of the result def.
Definition emit.h:111
virtual void call_insn(std::string_view sym, std::optional< std::array< size_t, Target::Num_Classes > > num_args)=0
Calls sym with num_args arguments per register class in the ABI's argument registers.
void label_here(std::string_view label)
Definition emit.h:98
std::string_view backend() const
Definition emit.h:101
size_t alloc_slots(nat_t bytes)
Reserves bytes and yields the index of their first slot.
Definition emit.h:152
virtual void load_arg(Reg dst, const Def *type, size_t i)=0
Loads the i-th argument that the caller passed on the stack, a value of type, into dst.
Emitter(const Target &target, std::ostream &os, AsmEmit &emit, Lam *fun)
Definition emit.h:45
Liveness of the values of one scheduled function, as a side table.
Definition liveness.h:35
Liveness(const FunPhase &phase, Lam *fun, bool solve=false)
Bails unless the blocks of the function fun are closed; with solve, it iterates to the fixed point in...
Definition liveness.cpp:11
The machine facts of a native backend that the phases of mach need.
Definition target.h:45
static DefVec operands(const App *insn)
The operands of insn: the argument of a sched's instruction, otherwise the arguments including the me...
Definition target.h:148
static const Def * strip(const Def *def)
The v of in r v, zext d v, or zext d (in r v), otherwise def.
Definition target.h:195
static bool is_mem(const Def *def)
Definition target.h:205
static size_t in_reg(const Def *in)
The register r of in r v.
Definition target.h:187
Class
The register classes; Stack values live in a spill slot and are unbounded.
Definition target.h:48
static bool is_in(const Def *def)
Definition target.h:180
static const Def * sched_insn(const App *app)
Definition target.h:204
static constexpr bool is_elf()
Definition target.h:62
static const Def * result(const App *insn, size_t j)
The j-th projection of the non-memory result of insn.
Definition target.h:153
The mach Plugin
Definition asm.h:15
const Def * imm
Definition emit.h:34
fe::Vector< std::optional< size_t > > ParamRegs
The register per parameter of a function with a convention of its own, or none if it is unused.
Definition target.h:40
size_t num_params(Lam *lam)
The parameters of lam without its return continuation.
Definition liveness.h:145
void interferences(const Liveness &live, const Liveness::Block &block, Keep keep, F f)
Calls f (d, v) for each value v that is live at the definition of d or defined along with it.
Definition liveness.h:188
void for_each_succ(const App *term, auto f)
Calls f for each block, possibly repeatedly, that the jump term passes control or a return continuati...
Definition liveness.h:18
fe::Vector< std::pair< Reg, Src > > Moves
Definition emit.h:37
fe::Vector< const Liveness::Block * > layout(const Liveness &live, const LamMap< Lam * > &forward={})
The blocks of live in emission order: each block is followed by the one it falls through to,...
Definition liveness.cpp:200
fe::Vector< ArgLoc > arg_locs(const Target &target, const Def *arg, size_t n, size_t num, const ParamRegs *conv)
The ArgLocs of the first num of the n arguments in arg under conv, or the ABI if it is nullptr.
Definition liveness.cpp:217
ParamRegs param_regs(const Target &target, Lam *fun, const DefMap< size_t > &regs)
Where the known() function fun receives its parameters, given the registers regs that Color assigned ...
Definition liveness.cpp:234
DefMap< const Def * > Def2Def
Definition def.h:93
GIDSet< Lam * > LamSet
Definition lam.h:211
GIDMap< const Def *, To > DefMap
Definition def.h:91
fe::Vector< const Def * > DefVec
Definition def.h:96
GIDSet< const Def * > DefSet
Definition def.h:92
@ App
Definition def.h:123