14constexpr size_t Inf = std::numeric_limits<size_t>::max();
16constexpr size_t Loop_Exit = 1 << 20;
18size_t add(
size_t a,
size_t b) {
return a >
Inf -
b ?
Inf :
a +
b; }
20const App* root(
const Def* value) {
21 while (
auto ex = value->isa<Extract>())
23 return value->isa<
App>();
27const Def* reroot(
const Def* value,
const Def* old_app,
const Def* new_app) {
28 if (value == old_app)
return new_app;
30 return value->world().extract(reroot(ex->tuple(), old_app, new_app), ex->index());
34bool is_remat(
const Def* value) {
43 : target_(phase.target())
44 , world_(fun->world())
50 , n_(live_.blocks().
size()) {
51 ret_cont_.resize(n_,
false);
52 for (
size_t b = 0;
b != n_; ++
b)
53 node2block_[node(b)] =
b;
54 for (
size_t p = 0;
p != n_; ++
p)
63 for (
size_t b = 0;
b != n_; ++
b)
64 reloads_.emplace_back(
size(b) + 1);
66 for (
size_t b = 0;
b != n_; ++
b)
73 enum class Term { Call, Jump, Other };
75 const Liveness::Block&
block(
size_t b)
const {
return live_.blocks()[
b]; }
76 const Nest::Node* node(
size_t b)
const {
return block(b).node; }
77 size_t size(
size_t b)
const {
return block(b).insns.size(); }
78 bool member(
const Def* v)
const {
return is_value(v, cls_, target_); }
80 std::erase_if(values, [&](
const Def* v) {
return !member(v); });
84 size_t survivors(
size_t b)
const {
86 auto lost = size_t(0);
87 for (
size_t r = 0, e = target_.num_regs(cls_); r != e; ++r)
88 lost += !target_.reserved(cls_, r) &&
clobbered(target_, conv, cls_, r);
89 return k_ > lost ? k_ - lost : 0;
91 const App* term(
size_t b)
const {
return block(b).lam->body()->as<
App>(); }
92 size_t index(Lam* lam)
const {
return size_t(live_.block(lam) - live_.blocks().data()); }
93 Term kind(
size_t b)
const;
95 const Def* arg(
size_t p,
size_t b,
size_t i)
const;
99 void for_each_param(
size_t b,
auto f)
const {
100 auto lam =
block(target(b)).lam;
101 auto n = lam->num_vars();
102 for (
size_t i = 0; i != n; ++i)
103 f(lam->var(n, i), term(b)->arg(n, i));
109 bool summarize(
const Nest::Node*);
110 bool next_uses(
size_t b);
111 size_t next_use(
size_t b,
const Def* v,
size_t pos)
const;
112 void entry(
size_t b);
114 void limit(
size_t b,
DefSet& w,
size_t m,
size_t pos)
const;
115 void reload(
size_t b,
size_t pos,
const Def* v);
118 void build(
size_t b);
119 Subst subst(
const Def2Def& cur)
const {
return Subst(target_, world_, cur, m_, &new_lams_); }
120 const Def*
sched(
const Def* f,
const Def* x);
121 const Def*
spill(
const Def* x);
122 const Def*
slot(
const Def* v)
const {
123 if (
auto slot = fe::lookup(stack_, v))
return slot;
124 v->blame(
"{} backend: `{}` has no spill slot", target_.name(), v).bail();
127 const Target& target_;
137 fe::Vector<size_t> jumps_;
138 fe::Vector<DefMap<size_t>> in_regs_;
139 fe::Vector<bool> ret_cont_;
140 fe::Vector<DefMap<fe::Vector<size_t>>> uses_;
141 fe::Vector<DefMap<size_t>> nu_out_;
143 fe::Vector<DefSet> w_entry_, w_exit_;
144 fe::Vector<fe::Vector<DefVec>> reloads_;
148 LamMap<Lam*> new_lams_;
149 DefMap<const Def*> stack_;
150 fe::Vector<Def2Def> exit_;
151 const Def* m_ =
nullptr;
154Spiller::Term Spiller::kind(
size_t b)
const {
155 auto callee = term(b)->callee();
156 if (callee == fun_->
ret_var() || callee->isa<Extract>())
return Term::Other;
157 if (
auto lam = Lam::isa_mut_basicblock(callee); lam && live_.
block(lam))
return Term::Jump;
161const Def* Spiller::arg(
size_t p,
size_t b,
size_t i)
const {
162 if (ret_cont_[b])
return nullptr;
163 auto lam =
block(b).lam;
164 return term(p)->arg(lam->num_vars(), i);
167void Spiller::next_uses() {
170 for (
size_t b = 0;
b != n_; ++
b) {
171 for (
size_t i = 0; i !=
size(b); ++i)
172 for (
auto v : members(live_.
uses(
block(b).insns[i])))
173 uses_[
b][v].emplace_back(i);
175 if (kind(b) != Term::Jump)
177 uses_[
b][v].emplace_back(
size(b));
184bool Spiller::summarize(
const Nest::Node* node) {
185 auto changed =
false;
186 for (
const auto& scc : node->topo() | std::views::reverse) {
187 auto nodes =
sorted(*scc);
188 auto recursive = nodes.front()->is_recursive();
189 for (
bool todo =
true; todo;) {
192 todo |= summarize(n);
197 if (
auto b = fe::lookup(node2block_, node)) changed |= next_uses(*b);
202bool Spiller::next_uses(
size_t b) {
203 auto d = DefMap<size_t>();
204 auto upd = [&](
const Def* v,
size_t s,
size_t dist) {
205 auto x =
add(dist, node(s)->loop_depth() < node(b)->loop_depth() ? Loop_Exit : 0);
206 auto [i, ins] =
d.emplace(v, x);
207 if (!ins) i->second = std::min(i->second, x);
209 for (
auto v :
block(b).live_out)
211 for (
auto s :
block(b).targets)
212 if (
block(s).live_in.contains(v)) upd(v, s, next_use(s, v, 0));
213 if (kind(b) == Term::Jump)
214 for_each_param(b, [&, s = target(b)](
const Def* x,
const Def* a) {
215 if (member(a) && !Lit::isa(a)) upd(a, s, next_use(s, x, 0));
217 auto changed =
false;
218 for (
auto [v, x] : d) {
219 auto [i, ins] = nu_out_[
b].emplace(v, x);
220 if (!ins && x < i->second) i->second = x, changed =
true;
221 if (ins && x != Inf) changed =
true;
226size_t Spiller::next_use(
size_t b,
const Def* v,
size_t pos)
const {
227 if (
auto us = fe::lookup(uses_[b], v))
228 if (
auto i = std::ranges::lower_bound(*us, pos); i !=
us->end())
return *i -
pos;
229 if (
auto d = fe::lookup(nu_out_[b], v))
return add(
size(b) + 1 - pos, *d);
233void Spiller::limit(
size_t b,
DefSet& w,
size_t m,
size_t pos)
const {
234 while (
w.size() > m) {
236 = *std::ranges::max_element(w, {}, [&](
const Def* v) {
return std::pair(next_use(b, v, pos), v->gid()); });
241void Spiller::reload(
size_t b,
size_t pos,
const Def* v) {
242 auto& rs = reloads_[
b][
pos];
243 if (std::ranges::contains(rs, v))
return;
245 if (!mphi_.contains(v) && !is_remat(v)) spill_.emplace(v);
248void Spiller::entry(
size_t b) {
249 auto lam =
block(b).lam;
250 auto n = lam->num_vars();
253 for (
size_t i = 0; i != n; ++i)
254 if (
auto x = lam->var(n, i); member(x)) params.emplace_back(x);
255 auto next = [&](
const Def* v) {
return next_use(b, v, 0); };
259 = [&](
DefVec&
vs) { std::ranges::sort(vs, {}, [&](
const Def* v) {
return std::pair(next(v), v->gid()); }); };
260 auto fill = [&](
DefVec vs,
size_t cap) {
263 if (take.size() < cap && next(v) != Inf && !std::ranges::contains(take, v)) take.emplace_back(v);
266 auto vars = lam->vars();
268 for (
auto v :
block(b).live_in)
269 if (member(v)) cands.emplace_back(v);
272 auto fixed =
b == 0 || ret_cont_[
b];
273 if (fixed) take = params;
274 if (take.size() > k_)
275 lam->blame(
"{} backend: `{}` takes more than {} register arguments", target_.
name(), lam, k_).bail();
276 std::erase_if(params, [&](
const Def* x) {
return std::ranges::contains(take, x) || next(x) ==
Inf; });
277 std::ranges::copy(params, std::back_inserter(cands));
279 if (!
block(b).live_in.empty()) {
282 assert(std::ranges::contains(
block(p).targets, b));
284 for (
auto v : cands) {
285 auto i = size_t(std::ranges::find(vars, v) - vars.begin());
286 auto a = i < n ? arg(p, b, i) : v;
287 if (!a || Lit::isa(a) || w_exit_[p].
contains(a)) avail.emplace_back(v);
290 }
else if (!node(b)->is_recursive()) {
294 if (
auto c = fe::lookup(in_regs_[b], v)) (*
c == jumps_[
b] ? all : some).emplace_back(v);
300 (next(v) < Loop_Exit ? in_loop : through).emplace_back(v);
302 auto pressure = size_t(0);
303 for (
size_t x = 0; x != n_; ++x)
304 if (node(x)->in_loop(node(b))) pressure = std::max(pressure,
block(x).max_live[cls_]);
305 auto busy = pressure > through.size() ? pressure - through.size() : 0;
306 fill(through, std::min(k_, take.size() + (k_ > busy ? k_ - busy : 0)));
309 for (
auto x : params)
310 if (!std::ranges::contains(take, x)) mphi_.emplace(x);
311 w_entry_[
b] =
DefSet(take.begin(), take.end());
314void Spiller::walk(
size_t b) {
316 auto w = w_entry_[
b];
319 auto use = [&](
const DefVec&
us,
size_t pos,
size_t more,
const Def* at) {
320 if (
us.size() + more > k_)
321 at->blame(
"{} backend: `{}` needs more than {} registers", target_.
name(), at, k_).bail();
323 if (
w.emplace(v).second)
reload(b, pos, v);
324 limit(b, w, k_ - more, pos);
327 for (
size_t i = 0; i != n; ++i) {
328 auto insn =
block(b).insns[i];
329 auto us = members(live_.
uses(insn));
332 if (cls_ != Liveness::Gpr)
c.fixed.clear(),
c.clobbers.clear();
333 if (
c.tied && !member(
c.ops[*
c.tied]))
c.tied.reset();
334 auto live = [&](
const Def* v) {
return next_use(b, v, i + 1) !=
Inf; };
336 for (
auto [j, _] :
copies(c, live))
337 if (
live(
c.ops[j])) cp.emplace_back(
c.ops[j]);
339 auto evict =
us.size() +
c.clobbers.size() + cp.size() > k_;
340 use(us, i,
c.clobbers.size() + (evict ? 0 : cp.size()), insn);
344 auto ds = members(live_.
defs(insn));
345 if (target_.
is_sched_cc(insn)) std::erase_if(ds, [&](
const Def* d) {
return !
live(d); });
347 insn->blame(
"{} backend: `{}` defines more than {} registers", target_.
name(), insn, k_).bail();
348 limit(b, w, k_ - ds.size(), i + 1);
349 w.insert(ds.begin(), ds.end());
353 if (t != Term::Jump) use(members(live_.
term_uses(
block(b))), n, 0, term(b));
354 if (t == Term::Call) limit(b, w, survivors(b), n + 1);
355 w_exit_[
b] = std::move(w);
356 if (t == Term::Jump) {
359 for_each_param(b, [&](
const Def* x,
const Def* a) {
360 if (member(x) && (Lit::isa(a) || w_exit_[b].
contains(a))) ++in_regs_[
s][x];
366void Spiller::couple() {
367 for (
size_t p = 0;
p != n_; ++
p) {
368 if (kind(p) != Term::Jump)
continue;
369 for_each_param(p, [&, b = target(p)](
const Def* x,
const Def* a) {
370 if (!member(x) || Lit::isa(a))
return;
371 if (mphi_.contains(x)) {
372 if (!mphi_.contains(a)) spill_.emplace(a);
373 }
else if (w_entry_[b].
contains(x) && next_use(b, x, 0) != Inf && !w_exit_[p].
contains(a)) {
380const Def* Spiller::sched(
const Def* f,
const Def* x) {
381 auto res = world_.
call<mach::sched>(
f, m_, x);
382 m_ = res->
proj(2, 0);
383 return res->
proj(2, 1);
386const Def* Spiller::spill(
const Def* x) {
return sched(Target::spill(x->type()), x); }
388void Spiller::build() {
390 for (
size_t b = 1;
b != n_; ++
b) {
391 auto lam =
block(b).lam;
392 auto n = lam->num_vars();
393 auto mems = std::ranges::count_if(lam->vars(), [&](
const Def* x) { return mphi_.contains(x); });
394 if (mems == 0)
continue;
396 lam->blame(
"{} backend: return continuation `{}` would need new parameters", target_.
name(), lam).bail();
399 for (
size_t i = 0; i != n; ++i) {
400 auto x = lam->var(n, i);
401 dom.emplace_back(mphi_.contains(x) ? Target::spill_type(x->type()) : x->type());
403 auto new_lam = world_.
mut_con(dom);
404 new_lam->
set(lam->dbg());
405 for (
size_t i = 0; i != n; ++i)
406 new_lam->
var(n, i)->
set(lam->var(n, i)->sym());
407 new_lams_[lam] = new_lam;
410 for (
size_t b = 0;
b != n_; ++
b)
416 for_each_param(b, [&, s = target(b)](
const Def* x,
const Def* a) {
417 if (!mphi_.contains(x)) {
419 auto dead = member(a) && !Lit::isa(a) && (!cur.contains(a) || !w_entry_[s].
contains(x));
420 res.emplace_back(dead ? world_.
lit(x->type(), 0) : subst(cur).rewrite(a));
421 }
else if (Lit::isa(a)) {
422 res.emplace_back(
spill(a));
424 res.emplace_back(
slot(a));
433void Spiller::build(
size_t b) {
434 auto old =
block(b).lam;
435 auto new_lam = fe::lookup(new_lams_, old);
436 if (!new_lam) new_lam = old;
437 auto n = old->num_vars();
438 auto m = new_lam->num_vars();
442 for (
size_t i = 0; i != n; ++i) {
443 auto x = old->var(n, i);
444 auto y = new_lam->var(m, i);
445 if (target_.
is_mem(x) && !m_) m_ = y;
446 if (mphi_.contains(x))
452 if (
const auto& in =
block(b).live_in; !
in.empty()) {
453 const auto& from = exit_[
block(b).parent];
455 if (
auto nv = fe::lookup(from, v)) cur[v] =
nv;
457 for (
auto x : old->vars())
458 if (spill_.contains(x)) stack_[x] =
spill(cur[x]);
460 auto reloads = [&](
size_t pos) {
461 for (
auto v : reloads_[b][pos]) {
463 cur[v] = is_remat(v) ? reroot(v, app->proj(2, 1),
sched(Target::sched_insn(app), app->arg()))
468 for (
size_t i = 0, e =
size(b); i !=
e; ++i) {
470 auto insn =
block(b).insns[i];
471 auto new_app = subst(cur).Rewriter::rewrite(insn);
472 m_ = target_.
is_mem(new_app) ? new_app : new_app->proj(2, 0);
474 for (
auto d : live_.
defs(insn)) {
475 cur[
d] = reroot(d, insn, new_app);
476 if (spill_.contains(d)) stack_[
d] =
spill(cur[d]);
483 auto body =
static_cast<const Def*
>(
nullptr);
484 if (kd == Term::Jump)
485 body = world_.
app(subst(cur).rewrite(
t->callee()), world_.
tuple(args(b, cur)));
487 body = subst(cur).rewrite_jump(t);
489 auto filter = old->filter();
491 old->
unset()->
set(subst(cur).rewrite(filter), body);
493 new_lam->
set(filter->is_closed() ? filter : world_.
lit_ff(), body);
494 exit_[
b] = std::move(cur);
502 if (*k != 0)
return size_t(*k);
503 driver.
log().w(
"ignoring `-X {}:k=0`", target.
name());
508 const auto& t = phase.
target();
509 for (
auto cls : {Liveness::Gpr, Liveness::Fpr})
510 if (t.num_regs(cls) != 0) Spiller(phase, fun, convs, cls, k.value_or(t.num_allocatable(cls))).run();
static auto isa(const Def *def)
const Def * proj(nat_t a, nat_t i) const
Similar to World::extract while assuming an arity of a, but also works on Sigmas and Arrays.
Def * set(size_t i, const Def *)
Successively set from left to right.
const Def * var(nat_t a, nat_t i) noexcept
Def * unset()
Unsets all Def::ops; works even, if not set at all or only partially set.
Some "global" variables needed all over the place.
std::optional< nat_t > arg_nat(std::string_view plugin, std::string_view key)
The number passed as -X <plugin>:<key>=<n>, if any; warns about and ignores a non-number.
Lam * set(Filter filter, const Def *body)
static Lam * isa_mut_basicblock(const Def *d)
const Def * ret_var()
Yields the Lam::var of the Lam::ret_pi.
std::string_view name() const
The plugin name, used as the prefix of diagnostics.
const Lit * lit(const Def *type, u64 val)
const Def * call(const Def *callee, auto &&arg, Args &&... args)
const Def * app(const Def *callee, const Def *arg)
const Def * tuple(Defs ops)
Lam * mut_con(const Def *dom)
Visits the closed Cns with a body of a scheduled World for one Target, each before the ones that call...
const Target & target() const
const Block * block(Lam *lam) const
const DefVec & uses(const App *insn) const
const DefVec & term_uses(const Block &block) const
The values the jump at the end reads.
const DefVec & defs(const App *insn) const
Subst(const Target &target, World &world, const Def2Def &map, const Def *m, const LamMap< Lam * > *lams=nullptr)
The machine facts of a native backend that the phases of mach need.
static bool is_mem(const Def *def)
virtual Constraint constraint(const App *insn) const
The register constraint of insn; by default, it has none.
static const Def * sched_insn(const App *app)
virtual bool is_sched_cc(const App *app) const =0
Is app the sched of the backend's cc?
bool clobbered(const Target &target, const Conv *conv, Target::Class cls, size_t r)
Does a call of a function with the convention conv, or of an ABI function if there is none,...
std::optional< size_t > arg_k(Driver &, const Target &)
The k of spill_fun(): -X <backend>:k=<n>, if given.
bool is_value(const Def *value, Liveness::Class cls, const Target &target)
Is value a value of class cls?
const Liveness::Block * call_cont(const Liveness &live, Lam *fun, const Liveness::Block &block)
The block that a call at the end of block returns to, if any.
fe::Vector< std::pair< size_t, std::optional< size_t > > > copies(const Constraint &c, auto live_after)
The fixed operands with their registers, and the tied one with no register if it is live_after.
fe::Vector< const Nest::Node * > sorted(const Nest::Node::SCC &scc)
The Nodes of scc in a deterministic order.
void spill_fun(const FunPhase &, Lam *fun, const LamMap< Conv > &convs, std::optional< size_t > k)
Spills and reloads until at most k values of each register class are live at every point of a schedul...
const Conv * callee_conv(const LamMap< Conv > &convs, const Liveness::Block &block)
The Conv of the callee that the call at the end of block returns from, if it has one.
DefMap< const Def * > Def2Def
ankerl::unordered_dense::map< K, V, GIDHash< K > > GIDMap
GIDMap< Lam *, To > LamMap
fe::Vector< const Def * > DefVec
GIDSet< const Def * > DefSet