MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
isel.cpp
Go to the documentation of this file.
2
3#include <array>
4#include <optional>
5#include <print>
6#include <ranges>
7#include <span>
8
9#include <pbqp/dot.h>
10#include <pbqp/solver.h>
11
12#include <mim/plugin.h>
13
14namespace mim::plug::mach {
15
16namespace {
17
18/// Is @p def a memory operation, whose value is its second result?
19bool mem_valued(const Def* def) {
20 auto t = def->type();
21 return t->num_projs() == 2 && Axm::isa<core::M>(t->proj(2, 0));
22}
23
24/// The continuation whose `mem.M` chain @p m is on.
25Lam* chain(const Def* m) {
26 for (;;) {
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;
31 m = core::mem_def(app->arg());
32 if (!m) return nullptr;
33 }
34}
35
36/// Does @p def depend on @p target without going through a mutable?
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;
42 return false;
43}
44
45constexpr pbqp::Cost Inf = pbqp::Cost::inf();
46
47pbqp::Cost cost(u32 c) { return c == rules::Inf ? Inf : pbqp::Cost(c); }
48
49/// Is @p def a Var or a projection of one?
50bool is_param_var(const Def* def) {
51 if (auto ex = def->isa<Extract>()) def = ex->tuple();
52 return def->isa<Var>();
53}
54
55} // namespace
56
57/*
58 * Table
59 */
60
61/// The rewrites with the root axiom @p flags.
62std::span<const rules::Rewrite> ISel::rewrites(flags_t flags) const {
63 auto i = std::ranges::lower_bound(table_.roots, flags, {}, &rules::Root::flags);
64 if (i == table_.roots.end() || i->flags != flags) return {};
65 return table_.rewrites.subspan(i->first, i->num);
66}
67
68/// The root of the rules covering @p def: its axiom, or `0` for an Extract at a dynamic index.
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();
74 return {};
75}
76
77pbqp::Cost ISel::conv(Ty from, Want want) const { return cost(table_.chains.conv(from, want)); }
78
79/// The non-terminal of @p def, which is no node: a literal, a floating-point register, or a general-purpose one.
80Ty ISel::leaf_ty(const Def* def) const {
81 if (Lit::isa(def)) return Ty::Lit;
82 return target_.cls(def) == Target::Fpr ? Ty::FReg : Ty::Reg;
83}
84
85/// The hole of type @p want that @p def fills: a RegImm or RegSh is an immediate if @p def is a literal that fits.
86Want ISel::resolve(const Def* def, Want want) const {
87 if (auto l = rules::literal_of(want); l != want) return literal(def, l) ? l : Want::Reg;
88 return want;
89}
90
91/// An atomic rule has no inner nodes and only holes that every non-terminal converts into.
92bool ISel::atomic(const rules::Rewrite& r) 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;
96 return true;
97}
98
99void ISel::append(const rules::Rewrite& rule, const Def* root, Alts& alts) {
100 auto swaps = rule.swaps;
101 auto copies = ankerl::unordered_dense::map<u32, u32>();
102 // Ascending subsets of `swaps`, so the rival of a swap comes first.
103 for (u32 swap = 0;; swap = ((swap | ~swaps) + 1) & swaps) {
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;
107 }
108}
109
110std::optional<u32>
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 {};
116
117 auto alt = Alt();
118 alt.rule = &r;
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;
125 if (info.kind == rules::Ref::Mem && uses(refs[j]) != 1) return {};
126 }
127
128 // A pure inner node that something else uses is looked through: the match takes its operands but not the node.
129 auto parent = fe::Vector<u8>(table_.max_covers);
130 auto owner = [&](u8 o) {
131 while (o != 0 && alt.covers[o - 1].through)
132 o = parent[o - 1];
133 return o;
134 };
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);
140 if (u.ref) {
141 auto def = refs[u.index];
142 auto c = table_.refs[m.refs + u.index].cover;
143 auto& cov = alt.covers[c];
144 parent[c] = o;
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 {};
148 cov.through = true;
149 continue;
150 }
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);
157 if (rules::is_literal(rw) && !literal(def, rw)) return {};
158 demands(o).emplace_back(Demand{def, rw});
159 }
160 }
161 for (size_t i = 0; i != r.num_metas; ++i)
162 if (r.tied >> i & 1 && overwritten(metas[i])) ++alt.copies;
163 // Such a swap only differs from its rival in which operand it overwrites.
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));
169 return res;
170}
171
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));
177 });
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);
182}
183
184void ISel::match(const Def* def, Alts& alts) {
185 auto r = root_of(def);
186 if (!r) return;
187 for (const auto& rule : rewrites(*r))
188 append(rule, def, alts);
189}
190
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;
197}
198
199bool ISel::holds(const Alt& alt) {
200 // The replacement sits at the inner node whose memory it replaces, so the root's holes must be available there.
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;
205 // `done` is shared, since a Def that does not reach `ld` never will.
206 auto done = DefSet();
207 for (const auto& d : alt.demands)
208 if (!d.inner && (!d.def->in_scope(bb) || depends(d.def, ld, done))) return false;
209 return true;
210}
211
212/*
213 * Selection
214 */
215
217 for (auto mut : old_world().externals().muts())
218 count(mut);
219
220 auto defs = DefVec(counted_.begin(), counted_.end());
221 std::ranges::sort(defs, [](const Def* a, const Def* b) { return a->gid() < b->gid(); });
222
223 auto nodes = DefVec();
224 for (auto def : defs) {
225 auto alts = Alts();
226 match(def, alts);
227 if (alts.empty()) continue;
228 alts_[def] = std::move(alts);
229 nodes.emplace_back(def);
230 }
231
232 // Each inner node of a match becomes an alternative of the node it covers; equal ones are one class.
233 // A cover's operands follow it in preorder, so their classes are known before its own.
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;
237 };
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;
243 resolve(alt, cover.demands);
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()) {
249 auto a = Alt();
250 a.demands = cover.demands;
251 inner.emplace_back(std::move(a));
252 }
253 }
254 resolve(alt, alt.demands);
255 }
256
257 auto graph = pbqp::Graph();
258 auto ids = DefMap<pbqp::NodeId>();
259 for (auto def : nodes) {
260 auto costs = pbqp::Costs();
261 for (const auto& alt : alts_[def]) {
262 auto c = alt.rule ? pbqp::Cost(alt.rule->cost + alt.copies * rules::Copy) : pbqp::Cost(0);
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);
266 }
267 ids[def] = graph.add(costs);
268 }
269
270 for (auto def : nodes) {
271 const auto& alts = alts_[def];
272 auto keys = fe::Vector<DefVec>(alts.size());
273 auto operands = DefVec();
274 auto seen = DefSet();
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);
279 }
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];
288 if (d.inner)
289 c += !o.rule && j + 1 == d.inner ? 0 : pbqp::Cost::inf();
290 else
291 c += o.rule ? conv(o.rule->type, d.want) : pbqp::Cost::inf();
292 }
293 return c;
294 });
295 if (std::ranges::any_of(costs, [](pbqp::Cost c) { return c != 0; }))
296 graph.add_edge_costs(ids[def], ids[op], costs);
297 }
298 }
299
300 auto fallback = pbqp::Choices(graph.num_nodes(), 0);
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);
307#endif
308 }
309#ifdef MIM_ENABLE_CHECKS
310 if (pbqp::evaluate(graph, fallback).is_inf()) fe::throwf("the atomic rules must cover the program");
311#endif
312 auto sol = pbqp::solve(graph);
313 log().d("{} isel: {} nodes, {} edges, cost {}", target_.name(), graph.num_nodes(), graph.num_edges(),
314 sol.cost.value());
315 // RN is a heuristic, but the atomic rules always remain a valid cover.
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);
322 pbqp::write_dot(os, graph, picked);
323 }
324 for (auto def : nodes) {
325 auto c = picked[ids[def]];
326 choices_[def] = c;
327 for (const auto& cover : alts_[def][c].covers)
328 if (!cover.through) roots_[cover.def] = def;
329 }
330 return false;
331}
332
333bool ISel::overwritten(const Def* def) const { return !Lit::isa(def) && !is_param_var(def) && uses(def) > 1; }
334
335void ISel::count(const Def* def) {
336 if (!counted_.emplace(def).second) return;
337 for (auto op : def->ops()) {
338 if (op) {
339 ++uses_[op];
340 count(op);
341 }
342 }
343}
344
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;
348 return nullptr;
349}
350
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;
354 return def;
355}
356
357const Alt* ISel::choice(const Def* def) const {
358 if (auto c = choices_.find(def); c != choices_.end()) return &alts_.at(def)[c->second];
359 return nullptr;
360}
361
362/*
363 * Replacement
364 */
365
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;
372}
373
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));
378 // The root of the match covering this inner node builds it.
379 rewrite(roots_.at(def));
380 return lookup(def);
381}
382
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);
385 // The value of a memory operation has the non-terminal of the operation's rule.
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);
389}
390
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());
400 t = c->to;
401 }
402 return x;
403}
404
406 if (auto res = selected(ex)) return res;
408}
409
410const Def* ISel::rewrite_imm_App(const App* app) {
411 auto& w = new_world();
412 if (Axm::isa<core::M>(app)) return w.call<core::M>(w.lit_nat_0());
413 if (auto res = selected(app)) return res;
414
415 if (auto axm = app->axm(); axm && Target::is_lowered(axm) && !app->type()->isa<Pi>() && !app->type()->isa<Type>()
416 && !app->type()->isa<Nat>())
417 app->blame("{} backend: instruction selection does not support `{}`", target_.name(), axm).bail();
418 return RWPhase::rewrite_imm_App(app);
419}
420
421Phase* mim_mach_isel(World& world, flags_t annex, const rules::Table& table) {
422 return new ISel(world, annex, Target::of(world.driver()), table);
423}
424
425} // namespace mim::plug::mach
const Axm * axm() const
Definition lam.h:257
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
Base class for all Defs.
Definition def.h:285
const Def * type() const noexcept
Yields the "raw" type of this Def (maybe nullptr).
Definition def.h:1116
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.
Definition def.h:329
Extracts from a Sigma or Array-typed Extract::tuple the element at position Extract::index.
Definition tuple.h:360
static std::optional< T > isa(const Def *def)
Definition def.h:974
Out()=default
A Phase performs one self-contained task over the whole World.
Definition phase.h:25
A dependent function type.
Definition lam.h:14
World & new_world()
Create new Defs into this.
Definition phase.h:418
World & old_world()
Get old Defs from here.
Definition phase.h:417
const Def * rewrite_imm_App(const App *) override
Definition phase.cpp:317
friend void swap(Rewriter &rw1, Rewriter &rw2) noexcept
Definition rewrite.h:154
virtual const Def * rewrite_imm_Extract(const Extract *)
const Def * map(const Def *old_def, const Def *new_def)
Definition rewrite.cpp:29
The World represents the whole program and manages creation of MimIR nodes (Defs).
Definition world.h:43
Driver & driver()
Definition world.h:107
Rewrites the core, mach, and math operations of a world that mach.legalize lowered into the instructi...
Definition isel.h:77
const Def * rewrite_imm_App(const App *) final
Definition isel.cpp:410
bool analyze() final
Runs the optional pre-analysis on old_world(), typically to a fixed point, before rewriting begins.
Definition isel.cpp:216
const Def * rewrite_imm_Extract(const Extract *) final
Definition isel.cpp:405
static const Target & of(Driver &driver)
The Target of the one loaded backend; every backend's Target is a mach::Target.
Definition target.h:55
static bool is_lowered(const Axm *axm)
Is axm an operation that instruction selection must have replaced?
Definition target.h:142
A saturating cost; Cost::inf forbids an option or option pair.
Definition graph.h:31
static constexpr Cost inf()
Definition graph.h:39
A PBQP problem graph.
Definition graph.h:252
An owning row-major cost matrix; it views its own storage, so writes go through span().
Definition graph.h:189
u32 cost(const App *app)
The cost of the instruction app: its latency plus one, so of two equally fast covers the shorter wins...
Definition insn.h:24
const Def * mem_def(const Def *def)
Returns def if it is a core.M a, or else its first projection that is.
Definition core.h:152
constexpr u32 Copy
A register-to-register copy, which move elimination makes free of latency.
Definition rule_table.h:121
u32 cost
The summed instruction costs of its rhs.
Definition rule_table.h:81
constexpr bool is_literal(Want want)
Does a hole of type want take a literal rather than a replacement?
Definition rule_table.h:129
constexpr bool is_param(Want w)
Is a meta variable that w wants bound to its rewrite rather than an operand?
Definition rule_table.h:126
@ Mem
By its memory, which only the match uses.
Definition rule_table.h:52
Want
What a rule wants of the term a meta variable matches; a Param is bound but no operand.
Definition rule_table.h:28
constexpr Want literal_of(Want want)
The literal form of a hole of type want, or want itself.
Definition rule_table.h:132
Ty
The non-terminal a rule yields by the type of its rhs: a register of either class,...
Definition rule_table.h:38
A closed rule lhs ↦ rhs, whose metas want num_metas consecutive entries of wants.
Definition rule_table.h:79
The generated tables of one backend, as its isel_rules.h defines them.
Definition rule_table.h:220
The mach Plugin
Definition asm.h:15
fe::Vector< Cover > covers
Definition isel.h:46
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.
Definition target.h:27
u32 copies
The operands its two-address instructions overwrite although something else uses them.
Definition isel.h:48
const rules::Rewrite * rule
nullptr for an inner alternative, whose id is its index plus one.
Definition isel.h:44
fe::Vector< Demand > demands
Definition isel.h:45
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.
Definition isel.cpp:421
fe::Vector< Alt > Alts
Definition isel.h:51
An alternative of a PBQP node: a match rooted there, or the class of all matches covering it as the s...
Definition isel.h:43
u64 flags_t
Definition types.h:39
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
uint32_t u32
Definition types.h:27
uint8_t u8
Definition types.h:27
std::optional< std::string_view > arg_value(fe::View< std::string > args, Keys... keys)
Definition plugin.h:65
@ Lam
Definition def.h:123
@ Var
Definition def.h:123
@ Extract
Definition def.h:123
@ App
Definition def.h:123
fe::Vector< OptionId, 8 > Choices
One option per node, indexed by node id.
Definition graph.h:68
Solution solve(const Graph &graph, fe::View< size_t > rn_priority={})
Heuristic PBQP solver.
Definition solver.cpp:629
Cost evaluate(const Graph &graph, fe::View< OptionId > choices)
All solver functions are safe to call concurrently on a graph that nobody mutates meanwhile.
Definition solver.cpp:591
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.
Definition dot.cpp:23
fe::Vector< Cost, 4 > Costs
Definition graph.h:66