31enum class Kind :
u8 {
Hole,
Axm,
Lit,
Nat,
Idx,
App,
Tuple,
Pack,
Extract,
Sigma,
Arr,
Pi,
Bot };
43constexpr std::string_view name(
Ty ty) {
46 case Ty::t: return #t;
53constexpr std::string_view name(
Want want) {
56 case Want::w: return #w;
64bool uses(
const Def* def,
const Def* meta,
const Var* var,
DefSet& done) {
65 if (def == meta)
return true;
66 if (!def || !done.emplace(def).second)
return false;
67 if (
auto ex = meta->isa<Extract>(); def == var && ex && ex->tuple() == var)
return true;
68 if (
auto ex = def->isa<Extract>(); ex && ex->tuple() == var &&
Lit::isa(ex->index()))
return false;
69 if (
auto type = def->type(); type && uses(type, meta, var, done))
return true;
70 for (
auto op : def->ops())
71 if (uses(op, meta, var, done))
return true;
75bool uses(
const Def* def,
const Def* meta,
const Var* var) {
77 return uses(def, meta, var, done);
81void checks(
const Def* def,
DefVec& conds,
DefSet& done) {
82 if (def->isa_mut() || !done.emplace(def).second)
return;
84 for (
auto op : def->ops())
85 checks(op, conds, done);
97 std::vector<u32> covers;
98 std::vector<RefInfo> refs;
99 std::vector<rules::Use> uses;
100 std::vector<std::pair<u32, u32>> swaps;
105 explicit Table(
const Gen& gen)
110 for (
auto op : def->projs())
111 commutes_.emplace(
op->as<Axm>()->flags());
115 void universes(
const Def* formats,
const Def* sizes) {
116 for (
auto op :
formats->projs())
117 formats_.emplace_back(op);
118 for (
auto op :
sizes->projs())
119 sizes_.emplace_back(op);
122 void collect(
const Def* def) {
123 if (
auto rule = def->isa<Rule>())
125 else if (
auto lam = def->isa_mut<Lam>(); lam && lam->type()->as<Pi>()->is_implicit())
127 else if (
auto tuple = def->isa<Tuple>())
128 for (
auto op : tuple->ops())
133 void sort() { std::ranges::stable_sort(rewrites_, {}, &Rewrite::root); }
134 void dump(std::ostream& os)
const;
138 Want classify(
const Def* type)
const;
140 Ty nonterminal(
const Rule* rule,
const Def* type)
const;
142 Ty type(
const Rule* rule)
const;
144 size_t cost(
const Def* def,
DefSet& done)
const;
145 size_t cost(
const Def* def)
const {
147 return cost(def, done);
150 const App* isa_marker(
flags_t flags,
const Def* def)
const {
151 if (flags == 0)
return nullptr;
152 auto [axm, curry, _] =
Axm::get(def);
153 return axm && curry == 0 && axm->flags() == flags ? def->as<
App>() : nullptr;
157 void check(
const std::vector<Shape>&,
const std::vector<size_t>& ids)
const;
162 std::vector<u32> ops;
163 bool operator==(
const Node&)
const =
default;
166 size_t operator()(
const Node& n)
const noexcept {
167 auto h = fe::hash_combine(
size_t(n.kind), n.val);
168 for (
auto op : n.ops)
169 h = fe::hash_combine(h, op);
198 std::vector<Meta> metas;
202 void add(
const Rule*,
const Var* param =
nullptr);
203 std::vector<Meta> metas(
const Rule*);
204 void guard(
const Def*, std::vector<Meta>&);
205 u32 node(
const Def*);
206 u32 node_(
const Def*);
207 u32 make(Node, std::string comment = {});
208 u32 hole(
u64 i) {
return make({Kind::Hole, i, {}}); }
210 u32 marked(
const Def* meta,
Want want) {
211 auto id = node(meta);
212 if (nodes_[
id].kind != Kind::Hole) meta->blame(
"{}: `{}` must be a meta variable", gen_.isel(), meta).bail();
213 marks_[nodes_[
id].val] = want;
217 u32 widened(
const Def* op,
Want want) {
219 if (nodes_[
id].kind != Kind::Hole)
op->blame(
"{}: `{}` must be a meta variable", gen_.isel(), op).bail();
220 marks_[nodes_[
id].val] = want;
224 size_t num_metas()
const {
return metas_.size(); }
226 std::optional<size_t> meta(
const Def* def)
const {
228 auto [axm, curry, _] =
Axm::get(def);
231 def = def->as<
App>()->arg();
233 if (
auto i = fe::lookup(meta_ids_, def))
return *i;
236 u32 tied(
const Def* rhs)
const;
242 ankerl::unordered_dense::map<u64, Want> marks_;
243 const Var* var_ =
nullptr;
245 DefMap<size_t> meta_ids_;
247 ankerl::unordered_dense::map<Node, u32, Node::Hash> node2id_;
248 fe::Vector<Node> nodes_;
249 fe::Vector<std::string> comments_;
250 fe::Vector<Rewrite> rewrites_;
251 fe::Vector<Conv> convs_;
252 ankerl::unordered_dense::set<flags_t> commutes_;
254 friend std::string sig(
const Table&,
u32,
const std::vector<Meta>&,
bool);
257Want Table::classify(
const Def* type)
const {
258 if (
auto want = gen_.
classify(type))
return *want;
259 if (math::isa_f(type))
return Want::FReg;
260 auto&
w =
type->world();
261 if (type ==
w.sigma({w.type_i64(), w.type_i2()}))
return Want::Scaled;
265Ty Table::nonterminal(
const Rule* rule,
const Def* type)
const {
266 switch (classify(type)) {
267 case Want::Base:
return Ty::Base;
268 case Want::Index:
return Ty::Index;
269 case Want::Scaled:
return Ty::Scaled;
270 case Want::Reg:
return Ty::Reg;
271 case Want::FReg:
return Ty::FReg;
272 default: rule->blame(
"{}: `{}` must fix its address form in `{}`", gen_.
isel(), type, rule).bail();
276Ty Table::type(
const Rule* rule)
const {
277 auto rhs = rule->rhs();
278 if (
auto t = rhs->isa<Tuple>(); t &&
t->num_ops() == 2 && core::isa_mem(
t->op(0))) rhs =
t->op(1);
279 if (isa_marker(gen_.
annexes().
zx, rhs))
return Ty::Zx;
280 auto type = rule->rhs()->type();
281 if (
type->num_projs() == 2 && Axm::isa<core::M>(
type->proj(2, 0)))
type =
type->proj(2, 1);
282 return nonterminal(rule, type);
285size_t Table::cost(
const Def* def,
DefSet& done)
const {
286 if (def->isa_mut() || !done.emplace(def).second)
return 0;
288 if (
auto [axm, curry, _] = Axm::get(def); axm && curry == 0 && axm->plugin() == gen_.
backend_id())
289 n += gen_.
cost(def->as<App>());
290 for (
auto op : def->ops())
299void Table::family(Lam* lam) {
300 if (!seen_.emplace(lam).second)
return;
301 auto body = lam->body();
302 while (body->isa_mut<Lam>() && body->type()->as<Pi>()->is_implicit())
303 body = body->as_mut<
Lam>()->body();
304 auto rule = body->isa<
Rule>();
305 if (!rule) lam->blame(
"{}: the body of the family `{}` is no rule", gen_.
isel(), lam).bail();
306 auto param = lam->has_var();
307 if (!param)
return collect(lam->body());
312 for (
auto def : {rule->type()->dom(), rule->type()->codom(), rule->rhs()})
313 checks(def, conds, done);
314 std::erase_if(conds, [&](
const Def* c) {
315 auto fvs =
c->free_vars();
316 return fvs.size() != 1 || !fvs.contains(param);
318 if (conds.empty() && !rule->guard()->has_free_var(param)) {
319 if (lam->body() != rule)
320 lam->blame(
"{}: `{}` of `{}` must be instantiated", gen_.
isel(), lam->dom(), lam).bail();
321 return add(rule, param);
324 auto&
w = lam->world();
325 auto dom = lam->dom();
326 auto universe = dom ==
w.type_nat() ? &sizes_ : dom ==
w.arr(2,
w.type_nat()) ? &formats_ :
nullptr;
327 if (!universe) lam->blame(
"{}: no values to instantiate `{}` of `{}` with", gen_.
isel(), dom, lam).bail();
328 for (
auto val : *universe) {
330 for (
auto cond : conds) {
331 auto c = Lit::isa<bool>(VarRewriter(param, val).rewrite(cond));
332 if (!c) lam->blame(
"{}: cannot decide `{}` of `{}` at `{}`", gen_.
isel(), cond, lam, val).bail();
335 if (ok) collect(lam->reduce_body(val));
340void Table::add(
const Rule* rule,
const Var* param) {
341 if (!seen_.emplace(rule).second)
return;
342 auto fvs = rule->free_vars();
343 if (!(fvs.empty() || (param && fvs.size() == 1 && fvs.contains(param))))
344 rule->blame(
"{}: rule `{}` is not closed", gen_.
isel(), rule).bail();
345 if (rule->guard() == rule->world().lit_ff())
return;
350 if (param) metas_.emplace_back(param);
353 for (
size_t i = 0; i != n; ++i)
354 metas_.emplace_back(n == 1 ? var_ : var_->
proj(n, i));
356 for (
size_t i = 0; i != metas_.size(); ++i)
357 meta_ids_[metas_[i]] = i;
359 auto lhs = rule->lhs();
360 auto mapped =
u32(-1);
362 if (var_ && (lhs == var_ || (zx &&
zx->arg() == var_))) {
363 auto from = var_->
type();
364 if (!Idx::isa(from) && classify(from) == Want::Reg)
365 rule->
blame(
"{}: the meta variable of conversion `{}` must be a register or a non-terminal", gen_.
isel(),
370 bool literal =
lit &&
lit->arg() == var_;
371 if (!literal && rule->guard() != rule->world().lit_tt())
372 rule->
blame(
"{}: the guard of conversion `{}` is no `lit` of its meta variable", gen_.
isel(), rule).bail();
373 convs_.emplace_back(Conv{.name = rule->sym().str(),
374 .rho = std::format(
"{} ↝ {}", rule->dom(), rule->codom()),
375 .cost =
cost(rule->rhs()),
376 .from = literal ? Ty::Lit
378 : nonterminal(rule, from),
380 .rhs = node(rule->rhs()),
381 .arity = num_metas()});
386 if (
auto t = lhs->isa<Tuple>(); t &&
t->num_ops() == 2 && core::isa_mem(
t->op(0))) {
387 mapped = node(
t->op(0));
390 auto [root, _, __] = Axm::get(lhs);
391 if (!root && !lhs->isa<Extract>())
392 rule->blame(
"{}: the lhs of `{}` must apply an axiom or extract", gen_.
isel(), rule).bail();
395 auto name = root ? std::format(
"{}({})", rule->sym().str(), root->sym().str()) : rule->sym().str();
396 rewrites_.emplace_back(Rewrite{.name = std::move(name),
397 .rho = std::format(
"{} ↝ {}", rule->dom(), rule->codom()),
398 .cost =
cost(rule->rhs()),
399 .root = root ? root->flags() : 0,
402 .rhs = node(rule->rhs()),
404 .tied =
tied(rule->rhs()),
405 .metas = metas(rule)});
409u32 Table::tied(
const Def* rhs)
const {
413 while (!todo.empty()) {
414 auto def = todo.back();
416 if (def->isa_mut() || !done.emplace(def).second)
continue;
417 if (
auto [axm, curry, _] = Axm::get(def); axm && curry == 0 && axm->plugin() == gen_.
backend_id())
418 if (
auto i = gen_.
tied(def->as<App>())) {
419 auto arg = def->as<
App>()->arg();
420 if (
auto m = meta(arg->proj(arg->num_projs(), *i))) res |= 1u << *m;
422 for (
auto op : def->ops())
423 todo.emplace_back(op);
428std::vector<Table::Meta> Table::metas(
const Rule* rule) {
429 auto res = std::vector<Meta>();
430 auto n = num_metas();
431 for (
size_t i = 0; i != n; ++i) {
432 auto meta = metas_[i];
433 auto type = meta->type();
434 bool param = !uses(rule->rhs(), meta, var_);
435 for (
size_t j = 0; j != n && !param; ++j)
436 param = j != i && uses(metas_[j]->
type(), meta, var_);
438 auto want = Want::Param;
440 auto mark = marks_.find(i);
441 auto marked = [&](
Want dflt) {
return mark == marks_.end() ? dflt : mark->second; };
442 if (Idx::isa(type)) {
443 want = marked(Want::Reg);
444 }
else if (math::isa_f(type)) {
445 want = marked(Want::FReg);
446 }
else if (
type->isa<Nat>() || Axm::isa<core::M>(type) ||
type->isa<Pi>()) {
448 }
else if (
auto addr = gen_.
classify(type)) {
451 rule->blame(
"{}: meta variable `{}` of `{}` has type `{}`, which is no operand", gen_.
isel(), meta,
456 res.emplace_back(want, node(type));
458 guard(rule->guard(), res);
462void Table::guard(
const Def* g, std::vector<Meta>& metas) {
463 auto&
w =
g->world();
464 if (g ==
w.lit_tt())
return;
465 if (
auto conj = Axm::isa(core::bit2::and_, g)) {
466 auto [
a,
b] =
conj->args<2>();
472 auto set = [&](
const Def* meta,
Want from,
Want to) {
473 for (
size_t i = 0; i != num_metas(); ++i)
474 if (metas_[i] == meta && metas[i].want == from) {
478 g->blame(
"{}: guard `{}` must constrain an operand of type `Idx s` or, for `lit`, a `Nat`", gen_.
isel(), g)
482 if (
auto imm = isa_marker(gen_.
annexes().
imm, g))
483 set(
imm->arg(), Want::Reg, Want::Imm);
484 else if (
auto lit = isa_marker(gen_.
annexes().
lit, g))
485 set(
lit->arg(), Want::Param, Want::Lit);
487 g->blame(
"{}: guard `{}` is no conjunction of `imm` and `lit`", gen_.
isel(), g).bail();
490u32 Table::node(
const Def* def) {
491 if (
auto id = fe::lookup(def2node_, def))
return *
id;
492 auto id = node_(def);
493 return def2node_[def] =
id;
496u32 Table::node_(
const Def* def) {
497 if (
auto i = fe::lookup(meta_ids_, def))
return hole(*i);
498 if (var_ && def == var_) {
499 auto ops = std::vector<u32>();
500 for (
size_t i = num_metas() - var_->
num_projs(); i != num_metas(); ++i)
501 ops.emplace_back(hole(i));
502 return make({Kind::Tuple, 0, std::move(ops)});
506 if (
auto addr = isa_marker(
a.addr, def))
return marked(
addr->arg(), Want::Addr);
507 if (
auto ri = isa_marker(
a.reg_imm, def))
return widened(ri->arg(), Want::RegImm);
508 if (
auto rs = isa_marker(
a.reg_sh, def))
return widened(rs->arg(), Want::RegSh);
509 if (
auto scaled = isa_marker(
a.scaled, def))
return marked(
scaled->arg(), Want::Scaled);
510 if (
auto zx = isa_marker(
a.zx, def))
511 return meta_ids_.contains(
zx->arg()) ? marked(
zx->arg(), Want::Zx) : node(
zx->arg());
512 if (
auto axm = def->isa<Axm>())
return make({Kind::Axm, axm->flags(), {}}, axm->sym().str());
513 if (
auto lit = def->isa<Lit>())
return make({Kind::Lit,
lit->get(), {node(
lit->type())}});
514 if (def->isa<Nat>())
return make({Kind::Nat, 0, {}});
515 if (def->isa<Idx>())
return make({Kind::Idx, 0, {}});
516 if (
auto app = def->isa<App>()) {
517 auto [axm, curry, _] = Axm::get(app);
518 u64 flags = app->callee_type()->is_implicit() ? u64(Implicit) : 0;
519 auto arg = node(app->arg());
520 if (axm && curry == 0 && !app->type()->isa<Type>()) {
523 if (commutes_.contains(axm->flags()) && nodes_[arg].kind == Kind::Tuple && nodes_[arg].ops.size() == 2)
526 return make({Kind::App, flags, {node(app->callee()), arg}});
528 if (
auto ex = def->isa<Extract>()) {
529 auto flags = core::isa_mem(ex) ? Mem : 0;
530 return make({Kind::Extract, flags, {node(ex->tuple()), node(ex->index())}});
532 if (
auto pack = def->isa_imm<Pack>())
return make({Kind::Pack, 0, {node(pack->arity()), node(pack->body())}});
533 if (
auto arr = def->isa_imm<Arr>())
return make({Kind::Arr, 0, {node(arr->arity()), node(arr->body())}});
534 if (
auto pi = def->isa_imm<Pi>())
return make({Kind::Pi, pi->is_implicit(), {node(pi->dom()), node(pi->codom())}});
535 if (def->isa<Bot>())
return make({Kind::Bot, 0, {}});
537 auto ops = std::vector<u32>();
538 if (def->isa<Tuple>() || def->isa_imm<Sigma>())
539 for (
auto op : def->ops())
540 ops.emplace_back(node(op));
541 if (def->isa<Tuple>())
return make({Kind::Tuple, 0, std::move(ops)});
542 if (def->isa_imm<Sigma>())
return make({Kind::Sigma, 0, std::move(ops)});
544 def->blame(
"{}: cannot put `{}` into a rule table", gen_.isel(), def).bail();
547u32 Table::make(
Node node, std::string comment) {
548 if (
auto id = fe::lookup(node2id_, node))
return *
id;
549 auto id =
u32(nodes_.size());
550 node2id_.emplace(node,
id);
551 nodes_.emplace_back(std::move(node));
552 comments_.emplace_back(std::move(comment));
559 Code(std::ostream& os,
const Table& table)
563 Shape match(
size_t id, u32 lhs, std::span<const u32> types);
567 template<
class... Args>
568 void line(std::format_string<Args...> fmt, Args&&... args) {
569 std::println(os_,
" {}", std::format(fmt, std::forward<Args>(args)...));
573 std::string
fresh(
char prefix) {
return std::format(
"{}{}", prefix, next_++); }
574 const Table::Node& node(u32 n)
const {
return t_.nodes_[n]; }
575 const std::string& comment(u32 n)
const {
return t_.comments_[n]; }
576 bool inner(u32 n)
const {
return !in_type_ && node(n).kind == Kind::App && node(n).val & Inner && n != root_; }
578 std::string name(
const std::string& expr);
580 void match(u32 n,
const std::string& expr,
bool spine =
false);
581 void match_inner(u32 n,
const std::string& expr);
582 void match_app(u32 n,
const std::string& expr,
bool spine =
false);
583 void match2(u32 n,
const std::string& expr, std::string_view isa, std::string_view op0, std::string_view op1);
584 void ref(u32 n,
const std::string& expr, Ref kind);
585 std::string build_(u32 n);
590 bool in_type_ =
false;
593 std::vector<bool> bound_;
594 ankerl::unordered_dense::map<u32, std::string> cover_vars_;
595 std::span<const u32> types_;
596 ankerl::unordered_dense::map<u32, std::string> built_;
600Shape Code::match(
size_t id,
u32 lhs, std::span<const u32> types) {
603 "inline bool match_{}(const Def* def, [[maybe_unused]] u32 swap, [[maybe_unused]] const Def** m, "
604 "[[maybe_unused]] const Def** r) {{",
607 line(
"return true;");
608 std::println(os_,
"}}");
612 auto children = std::vector<std::vector<u8>>(shape_.covers.size() + 1);
613 for (
const auto& r : shape_.refs)
614 if (
r.kind == Ref::Value) children[
r.owner].emplace_back(
r.cover);
615 auto perm = std::vector<u8>(shape_.covers.size(),
u8(-1));
616 auto stack = std::vector<u8>(children[0].rbegin(), children[0].rend());
618 while (!stack.empty()) {
619 auto c = stack.back();
621 if (perm[c] !=
u8(-1))
continue;
623 stack.insert(stack.end(), children[c + 1].rbegin(), children[c + 1].rend());
625 if (next != shape_.covers.size()) fe::throwf(
"{}: an inner node is no operand of its rule", t_.gen_.
isel());
626 auto res = std::move(shape_);
627 auto owner = [&](
u8 o) {
return o == 0 ?
o :
u8(perm[o - 1] + 1); };
628 for (
auto& r : res.refs)
629 r.cover =
perm[
r.cover],
r.owner = owner(
r.owner);
630 for (
auto& u : res.uses)
631 u.owner = owner(
u.owner);
632 auto covers = res.covers;
633 for (
size_t k = 0; k != covers.size(); ++k)
634 res.covers[perm[k]] = covers[k];
638void Code::walk(
u32 lhs) {
644 bound_.assign(types_.size(),
false);
645 match(lhs,
"def",
true);
648std::string Code::name(
const std::string& expr) {
649 if (std::ranges::all_of(expr, [](
char c) {
return std::isalnum(c) ||
c ==
'_'; }))
return expr;
650 auto res =
fresh(
'd');
651 line(
"auto {} = {};", res, expr);
655void Code::match2(
u32 n,
const std::string& e, std::string_view isa, std::string_view op0, std::string_view op1) {
657 line(
"auto {} = {}->{};", x, e, isa);
658 line(
"if (!{}) return false;", x);
659 match(node(n).ops[0], std::format(
"{}->{}()", x, op0));
660 match(node(n).ops[1], std::format(
"{}->{}()", x, op1));
663void Code::ref(
u32 n,
const std::string& e,
Ref kind) {
664 auto k = std::ranges::find(shape_.covers, n) - shape_.covers.begin();
665 if (
size_t(k) == shape_.covers.size()) shape_.covers.emplace_back(n);
666 auto j = shape_.refs.size();
667 shape_.refs.emplace_back(RefInfo{
u8(k), owner_, kind});
668 if (kind == Ref::Value) shape_.uses.emplace_back(rules::Use{owner_,
u8(j),
true});
669 line(
"r[{}] = {};", j, e);
672void Code::match_inner(
u32 n,
const std::string& e) {
673 if (
auto var = cover_vars_.find(n); var != cover_vars_.end()) {
674 line(
"if ({} != {}) return false;", e, var->second);
678 cover_vars_[n] = var;
680 owner_ =
u8(std::ranges::find(shape_.covers, n) - shape_.covers.begin() + 1);
685void Code::match_app(
u32 n,
const std::string& e,
bool spine) {
686 const auto& x = node(n);
687 auto app =
fresh(
'd');
688 line(
"auto {} = {}->isa<App>();", app, e);
689 line(
"if (!{}) return false;", app);
690 match(x.ops[0], app +
"->callee()", spine);
691 if (in_type_ || !(x.val & Commutes))
return match(x.ops[1], app +
"->arg()");
692 auto arg = name(app +
"->arg()");
693 auto bit = shape_.swaps.size();
694 auto&
t = node(x.ops[1]);
695 shape_.swaps.emplace_back(
t.ops[0],
t.ops[1]);
696 line(
"if (Lit::isa({}->arity()) != 2) return false;", arg);
697 match(
t.ops[0], std::format(
"{}->proj(2, swap >> {} & 1)", arg, bit));
698 match(
t.ops[1], std::format(
"{}->proj(2, ~swap >> {} & 1)", arg, bit));
701void Code::match(
u32 n,
const std::string& e,
bool spine) {
702 const auto& x = node(n);
706 if (!in_type_) shape_.uses.emplace_back(rules::Use{owner_,
u8(i),
false});
708 line(
"if (m[{}] != {}) return false;", i, e);
712 line(
"m[{}] = {};", i, e);
713 auto outer = std::exchange(in_type_,
true);
714 match(types_[i], std::format(
"m[{}]->type()", i));
721 line(
"if (!{0}->isa<Axm>() || {0}->flags() != {1:#x}) return false; // {2}", d, x.val, comment(n));
726 line(
"auto {} = {}->isa<Lit>();", lit, e);
727 line(
"if (!{0} || {0}->get() != {1:#x}) return false;", lit, x.val);
728 auto outer = std::exchange(in_type_,
true);
729 match(x.ops[0], lit +
"->type()");
733 case Kind::Nat: line(
"if (!{}->isa<Nat>()) return false;", e);
return;
734 case Kind::Idx: line(
"if (!{}->isa<Idx>()) return false;", e);
return;
736 if (!inner(n))
return match_app(n, e, spine);
738 if (!cover_vars_.contains(n)) ref(n, d, Ref::Value);
739 return match_inner(n, d);
741 case Kind::Extract: {
742 auto tuple = x.ops[0];
743 if (!inner(tuple))
return match2(n, e,
"isa<Extract>()",
"tuple",
"index");
744 auto ex =
fresh(
'd');
745 line(
"auto {} = {}->isa<Extract>();", ex, e);
746 line(
"if (!{}) return false;", ex);
747 ref(tuple, ex, x.val & Mem ? Ref::Mem : Ref::Value);
748 match_inner(tuple, ex +
"->tuple()");
749 match(x.ops[1], ex +
"->index()");
752 case Kind::Pack:
return match2(n, e,
"isa_imm<Pack>()",
"arity",
"body");
753 case Kind::Arr:
return match2(n, e,
"isa_imm<Arr>()",
"arity",
"body");
754 case Kind::Pi:
return match2(n, e,
"isa_imm<Pi>()",
"dom",
"codom");
755 case Kind::Bot: line(
"if (!{}->isa<Bot>()) return false;", e);
return;
757 auto sigma =
fresh(
'd');
758 line(
"auto {} = {}->isa_imm<Sigma>();", sigma, e);
759 line(
"if (!{0} || {0}->num_ops() != {1}) return false;", sigma, x.ops.size());
760 for (
size_t j = 0; j != x.ops.size(); ++j)
761 match(x.ops[j], std::format(
"{}->op({})", sigma, j));
767 line(
"if (Lit::isa({}->arity()) != {}) return false;", d, x.ops.size());
768 for (
size_t j = 0; j != x.ops.size(); ++j)
769 match(x.ops[j], std::format(
"{}->proj({}, {})", d, x.ops.size(), j));
776void Code::build(
u32 rhs) {
779 std::println(os_,
"inline const Def* build_{}([[maybe_unused]] World& w, [[maybe_unused]] const Def* const* h) {{",
781 line(
"return {};", build_(rhs));
782 std::println(os_,
"}}");
786std::string Code::build_(
u32 n) {
787 if (
auto i = built_.find(n); i != built_.end())
return i->second;
788 const auto& x = node(n);
789 if (x.kind == Kind::Hole)
return built_[n] = std::format(
"h[{}]", x.val);
792 const auto& callee = node(x.kind == Kind::App ? x.ops[0] : n);
793 if (x.kind == Kind::App && callee.kind == Kind::App && callee.val & Implicit) {
794 auto f = build_(callee.ops[0]);
795 auto a = build_(x.ops[1]);
796 auto res =
fresh(
'b');
797 line(
"auto {} = w.implicit_app({}, {});", res, f, a);
798 return built_[n] = res;
801 auto ops = std::vector<std::string>();
802 for (
auto op : x.ops)
803 ops.emplace_back(build_(op));
804 auto res =
fresh(
'b');
806 case Kind::Axm: line(
"auto {} = w.annex({:#x}); // {}", res, x.val, comment(n));
break;
807 case Kind::Lit: line(
"auto {} = w.lit({}, {:#x});", res, ops[0], x.val);
break;
808 case Kind::Nat: line(
"auto {} = w.type_nat();", res);
break;
809 case Kind::Idx: line(
"auto {} = w.type_idx();", res);
break;
810 case Kind::App: line(
"auto {} = w.app({}, {});", res, ops[0], ops[1]);
break;
811 case Kind::Extract: line(
"auto {} = w.extract({}, {});", res, ops[0], ops[1]);
break;
812 case Kind::Pack: line(
"auto {} = w.pack({}, {});", res, ops[0], ops[1]);
break;
813 case Kind::Arr: line(
"auto {} = w.arr({}, {});", res, ops[0], ops[1]);
break;
814 case Kind::Tuple: line(
"auto {} = w.tuple({{{}}});", res, fe::Join(ops,
", "));
break;
815 case Kind::Sigma: line(
"auto {} = w.sigma({{{}}});", res, fe::Join(ops,
", "));
break;
816 case Kind::Pi: line(
"auto {} = w.pi({}, {}, {});", res, ops[0], ops[1], x.val != 0);
break;
817 case Kind::Bot: line(
"auto {} = w.bot(w.type());", res);
break;
818 case Kind::Hole: std::unreachable();
820 return built_[n] = res;
825 size_t operator()(
const std::vector<u32>& v)
const noexcept {
828 h = fe::hash_combine(h, x);
835std::string sig(
const Table& t,
u32 n,
const std::vector<Table::Meta>& metas,
bool reg);
837void Table::check(
const std::vector<Shape>& shapes,
const std::vector<size_t>& ids)
const {
838 auto chains = rules::Chains(convs_);
839 auto atomic = ankerl::unordered_dense::set<flags_t>();
840 for (
size_t i = 0, e = rewrites_.size(); i != e; ++i) {
841 const auto&
r = rewrites_[i];
842 if (
chains.
conv(
r.type, rules::reg_want(
r.type)) == rules::Inf)
843 fe::throwf(
"{}: rule `{}` yields a value that does not convert to a register", gen_.
isel(),
r.name);
844 for (
auto m :
r.metas)
845 if (!rules::is_param(m.want) && !rules::is_literal(m.want) && !
chains.
reachable(m.want))
846 fe::throwf(
"{}: no rule type converts to a hole of `{}`", gen_.
isel(),
r.name);
847 auto total = [&](
Meta m) {
return rules::is_param(m.want) ||
chains.
total(m.want); };
848 if (shapes[ids[i]].covers.empty() && std::ranges::all_of(
r.metas, total)) atomic.emplace(
r.root);
850 for (
const auto& r : rewrites_)
851 if (!atomic.contains(
r.root)) fe::throwf(
"{}: no atomic rule shares the root of `{}`", gen_.
isel(),
r.name);
854void Table::dump(std::ostream& os)
const {
855 std::println(os,
"// Generated by `{}.gen`; do not edit.", gen_.
isel());
856 std::println(os,
"#pragma once");
858 std::println(os,
"#include <mim/world.h>");
860 std::println(os,
"#include <mim/plug/mach/rule_table.h>");
862 std::println(os,
"#include \"mim/plug/{0}/{0}.h\"", gen_.
backend());
864 std::println(os,
"namespace mim::plug::{}::rules {{", gen_.
backend());
866 std::println(os,
"using namespace mim::plug::mach::rules;");
869 auto code = Code(os, *
this);
870 auto matchers = ankerl::unordered_dense::map<std::vector<u32>, size_t, LhsHash>();
871 auto shapes = std::vector<Shape>();
872 auto ids = std::vector<size_t>();
873 for (
const auto& r : rewrites_) {
874 auto types = std::vector<u32>{
r.lhs};
875 for (
auto m :
r.metas)
876 types.emplace_back(m.type);
878 if (fresh) shapes.emplace_back(code.match(i->second,
r.lhs, std::span(types).subspan(1)));
879 ids.emplace_back(i->second);
883 auto built = ankerl::unordered_dense::set<u32>();
884 for (
const auto& r : rewrites_)
885 if (built.emplace(
r.rhs).second) code.build(
r.rhs);
886 for (
const auto& c : convs_)
887 if (built.emplace(
c.rhs).second) code.build(
c.rhs);
889 std::println(os,
"// clang-format off");
890 std::println(os,
"inline constexpr Want wants[] = {{");
891 size_t num_wants = 0;
892 for (
const auto& r : rewrites_) {
893 if (
r.metas.empty())
continue;
895 for (
auto m :
r.metas)
896 std::print(os,
" Want::{},", name(m.want));
897 std::println(os,
" // {}: {}",
r.name,
r.rho);
898 num_wants +=
r.metas.size();
901 if (num_wants == 0) std::println(os,
" Want::Param,");
902 std::println(os,
"}};");
905 constexpr std::string_view refs[] = {
"Value",
"Mem"};
906 std::println(os,
"inline constexpr Use all_uses[] = {{");
907 std::println(os,
" {{0, 0, false}},");
908 for (
const auto& s : shapes)
909 for (
auto u :
s.uses)
910 std::println(os,
" {{{}, {}, {}}},",
u.owner,
u.index,
u.ref);
911 std::println(os,
"}};");
913 std::println(os,
"inline constexpr RefInfo all_refs[] = {{");
914 std::println(os,
" {{0, Ref::Value}},");
915 for (
const auto& s : shapes)
916 for (
auto r :
s.refs)
917 std::println(os,
" {{{}, Ref::{}}},",
r.cover, refs[
size_t(
r.kind)]);
918 std::println(os,
"}};");
920 auto max = [&](
auto f) {
return std::ranges::max(shapes | std::views::transform(f)); };
921 std::println(os,
"inline constexpr size_t Max_Refs = {};", max([](
const Shape& s) {
return s.refs.size(); }));
922 std::println(os,
"inline constexpr size_t Max_Covers = {};", max([](
const Shape& s) {
return s.covers.size(); }));
923 std::println(os,
"inline constexpr size_t Max_Metas = {};",
924 std::ranges::max(rewrites_ | std::views::transform([](
const Rewrite& r) {
return r.metas.size(); })));
926 std::println(os,
"inline constexpr Matcher matchers[] = {{");
927 size_t num_uses = 1, num_refs = 1;
928 for (
size_t i = 0; i != shapes.size(); ++i) {
929 const auto&
s = shapes[i];
930 std::println(os,
" {{&match_{}, {}, {}, {}, {}, {}}},", i, num_uses,
s.uses.size(), num_refs,
s.refs.size(),
932 num_uses +=
s.uses.size();
933 num_refs +=
s.refs.size();
935 std::println(os,
"}};");
938 std::println(os,
"inline constexpr Rewrite rewrites[] = {{");
940 for (
size_t i = 0, e = rewrites_.size(); i != e; ++i) {
941 const auto&
r = rewrites_[i];
942 const auto&
s = shapes[ids[i]];
943 u32 swaps = 0, reg_swaps = 0;
944 for (
size_t b = 0;
b !=
s.swaps.size(); ++
b) {
945 auto [x, y] =
s.swaps[
b];
946 if (sig(*
this, x,
r.metas,
false) != sig(*
this, y,
r.metas,
false)) swaps |= 1u <<
b;
947 if (sig(*
this, x,
r.metas,
true) != sig(*
this, y,
r.metas,
true)) reg_swaps |= 1u <<
b;
950 if (
r.mapped !=
u32(-1)) {
951 auto k = std::ranges::find(
s.covers, nodes_[
r.mapped].ops[0]) -
s.covers.begin();
952 if (
size_t(k) ==
s.covers.size())
953 fe::throwf(
"{}: `{}` maps the memory of no inner node", gen_.
isel(),
r.name);
957 os,
" {{\"{}\", {}, {:#x}, Ty::{}, &matchers[{}], &build_{}, {}, {}, {:#x}, {:#x}, {:#x}, {}}}, // {}",
958 r.name,
r.cost,
r.root, name(
r.type), ids[i],
r.rhs, first,
r.metas.size(), swaps, swaps & ~reg_swaps,
959 r.tied, maps,
r.rho);
962 std::println(os,
"}};");
964 std::println(os,
"inline constexpr Root roots[] = {{");
965 for (
size_t i = 0, e = rewrites_.size(); i != e;) {
967 while (j != e && rewrites_[j].root == rewrites_[i].root)
969 std::println(os,
" {{{:#x}, {}, {}}},", rewrites_[i].root, i, j - i);
972 std::println(os,
"}};");
975 if (convs_.empty()) fe::throwf(
"{}: there is no conversion", gen_.
isel());
976 std::println(os,
"inline constexpr Conversion conversions[] = {{");
977 for (
const auto& c : convs_)
978 std::println(os,
" {{\"{}\", {}, Ty::{}, Ty::{}, {}, &build_{}}}, // {}",
c.name,
c.cost, name(
c.from),
979 name(
c.to),
c.arity,
c.rhs,
c.rho);
980 std::println(os,
"}};");
982 std::println(os,
"inline constexpr Chains chains{{conversions}};");
984 os,
"inline constexpr Table table{{wants, all_uses, all_refs, matchers, rewrites, roots, conversions, chains,");
985 std::println(os,
" Max_Refs, Max_Covers, Max_Metas}};");
986 std::println(os,
"// clang-format on");
988 std::println(os,
"}} // namespace mim::plug::{}::rules", gen_.
backend());
991std::string sig(
const Table& t,
u32 n,
const std::vector<Table::Meta>& metas,
bool reg) {
992 const auto& x =
t.nodes_[n];
993 if (x.kind == Kind::Hole) {
994 auto w = metas[x.val].want;
996 return std::format(
"{}:{}", name(w), sig(t, metas[x.val].type, metas, reg));
998 auto res = std::format(
"{}.{}(",
size_t(x.kind), x.val);
999 for (
auto op : x.ops)
1000 res += sig(t, op, metas, reg) +
",";
1007 auto& lib = *gen.driver().library();
1008 auto flags = std::vector<flags_t>();
1009 for (
const auto& [f, _] : lib.annexes())
1011 std::ranges::sort(flags);
1013 auto& w = gen.world();
1014 auto table = Table(gen);
1015 table.commutes(w.annex(gen.annexes().commutes));
1016 table.universes(w.annex(gen.annexes().formats), w.annex(gen.annexes().sizes));
1017 for (
auto f : flags)
1018 table.collect(w.annex(f));
1021 auto out =
Out(std::string(
arg_value(gen.args(),
"o",
"output").value_or(
"-")));
1022 table.dump(*out.os());
static auto isa(const Def *def)
static std::tuple< const Axm *, u8, u8 > get(const Def *def)
Yields currying counter of 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.
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.
nat_t num_projs() const
Yields Def::arity(), if it is a Lit, or 1 otherwise.
const Var * has_var()
Only returns not nullptr, if Var of this mutable has ever been created.
static std::optional< T > isa(const Def *def)
Writes the closed rules among the annexes of a backend's isel plugin as the C++ matchers and builders...
virtual std::optional< mach::rules::Want > classify(const Def *) const
What an operand of the backend's address type type is: Want::Base, Want::Index, or Want::Addr.
std::string_view backend() const
flags_t lit
The guard lit x: a literal.
virtual std::optional< size_t > tied(const App *) const
The operand whose register the result of the two-address instruction insn takes.
flags_t zx
zx x: Want::Zx of a meta variable, else the non-terminal Zx of a rhs or conversion.
std::string_view isel() const
plugin_t backend_id() const
virtual u32 cost(const App *insn) const =0
flags_t imm
The guard imm x: Want::Imm.
const Annexes & annexes() const
u32 cost(const App *app)
The cost of the instruction app: its latency plus one, so of two equally fast covers the shorter wins...
constexpr Matcher matchers[]
Ref
How the lhs refers to one of its inner nodes.
@ 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,...
void mim_mach_gen(Gen &)
Gen::start, compiled once into libmim_mach; Gen reaches it via GET_FUN_PTR.
std::optional< size_t > tied(flags_t base)
The operand whose register the result of a two-address instruction base takes.
GIDMap< const Def *, To > DefMap
fe::Vector< const Def * > DefVec
GIDSet< const Def * > DefSet
@ Meta
Meta rules for universe and Type levels.
std::optional< std::string_view > arg_value(fe::View< std::string > args, Keys... keys)
#define MIM_MACH_RULE_WANTS(X)
#define MIM_MACH_RULE_TYS(X)
static constexpr plugin_t flags2plugin(flags_t f)
static consteval flags_t base()
constexpr u32 conv(Ty from, Want want) const
Cost of converting a replacement or operand of non-terminal from into a hole of type want.
constexpr bool reachable(Want w) const
Does some non-terminal of the register class of a rule convert into a hole of type w?
constexpr bool total(Want w) const
Does every non-terminal of w's register class convert into a hole of type w, as an atomic rule's hole...