16constexpr pbqp::Cost Move = 4;
18constexpr pbqp::Cost Callee_Saved = 1;
20class Prune :
public Rewriter {
22 Prune(
const Target& target, World& world,
const DefSet& dead)
27 const Def* rewrite(
const Def* def)
final {
28 if (def->isa_mut() || def->is_closed())
return def;
29 if (
auto ex = def->isa<Extract>(); ex && target_.is_mem(def))
30 if (
auto app = ex->tuple()->isa<App>(); app && dead_.contains(app))
return rewrite(target_.prev_mem(app));
35 const Target& target_;
42 for (
const auto& block :
live.blocks()) {
43 if (
auto lam =
block.lam; lam->filter() != fun->world().lit_ff()) {
44 auto body = lam->body();
45 lam->unset()->set(
false, body);
49 auto count = DefMap<size_t>();
52 auto unused = [&](
const Def*
d) {
53 auto n = fe::lookup(count, d);
57 for (
bool todo =
true; todo;) {
59 for (
const auto& block :
live.blocks()) {
61 auto cond = ex ? target.isa_sched_cc(ex->index()) :
nullptr;
62 for (
auto insn :
block.insns | std::views::reverse) {
63 if (dead.contains(insn) || insn == cond || !target.is_removable(insn))
continue;
64 auto ds =
live.defs(insn);
65 if (ds.empty() || !std::ranges::all_of(ds, unused))
continue;
68 for (
auto u :
live.uses(insn))
73 if (dead.empty())
return false;
75 auto p = Prune(target, fun->world(), dead);
82 Colorer(
const Target& target,
88 std::ostream* dot =
nullptr)
96 , n_(target.num_regs(
cls))
97 , interfere_(n_, n_, [](size_t i, size_t j) {
return i == j ?
pbqp::Cost::inf() : 0; })
98 , tie_(n_, n_, [](
size_t i,
size_t j) {
return i == j ? 0 :
pbqp::Cost::inf(); })
99 , move_(n_, n_, [](
size_t i,
size_t j) {
return i == j ? 0 : Move; })
100 , base_(n_, [&](
size_t r) {
102 return target.caller_saved(cls, r) ? pbqp::Cost(0) : Callee_Saved;
107 for (
const auto& block : live_.blocks())
109 live_, block, [&](
const Def* v) {
return ids_.contains(v); },
110 [&](
const Def*
a,
const Def*
b) { link(a, b, interfere_); });
116 const DefMap<size_t>& regs()
const {
return regs_; }
125 void add(
const Def* v);
127 auto id = fe::lookup(ids_, target_.strip(v));
128 return id ? &costs_[*
id] :
nullptr;
130 void fix(
const Def* v,
size_t r) {
131 if (
auto cs = costs(v))
132 for (
size_t o = 0;
o != n_; ++
o)
135 void forbid(
const Def* v,
size_t r) {
138 void prefer(
const Def* v,
size_t r) {
139 if (
auto cs = costs(v))
140 for (
size_t o = 0;
o != n_; ++
o)
141 if (o != r) (*cs)[
o] += Move;
144 a = target_.strip(a),
b = target_.strip(b);
146 if (
auto i = fe::lookup(ids_, a))
147 if (
auto j = fe::lookup(ids_, b)) graph_.add_edge_costs(*i, *j, m);
149 void jump(Lam* target,
const Def* arg) {
150 auto n = target->num_vars();
151 for (
size_t i = 0; i != n; ++i)
152 link(arg->proj(n, i), target->var(n, i), move_);
155 const Target& target_;
157 const Liveness& live_;
166 fe::Vector<pbqp::Costs> costs_;
167 fe::Vector<size_t> points_;
168 size_t num_points_ = 0;
169 const pbqp::Matrix interfere_, tie_, move_;
171 DefMap<size_t> regs_;
174void Colorer::add(
const Def* v) {
175 ids_[v] = graph_.
add(base_);
176 values_.emplace_back(v);
177 costs_.emplace_back(base_);
178 points_.emplace_back(num_points_);
182void Colorer::nodes() {
184 for_each_use(live_, [&](
const Def* u) { used.emplace(u); });
186 for (
const auto& block : live_.
blocks()) {
188 for (
auto x : live_.
params(block))
190 for (
auto insn :
block.insns) {
194 implied.emplace(Target::result(insn, j));
195 for (
auto d : live_.
defs(insn))
196 if (
is_value(d) && (used.contains(d) || implied.contains(d)))
add(d);
201void Colorer::constraints() {
202 for (
const auto& block : live_.
blocks()) {
203 for (
auto insn :
block.insns) {
206 if (cls_ == Liveness::Gpr) {
207 for (
auto [j, r] :
c.fixed)
209 for (
auto [j, r] :
c.results)
210 fix(Target::result(insn, j), r);
211 for (
auto r :
c.clobbers)
212 for (
auto u : live_.
uses(insn))
215 if (
c.tied &&
is_value(
c.ops[*
c.tied])) link(
c.ops[*
c.tied], Target::result(insn, 0), tie_);
220void Colorer::copies() {
221 auto args = [&](
const Def* arg,
size_t n,
size_t num,
const Conv*
conv) {
222 auto locs =
arg_locs(target_, arg, n, num, conv ? &
conv->params :
nullptr);
223 for (
size_t i = 0; i != num; ++i)
224 if (
auto x = arg->proj(n, i);
is_value(x) && locs[i].reg) prefer(x, *locs[i].reg);
228 for (
const auto& block : live_.
blocks()) {
229 auto term =
block.lam->body()->as<
App>();
230 auto callee = term->callee();
231 if (callee == fun_->
ret_var()) {
232 for (
auto a : term->args())
234 }
else if (
auto bb = Lam::isa_mut_basicblock(callee); bb && live_.
block(bb)) {
235 jump(bb, term->arg());
236 }
else if (
auto bb = Lam::isa_mut_basicblock(callee)) {
237 args(term->arg(), term->num_args(), term->num_args(), fe::lookup(convs_, bb));
238 }
else if (
auto f = Lam::isa_mut_returning(callee)) {
239 auto conv = fe::lookup(convs_, f);
240 args(term->arg(), term->num_args(), term->num_args() - 1, conv);
241 if (
auto k =
call_cont(live_, fun_, block)) {
242 for (
auto v : k->live_in)
243 if (
auto cs = costs(v))
244 for (
size_t r = 0;
r != n_; ++
r)
246 for (
auto x : live_.
params(*k))
253void Colorer::solve() {
254 for (
size_t i = 0; i != values_.size(); ++i)
258 auto order = fe::Vector<size_t>(values_.size(), [](
size_t i) { return i; });
259 auto fixed = fe::Vector<std::ptrdiff_t>(values_.size(),
260 [&](
size_t i) { return std::ranges::count(costs_[i], pbqp::Cost::inf()); });
261 std::ranges::sort(order, {}, [&](
size_t i) {
return std::tuple(points_[i], -fixed[i], i); });
262 auto priority = fe::Vector<size_t>(values_.size());
263 for (
size_t r = 0;
r != order.size(); ++
r)
264 priority[order[r]] = order.size() - 1 -
r;
267 std::println(*dot_,
"// fun {}", fun_);
268 for (
size_t i = 0; i != values_.size(); ++i)
269 std::println(*dot_,
"// n{} = {}", i, values_[i]);
272 if (!sol.feasible()) {
274 for (
size_t i = 0; i != values_.size(); ++i)
275 if (sol.conflicts[i])
conflicts.emplace_back(values_[i]);
276 fun_->
blame(
"{} backend: cannot assign registers in `{}`; conflicting values: {}", target_.
name(), fun_,
277 fe::Join(conflicts,
", "))
280 for (
size_t i = 0; i != values_.size(); ++i)
281 regs_[values_[i]] = sol.choices[i];
287 Checker(
const Target& target, Lam* fun,
const Liveness& live,
const LamMap<Conv>& convs, Liveness::Class cls)
297 bool is_value(
const Def* v)
const {
return mach::is_value(v, cls_, target_); }
298 void walk(
const Def* def,
const Def* at);
299 std::optional<size_t>
reg(
const Def* v)
const {
300 if (
auto r = fe::lookup(regs_, target_.
strip(v)))
return *
r;
303 [[noreturn]]
void fail(
const Def* at, std::string msg) {
304 at->blame(
"{} backend: register assignment of `{}`: {}", target_.
name(), fun_, msg).bail();
307 const Target& target_;
309 const Liveness& live_;
310 const LamMap<Conv>& convs_;
311 Liveness::Class cls_;
312 DefMap<size_t> regs_;
315void Checker::walk(
const Def* def,
const Def* at) {
316 if (def->isa_mut() || def->is_closed() || target_.
is_mem(def))
return;
317 if (target_.
is_in(def)) {
318 auto v = target_.
strip(def);
319 if (target_.
cls(v) != cls_)
return;
320 auto r = Target::in_reg(def);
321 auto [i, ins] = regs_.emplace(v, r);
322 if (!live_.
local(v) || !
is_value(v)) fail(at, std::format(
"`{}` is no value", v));
323 if (target_.
reserved(cls_, r)) fail(at, std::format(
"`{}` is in a reserved register", v));
324 if (!ins && i->second != r) fail(at, std::format(
"`{}` is in two registers", v));
327 if (live_.
local(def)) {
328 for (
auto d : def->projs())
329 if (
is_value(d)) fail(at, std::format(
"`{}` is used without a register", d));
332 if (
auto app = def->isa<App>(); app && target_.
prev_mem(app)) fail(at, std::format(
"`{}` is off the chain", app));
333 for (
auto op : def->ops())
338 for (
const auto& block : live_.
blocks()) {
339 for (
auto insn :
block.insns) {
340 walk(insn->callee(), insn);
341 walk(insn->arg(), insn);
343 auto term =
block.lam->body()->as<
App>();
344 if (
auto ex = term->callee()->isa<Extract>(); ex && target_.
isa_sched_cc(ex->index())) {
345 walk(ex->tuple(), term);
346 walk(term->arg(), term);
352 for (
const auto& block : live_.
blocks()) {
353 for (
auto insn :
block.insns) {
355 if (cls_ == Liveness::Gpr) {
356 for (
auto [j, r] :
c.results) {
357 auto d = Target::result(insn, j);
358 if (regs_.emplace(d, r).first->second != r)
359 fail(insn, std::format(
"`{}` is not in its fixed register", d));
361 for (
auto [j, r] :
c.fixed)
362 if (!target_.
is_in(
c.ops[j]) || Target::in_reg(
c.ops[j]) != r)
363 fail(insn, std::format(
"operand `{}` is not in its fixed register",
c.ops[j]));
364 for (
auto r :
c.clobbers)
365 for (
auto u : live_.
uses(insn))
366 if (
reg(u) == r) fail(insn, std::format(
"operand `{}` is in a clobbered register", u));
368 if (
c.tied &&
is_value(
c.ops[*
c.tied]) &&
reg(
c.ops[*
c.tied]) !=
reg(Target::result(insn, 0)))
369 fail(insn, std::format(
"`{}` is not in the register of operand `{}`", Target::result(insn, 0),
374 for (
const auto& block : live_.
blocks()) {
376 live_, block, [&](
const Def* v) {
return regs_.contains(v); },
377 [&](
const Def*
a,
const Def*
b) {
378 if (regs_[a] == regs_[b])
379 fail(
block.lam, std::format(
"`{}` and `{}` interfere but share a register", a, b));
381 if (
auto k =
call_cont(live_, fun_, block))
382 for (
auto v : k->live_in)
384 fail(
block.lam, std::format(
"`{}` lives across a call in a clobbered register", v));
388Conv convention(
const Target& target,
390 const Liveness&
live,
392 const DefMap<size_t>& regs) {
393 auto res = Conv{.params =
param_regs(target, fun, regs)};
394 auto& cl = res.clobbers;
395 auto classes = {Liveness::Gpr, Liveness::Fpr};
396 for (
auto cls : classes) {
397 cl[
cls].resize(target.num_regs(cls));
398 if (!cl[cls].
empty()) cl[
cls][target.ret_reg(cls)] =
true;
400 for (
auto [v, r] : regs)
401 if (
auto cls = target.cls(v); target.caller_saved(cls, r)) cl[
cls][
r] =
true;
402 for (
size_t i = 0, n = fun->num_vars(); i != res.params.size(); ++i)
403 if (
auto r = res.params[i]) cl[target.cls(fun->var(n, i))][*
r] =
true;
405 for (
const auto& block :
live.blocks()) {
406 for (
auto insn :
block.insns) {
407 auto c = target.constraint(insn);
408 for (
auto [_, r] :
c.results)
409 cl[Liveness::Gpr][
r] =
true;
410 for (
auto r :
c.clobbers)
411 cl[Liveness::Gpr][
r] =
true;
415 for (
auto cls : classes)
416 for (
size_t r = 0;
r != cl[
cls].size(); ++
r)
426 const auto& t = phase.
target();
430 for (
auto cls : {Liveness::Gpr, Liveness::Fpr}) {
431 if (t.num_regs(cls) == 0)
continue;
432 auto colorer = Colorer(t, fun,
live, convs,
known, cls, dot);
434 regs.insert(colorer.regs().begin(), colorer.regs().end());
440 for (
auto cls : {Liveness::Gpr, Liveness::Fpr})
441 if (t.num_regs(cls) != 0) Checker(t, fun,
live, convs, cls).run();
442 if (
known) convs[fun] = convention(t, fun,
live, convs, regs);
452std::ostream* RegAlloc::dot() {
453 if (
auto d =
arg_value(target_args(),
"color-dot")) {
454 if (dot_.name().empty()) dot_.name() = std::string(*d);
World & world() const noexcept
const Def * var(nat_t a, nat_t i) noexcept
nat_t num_vars() noexcept
fe::Error & blame(fe::cite_string< Args... > s, Args &&... args) const
Reports an error that blames this; chain Error::n for Notes and Error::bail to throw.
static Lam * isa_mut_returning(const Def *d)
const Def * ret_var()
Yields the Lam::var of the Lam::ret_pi.
virtual const Def * rewrite(const Def *)
std::string_view name() const
The plugin name, used as the prefix of diagnostics.
Assign(World &world, const Liveness &live, const DefMap< size_t > ®s)
Visits the closed Cns with a body of a scheduled World for one Target, each before the ones that call...
const LamSet & known() const
The functions with a convention of their own, see mach::known.
const Target & target() const
Liveness of the values of one scheduled function, as a side table.
const auto & blocks() const
In pre-order of the Nest with siblings in topological order, so a block comes after the block it is n...
const Block * block(Lam *lam) const
const DefVec & uses(const App *insn) const
const DefVec & params(const Block &block) const
bool local(const Def *def) const
Is def a parameter of a block or a result of an instruction on a chain, or a projection thereof?
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...
const DefVec & defs(const App *insn) const
The machine facts of a native backend that the phases of mach need.
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)
const Def * prev_mem(const App *app) const
The memory app continues, if app is an instruction on a mem.M 0 chain.
virtual Constraint constraint(const App *insn) const
The register constraint of insn; by default, it has none.
virtual bool reserved(Class cls, size_t r) const =0
Is r never available to register allocation?
static bool is_in(const Def *def)
Class cls(const Def *def) const
virtual size_t ret_reg(Class cls) const =0
const App * isa_sched_cc(const Def *cond) const
The sched of a cc that yields cond, if any.
static constexpr Cost inf()
void set_node_costs(NodeId n, fe::View< Cost > costs)
Replace a cost vector; the option count must not change.
NodeId add(fe::View< Cost > costs)
Add a node with the given cost vector.
void for_each_use(const Liveness &live, auto f)
Calls f for each use of a value in live.
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,...
fe::Vector< std::pair< size_t, size_t > > results
Results, see Target::result, that land in a given register.
bool is_value(const Def *value, Liveness::Class cls, const Target &target)
Is value a value of class cls?
size_t num_params(Lam *lam)
The parameters of lam without its return continuation.
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.
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.
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.
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...
void rewrite_blocks(const Liveness &live, Rewriter &rw)
Rewrites the filter and body of each block of live in place.
bool constrain_fun(const Liveness &live)
Copies fixed and live tied operands by a jump right before their instruction, keeping the graph chord...
LamSet known(World &world)
The closed Cns with a body that get a convention of their own instead of the ABI.
void color_fun(const FunPhase &, Lam *fun, Liveness live, LamMap< Conv > &convs, std::ostream *dot)
Assigns a register to every value by one PBQP per function and register class (Buchwald,...
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.
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 ...
GIDMap< const Def *, To > DefMap
GIDMap< Lam *, To > LamMap
fe::Vector< const Def * > DefVec
GIDSet< const Def * > DefSet
std::optional< std::string_view > arg_value(fe::View< std::string > args, Keys... keys)
BasicMatrix< const Cost > MatrixView
Solution solve(const Graph &graph, fe::View< size_t > rn_priority={})
Heuristic PBQP solver.
void write_dot(std::ostream &out, const Graph &graph, fe::View< OptionId > choices={})
Write graph in Graphviz DOT format with cost vectors and matrices as HTML-like labels.
fe::Bitset conflicts(const Graph &graph, fe::View< OptionId > choices)
Nodes whose choice is Cost::inf in their cost vector or, given the neighbour's choice,...
fe::Vector< Cost, 4 > Costs