13 auto keep = [&](
const Def* v) {
return target.cls(v) ==
Target::Stack; };
15 for (
const auto& block :
live.blocks())
17 interfere[
a].emplace(b);
18 interfere[
b].emplace(a);
22 auto members = DefMap<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);
31 auto unite = [&](
const Def*
a,
const Def*
b) {
32 a = find(a),
b = find(b);
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;
39 auto& ms = members[
a];
40 ms.insert(ms.end(), members[b].begin(), members[b].end());
44 for (
const auto& block :
live.blocks()) {
45 for (
auto insn :
block.insns)
46 for (
auto d :
live.defs(insn))
48 for (
auto x :
block.params)
50 auto term =
block.lam->body()->as<
App>();
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);
59 auto res = fe::Vector<DefVec>();
61 if (
auto ms = fe::lookup(members, v)) res.emplace_back(std::move(*ms));
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;
71 for (
auto op : def->ops())
72 collect(op, done, regs);
76 auto regs = DefMap<size_t>();
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);
83 collect(
b.lam->body(), done, regs);
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");
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)
102 for (
auto [to, _] : slot_moves | std::views::reverse)
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; });
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; });
114 if (free != moves.end()) {
120 auto [
d,
s] = moves.back();
124 for (
auto& [_, from] : moves)
125 if (from.reg == d) from.reg = *
tmp;
129 for (
auto& [_, from] : moves)
132 else if (from.reg ==
s.reg)
134 std::erase_if(moves, [](
const auto& m) {
return m.first == m.second.reg; });
138 for (
auto [dst, s] : imms)
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);
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);
156 return {std::move(moves), std::move(slot_moves)};
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));
164void Emitter::jump(Lam* target) {
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);
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];
181 parallel(std::move(moves), {});
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);
192 auto ret = arg->proj(n, n - 1);
193 if (ret == ret_)
return epilogue();
196 auto m = k->num_vars();
198 for (
size_t i = 0; i != m; ++i)
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}});
203 parallel(std::move(back), {});
207void Emitter::insn(
const App* app) {
210 auto res = app->proj(2, 1);
221void Emitter::block(Lam* lam,
const fe::Vector<const App*>& insns) {
222 for (
auto app : insns)
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()) {
233 moves.emplace_back(Reg{target_.ret_reg(cls),
cls},
source(a));
235 if (moves.size() > 1) lam->blame(
"{} backend: `{}` returns more than one value",
backend(), lam).bail();
236 parallel(std::move(moves), {});
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();
245 if (!e || !t) lam->blame(
"{} backend: `{}` branches to something other than blocks",
backend(), lam).bail();
246 auto c = ex->index();
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)) {
253 branch_cc(flip ? target_.negate_cc(cc) : cc, taken);
255 c->blame(
"{} backend: a branch on the literal `{}`",
backend(), c).bail();
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);
276 auto conv = params(bb);
277 pass(arg, arg->num_projs(), conv);
281 lam->blame(
"{} backend: cannot emit the jump to `{}`",
backend(), callee).bail();
285void Emitter::run(
bool global) {
288 for (
const auto& group : slot_groups(target_,
live)) {
290 slots_[v] = num_slots_;
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)
302 for (
auto [def, r] : regs_)
303 if (
auto& u = used[target_.cls(def)]; r <
u.size())
u[
r] =
true;
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);
310 for (
const auto& b :
live.blocks() | std::views::drop(1)) {
311 auto term =
b.lam->body()->as<
App>();
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;
319 for (
auto& [from, to] : forward_) {
320 if (!forward_.contains(to))
continue;
322 while (
auto next = fe::lookup(forward_, to)) {
323 if (!seen.emplace(to).second)
break;
327 std::erase_if(forward_, [&](
const auto& p) {
return forward_.contains(
p.second); });
331 auto n = fun_->num_vars();
332 auto moves =
Moves();
333 if (emit_.known().contains(fun_)) emit_.params()[fun_] =
param_regs(target_, fun_, regs_);
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);
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);
346 parallel(std::move(moves), {});
348 for (
auto [dst, type, i] : loads)
351 for (
size_t i = 0; i != order.size(); ++i) {
353 next_ = i + 1 != order.size() ? order[i + 1]->lam :
nullptr;
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;
359 block(
b->lam,
b->insns);
363 if (global) std::println(os_,
"\t.globl {}", sym);
365 std::println(os_,
"{}:", sym);
368 if (
Target::is_elf()) std::println(os_,
"\t.size {}, .-{}", sym, sym);
static auto isa(const Def *def)
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of def.
static Lam * isa_mut_basicblock(const Def *d)
static Lam * isa_mut_returning(const Def *d)
static std::optional< T > isa(const Def *def)
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)
std::string label(Lam *lam) const
Src source(const Def *def) const
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
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.
virtual std::string_view function_type() const
The argument of .type, e.g. @function.
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.
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().
size_t use_reg(const Def *def) const
The register of the operand def, a Target::in, possibly under a Target::is_view.
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
virtual std::optional< Reg > scratch(Target::Class) const
A register of class cls that breaks a copy cycle instead of swap(), if any.
std::string symbol(Lam *lam)
size_t def_reg(const Def *def) const
The register of the result def.
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)
std::string_view backend() const
size_t alloc_slots(nat_t bytes)
Reserves bytes and yields the index of their first slot.
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)
Liveness of the values of one scheduled function, as a side table.
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...
The machine facts of a native backend that the phases of mach need.
static DefVec operands(const App *insn)
The operands of insn: the argument of a sched's instruction, otherwise the arguments including the me...
static const Def * strip(const Def *def)
The v of in r v, zext d v, or zext d (in r v), otherwise def.
static bool is_mem(const Def *def)
static size_t in_reg(const Def *in)
The register r of in r v.
Class
The register classes; Stack values live in a spill slot and are unbounded.
static bool is_in(const Def *def)
static const Def * sched_insn(const App *app)
static constexpr bool is_elf()
static const Def * result(const App *insn, size_t j)
The j-th projection of the non-memory result of insn.
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.
size_t num_params(Lam *lam)
The parameters of lam without its return continuation.
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.
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...
fe::Vector< std::pair< Reg, Src > > Moves
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,...
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.
ParamRegs param_regs(const Target &target, Lam *fun, const DefMap< size_t > ®s)
Where the known() function fun receives its parameters, given the registers regs that Color assigned ...
DefMap< const Def * > Def2Def
GIDMap< const Def *, To > DefMap
fe::Vector< const Def * > DefVec
GIDSet< const Def * > DefSet