19bool mem_valued(
const Def* def) {
25Lam* chain(
const Def* m) {
27 if (
auto ex = m->isa<Extract>()) m = ex->tuple();
28 if (
auto var = m->isa<Var>())
return var->binder()->isa<
Lam>();
29 auto app = m->isa<
App>();
30 if (!app)
return nullptr;
32 if (!m)
return nullptr;
37bool depends(
const Def* def,
const Def* target,
DefSet& done) {
38 if (def == target)
return true;
39 if (def->isa_mut() || !done.emplace(def).second)
return false;
40 for (
auto op : def->ops())
41 if (depends(op, target, done))
return true;
50bool is_param_var(
const Def* def) {
51 if (
auto ex = def->isa<Extract>()) def = ex->tuple();
52 return def->isa<
Var>();
62std::span<const rules::Rewrite> ISel::rewrites(
flags_t flags)
const {
64 if (i == table_.roots.end() || i->flags != flags)
return {};
65 return table_.rewrites.subspan(i->first, i->num);
69std::optional<flags_t> ISel::root_of(
const Def* def)
const {
70 if (
auto ex = def->isa<Extract>())
return Lit::isa(ex->index()) ? std::nullopt : std::optional<flags_t>(0);
71 auto [axm, curry, _] =
Axm::get(def);
72 if (!axm || curry)
return {};
73 if (!rewrites(axm->flags()).empty())
return axm->flags();
77pbqp::Cost ISel::conv(
Ty from,
Want want)
const {
return cost(table_.chains.conv(from, want)); }
80Ty ISel::leaf_ty(
const Def* def)
const {
82 return target_.cls(def) ==
Target::Fpr ? Ty::FReg : Ty::Reg;
86Want ISel::resolve(
const Def* def,
Want want)
const {
93 if (
r.match->num_covers != 0)
return false;
94 for (
size_t i = 0; i !=
r.num_metas; ++i)
95 if (
auto w = want_of(r, i); !
rules::is_param(w) && !table_.chains.total(w))
return false;
100 auto swaps = rule.swaps;
101 auto copies = ankerl::unordered_dense::map<u32, u32>();
104 auto rival =
swap & rule.copy_swaps ? fe::lookup(
copies,
swap & ~rule.copy_swaps) : nullptr;
105 if (
auto c = append(rule, root,
swap, rival ? std::optional(*rival) : std::nullopt, alts))
copies[
swap] = *
c;
106 if (
swap == swaps)
break;
111ISel::append(
const rules::Rewrite& r,
const Def* root,
u32 swap, std::optional<u32> rival,
Alts& alts) {
112 const auto& m = *
r.match;
113 auto metas =
DefVec(table_.max_metas);
114 auto refs =
DefVec(table_.max_refs);
115 if (!m.fn(root,
swap, metas.data(), refs.data()))
return {};
119 alt.covers.resize(m.num_covers);
120 for (
size_t j = 0; j != m.num_refs; ++j) {
121 auto info = table_.refs[m.refs + j];
122 auto ex = refs[j]->isa<
Extract>();
123 auto cover = ex ? ex->tuple() : refs[j];
124 alt.covers[
info.cover].def = cover;
129 auto parent = fe::Vector<u8>(table_.max_covers);
130 auto owner = [&](
u8 o) {
131 while (o != 0 && alt.covers[o - 1].through)
135 auto node = [&](
u8 o) {
return o == 0 ? root : alt.covers[
o - 1].def; };
136 auto demands = [&](
u8 o) ->
auto& {
return o == 0 ? alt.demands : alt.covers[
o - 1].demands; };
137 for (
size_t j = 0; j != m.num_uses; ++j) {
138 auto u = table_.uses[m.uses + j];
139 auto o = owner(
u.owner);
141 auto def = refs[
u.index];
142 auto c = table_.refs[m.refs +
u.index].cover;
143 auto& cov = alt.covers[
c];
145 if (!root_of(cov.def))
return {};
146 if (sole(node(
u.owner), def) != cov.def) {
147 if (mem_valued(cov.def) || c + 1u ==
r.maps)
return {};
151 demands(o).emplace_back(Demand{def, Want::Reg, size_t(c) + 1});
152 }
else if (
auto w = want_of(r,
u.index); w == Want::Lit) {
153 if (!
Lit::isa(metas[
u.index]))
return {};
154 }
else if (w != Want::Param) {
155 auto def = metas[
u.index];
156 auto rw = resolve(def, w);
158 demands(o).emplace_back(Demand{def, rw});
161 for (
size_t i = 0; i !=
r.num_metas; ++i)
162 if (
r.tied >> i & 1 && overwritten(metas[i])) ++alt.copies;
164 if ((
swap &
r.copy_swaps) && !(rival && alt.copies < *rival))
return {};
165 if (!holds(alt))
return {};
166 alt.metas =
DefVec(metas.begin(), metas.begin() +
r.num_metas);
167 auto res = alt.copies;
168 alts.emplace_back(std::move(alt));
172const Def* ISel::build(
const Alt& alt) {
173 const auto&
r = *alt.rule;
174 auto holes =
DefVec(
r.num_metas, [&](
size_t i) {
175 auto w = want_of(r, i);
176 return rules::is_param(w) ? rewrite(alt.metas[i]) : hole(alt.metas[i], resolve(alt.metas[i], w));
178 auto res =
r.build(
new_world(), holes.data());
179 if (!
r.maps)
return res;
180 map(alt.covers[
r.maps - 1].def, res);
181 return res->proj(2, 1);
184void ISel::match(
const Def* def,
Alts& alts) {
185 auto r = root_of(def);
187 for (
const auto& rule : rewrites(*r))
188 append(rule, def, alts);
191const App* ISel::sole(
const Def* parent,
const Def* def)
const {
192 auto app = parent->isa<
App>();
193 if (!app || !root_of(app) || uses(app->arg()) != 1)
return nullptr;
194 if (std::ranges::count(app->arg()->projs(), def) != 1)
return nullptr;
195 if (def->isa<Extract>() && key(def) != def)
return sole_value(def);
196 return uses(def) == 1 ? def->isa<
App>() : nullptr;
199bool ISel::holds(
const Alt& alt) {
201 if (!alt.rule->maps)
return true;
202 auto ld = alt.covers[alt.rule->maps - 1].def->as<
App>();
203 auto bb = chain(ld->arg(2, 0));
204 if (!bb)
return false;
207 for (
const auto& d : alt.demands)
208 if (!
d.inner && (!
d.def->in_scope(bb) || depends(
d.def, ld, done)))
return false;
217 for (
auto mut :
old_world().externals().muts())
220 auto defs =
DefVec(counted_.begin(), counted_.end());
221 std::ranges::sort(defs, [](
const Def* a,
const Def* b) {
return a->gid() < b->gid(); });
224 for (
auto def : defs) {
227 if (alts.empty())
continue;
228 alts_[def] = std::move(alts);
229 nodes.emplace_back(def);
234 auto resolve = [](
const Alt& alt, fe::Vector<Demand>& demands) {
235 for (
auto& d : demands)
236 if (d.inner) d.inner = alt.
covers[d.inner - 1].inner;
238 for (
auto def : nodes)
239 for (
auto& alt : alts_[def]) {
240 for (
size_t j = alt.
covers.size(); j-- != 0;) {
241 auto& cover = alt.
covers[j];
242 if (cover.through)
continue;
244 auto& inner = alts_.at(cover.def);
245 auto same = [&](
const Alt& a) {
return !a.rule && std::ranges::equal(a.demands, cover.demands); };
246 auto i = std::ranges::find_if(inner, same);
247 cover.inner = size_t(i - inner.begin()) + 1;
248 if (i == inner.end()) {
250 a.demands = cover.demands;
251 inner.emplace_back(std::move(a));
259 for (
auto def : nodes) {
261 for (
const auto& alt : alts_[def]) {
263 for (
const auto& d : alt.
demands)
264 if (!alts_.contains(key(d.def))) c += d.inner ?
pbqp::Cost::inf() : leaf(d.def, d.want);
265 costs.emplace_back(c);
267 ids[def] = graph.add(costs);
270 for (
auto def : nodes) {
271 const auto& alts = alts_[def];
272 auto keys = fe::Vector<DefVec>(alts.size());
275 for (
size_t i = 0; i != alts.size(); ++i)
276 for (
const auto& d : alts[i].demands) {
277 auto op = keys[i].emplace_back(key(d.def));
278 if (alts_.contains(op) && seen.emplace(op).second) operands.emplace_back(op);
280 for (
auto op : operands) {
281 const auto& op_alts = alts_[op];
282 auto costs =
pbqp::Matrix(alts.size(), op_alts.size(), [&](
size_t i,
size_t j) {
283 const auto& o = op_alts[j];
284 auto c = pbqp::Cost(0);
285 for (size_t k = 0; k != alts[i].demands.size(); ++k) {
286 if (keys[i][k] != op) continue;
287 const auto& d = alts[i].demands[k];
289 c += !o.rule && j + 1 == d.inner ? 0 : pbqp::Cost::inf();
291 c += o.rule ? conv(o.rule->type, d.want) : pbqp::Cost::inf();
295 if (std::ranges::any_of(costs, [](
pbqp::Cost c) {
return c != 0; }))
296 graph.add_edge_costs(ids[def], ids[op], costs);
301 for (
auto def : nodes) {
302 auto i = std::ranges::find_if(alts_[def], [
this](
const Alt& a) {
return a.rule && atomic(*a.rule); });
303 auto found = i != alts_[def].end();
304 fallback[ids[def]] = found ? size_t(i - alts_[def].begin()) : 0;
305#ifdef MIM_ENABLE_CHECKS
306 if (!found) fe::throwf(
"{} isel: `{}` has no atomic rule", target_.name(), def);
309#ifdef MIM_ENABLE_CHECKS
310 if (
pbqp::evaluate(graph, fallback).is_inf()) fe::throwf(
"the atomic rules must cover the program");
313 log().d(
"{} isel: {} nodes, {} edges, cost {}", target_.name(), graph.num_nodes(), graph.num_edges(),
316 const auto& picked = sol.feasible() ? sol.choices : fallback;
317 if (
auto d =
arg_value(args(),
"isel-dot")) {
318 auto out =
Out(std::string(*d));
319 auto& os = *out.os();
320 for (
auto def : nodes)
321 std::println(os,
"// n{} = {}", ids[def], def);
324 for (
auto def : nodes) {
325 auto c = picked[ids[def]];
327 for (
const auto& cover : alts_[def][c].covers)
328 if (!cover.through) roots_[cover.def] = def;
333bool ISel::overwritten(
const Def* def)
const {
return !
Lit::isa(def) && !is_param_var(def) && uses(def) > 1; }
335void ISel::count(
const Def* def) {
336 if (!counted_.emplace(def).second)
return;
337 for (
auto op : def->ops()) {
345const App* ISel::sole_value(
const Def* def)
const {
346 if (
auto app = key(def)->isa<App>(); app != def && uses(def) == 1 && uses(app) == 2)
347 if (
auto m = app->proj(2, 0); m && uses(m) != 0)
return app;
351const Def* ISel::key(
const Def* def)
const {
352 if (
auto ex = def->isa<Extract>(); ex &&
Lit::isa(ex->index()) == 1)
353 if (
auto app = ex->tuple()->isa<App>(); app && root_of(app) && mem_valued(app))
return app;
357const Alt* ISel::choice(
const Def* def)
const {
358 if (
auto c = choices_.find(def); c != choices_.end())
return &alts_.at(def)[
c->second];
366const Def* ISel::select(
const Def* def) {
367 if (
auto i = repls_.find(def); i != repls_.end())
return i->second;
368 auto alt = choice(def);
369 auto res = build(*alt);
370 if (!res) def->blame(
"{} backend: rule `{}` cannot select `{}`", target_.name(), alt->rule->name, def).bail();
371 return repls_[def] = res;
374const Def* ISel::selected(
const Def* def) {
375 auto alt = choice(def);
376 if (!alt)
return nullptr;
377 if (alt->rule)
return convert(
select(def), alt->rule->type, rules::reg_want(alt->rule->type));
379 rewrite(roots_.at(def));
383const Def* ISel::hole(
const Def* def, Want want) {
384 if (
auto alt = choice(def); alt && alt->rule)
return convert(
select(def), alt->rule->type, want);
386 if (
auto app = key(def); app != def)
387 if (
auto alt = choice(app); alt && alt->rule)
return convert(rewrite(def), alt->rule->type, want);
388 return convert(rewrite(def), leaf_ty(def), want);
391const Def* ISel::convert(
const Def* x, Ty from, Want want) {
392 if (rules::is_literal(want))
return x;
393 auto&
w = new_world();
394 if (
Lit::isa(x) && (from == Ty::Reg || from == Ty::FReg)) from = Ty::Lit;
395 auto to = table_.chains.target(from, want).first;
396 for (
auto t = from;
t != to;) {
397 auto c = &table_.conversions[table_.chains.first[size_t(t)][size_t(to)]];
398 auto holes = x->projs(
c->arity);
399 x =
c->build(w, holes.data());
406 if (
auto res = selected(ex))
return res;
413 if (
auto res = selected(app))
return res;
417 app->
blame(
"{} backend: instruction selection does not support `{}`", target_.name(), axm).bail();
static auto isa(const Def *def)
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of def.
const Def * type() const noexcept
Yields the "raw" type of this Def (maybe nullptr).
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 std::optional< T > isa(const Def *def)
A Phase performs one self-contained task over the whole World.
A dependent function type.
World & new_world()
Create new Defs into this.
World & old_world()
Get old Defs from here.
const Def * rewrite_imm_App(const App *) override
friend void swap(Rewriter &rw1, Rewriter &rw2) noexcept
virtual const Def * rewrite_imm_Extract(const Extract *)
const Def * map(const Def *old_def, const Def *new_def)
The World represents the whole program and manages creation of MimIR nodes (Defs).
Rewrites the core, mach, and math operations of a world that mach.legalize lowered into the instructi...
const Def * rewrite_imm_App(const App *) final
bool analyze() final
Runs the optional pre-analysis on old_world(), typically to a fixed point, before rewriting begins.
const Def * rewrite_imm_Extract(const Extract *) final
static const Target & of(Driver &driver)
The Target of the one loaded backend; every backend's Target is a mach::Target.
static bool is_lowered(const Axm *axm)
Is axm an operation that instruction selection must have replaced?
A saturating cost; Cost::inf forbids an option or option pair.
static constexpr Cost inf()
An owning row-major cost matrix; it views its own storage, so writes go through span().
u32 cost(const App *app)
The cost of the instruction app: its latency plus one, so of two equally fast covers the shorter wins...
const Def * mem_def(const Def *def)
Returns def if it is a core.M a, or else its first projection that is.
constexpr u32 Copy
A register-to-register copy, which move elimination makes free of latency.
u32 cost
The summed instruction costs of its rhs.
constexpr bool is_literal(Want want)
Does a hole of type want take a literal rather than a replacement?
constexpr bool is_param(Want w)
Is a meta variable that w wants bound to its rewrite rather than an operand?
@ Mem
By its memory, which only the match uses.
Want
What a rule wants of the term a meta variable matches; a Param is bound but no operand.
constexpr Want literal_of(Want want)
The literal form of a hole of type want, or want itself.
Ty
The non-terminal a rule yields by the type of its rhs: a register of either class,...
A closed rule lhs ↦ rhs, whose metas want num_metas consecutive entries of wants.
The generated tables of one backend, as its isel_rules.h defines them.
fe::Vector< Cover > covers
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.
u32 copies
The operands its two-address instructions overwrite although something else uses them.
const rules::Rewrite * rule
nullptr for an inner alternative, whose id is its index plus one.
fe::Vector< Demand > demands
Phase * mim_mach_isel(World &, flags_t annex, const rules::Table &table)
A new ISel for the annex annex of a backend, with the rules table; compiled once into libmim_mach.
An alternative of a PBQP node: a match rooted there, or the class of all matches covering it as the s...
GIDMap< const Def *, To > DefMap
fe::Vector< const Def * > DefVec
GIDSet< const Def * > DefSet
std::optional< std::string_view > arg_value(fe::View< std::string > args, Keys... keys)
fe::Vector< OptionId, 8 > Choices
One option per node, indexed by node id.
Solution solve(const Graph &graph, fe::View< size_t > rn_priority={})
Heuristic PBQP solver.
Cost evaluate(const Graph &graph, fe::View< OptionId > choices)
All solver functions are safe to call concurrently on a graph that nobody mutates meanwhile.
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::Vector< Cost, 4 > Costs