12 : target_(&phase.
target()) {
13 if (!fun->
is_closed()) fun->
blame(
"{} backend: `{}` is no closed function", target_->name(), fun).bail();
15 for (
auto todo = fe::Vector<Lam*>{fun}; !todo.empty();) {
16 auto lam = todo.back();
17 auto term = lam->body()->isa<
App>();
19 if (!term) lam->
blame(
"{} backend: `{}` does not end in a jump", target_->name(), lam).bail();
21 if ((bb == fun || !bb->
is_closed()) && reach.emplace(bb).second) todo.emplace_back(bb);
26 assert(blocks_.size() == reach.size());
27 for (
size_t i = 0; i != blocks_.size(); ++i)
29 for (
auto&
block : blocks_)
33 for (
bool todo =
true; todo; todo &= solve) {
35 for (
size_t i = blocks_.size(); i-- != 0;)
36 todo |= flow(blocks_[i]);
39 for (
const auto&
block : blocks_)
41 for (
auto v : blocks_[s].live_in)
44 .lam->blame(
"{} backend: `{}` is not closed over `{}`", target_->name(), blocks_[s].lam, v)
47 for (
auto&
block : blocks_)
51void Liveness::order(
const Nest::Node* node,
const LamSet& reach,
size_t parent) {
52 if (
auto lam = node->
mut()->isa<
Lam>(); lam && reach.contains(lam)) {
53 lam2block_.emplace(lam, blocks_.size());
54 auto&
block = blocks_.emplace_back(lam);
56 block.
parent = std::exchange(parent, blocks_.size() - 1);
58 for (
const auto& scc : node->
topo())
59 for (
auto n :
sorted(*scc))
60 order(n, reach, parent);
63void Liveness::chain(
size_t b,
Lam* fun) {
64 auto lam = blocks_[b].lam;
65 auto term = lam->body()->as<
App>();
67 const Def* end =
nullptr;
68 for (
auto arg : term->args())
69 if (target_->
is_mem(arg)) end = arg;
70 if (!end) lam->
blame(
"{} backend: `{}` has no `mem.M` chain", target_->
name(), lam).bail();
72 auto insns = fe::Vector<const App*>();
75 auto app = node->isa<
App>();
76 auto prev = app ? target_->
prev_mem(app) :
nullptr;
77 if (!prev) m->
blame(
"{} backend: unexpected memory `{}` in `{}`", target_->
name(), m, lam).bail();
78 insns.emplace_back(app);
81 std::ranges::reverse(insns);
82 for (
size_t i = 0; i != insns.size(); ++i)
83 insn2block_.emplace(insns[i], std::pair(b, i));
84 blocks_[b].insns = std::move(insns);
87 if (bb == fun || !bb->is_closed()) blocks_[b].targets.emplace_back(lam2block_[bb]);
93 while (
auto ex = root->isa<
Extract>()) {
97 auto var = root->isa<
Var>();
98 return var ? lam2block_.contains(var->binder()->isa<
Lam>()) : insn2block_.contains(root);
101void Liveness::values(
const Def* def,
DefVec& res,
DefSet& done)
const {
102 if (def->
isa_mut() || !done.emplace(def).second)
return;
105 if (target_->
is_mem(def) || def->
type()->isa<
Pi>())
return;
107 res.emplace_back(def);
109 for (
size_t i = 0; i != n; ++i)
110 values(def->
proj(n, i), res, done);
112 for (
auto op : def->
ops())
113 values(op, res, done);
117void Liveness::values(Block& block) {
118 auto run = [
this](
auto...
defs) {
121 (values(
defs, res, done), ...);
126 for (
auto insn :
block.insns) {
128 block.uses.emplace_back(
run(insn->callee(), insn->arg()));
130 auto term =
block.lam->body()->as<
App>();
131 auto ex = term->callee()->isa<
Extract>();
132 if (
auto cc = ex ? target_->isa_sched_cc(ex->index()) :
nullptr)
138bool Liveness::flow(Block& block) {
140 for (
auto s :
block.targets)
141 live.insert(blocks_[s].live_in.begin(), blocks_[s].live_in.end());
144 for (
size_t i =
block.insns.size(); i-- != 0;) {
145 for (
auto d :
block.defs[i])
149 for (
auto x :
block.params)
151 if (
live.size() ==
block.live_in.size())
return false;
156void Liveness::sweep(Block& block) {
159 for (
auto value :
live)
160 ++count[target_->cls(value)];
163 for (
auto value : values)
164 if (
live.emplace(value).second) ++count[target_->cls(value)];
165 for (
size_t c = 0;
c != Num_Classes; ++
c)
166 block.max_live[c] = std::max(
block.max_live[c], count[c]);
168 auto kill = [&](
const DefVec& values) {
169 for (
auto value : values)
170 if (
live.erase(value)) --count[target_->cls(value)];
174 for (
size_t i =
block.insns.size(); i-- != 0;) {
175 const auto& ds =
block.defs[i];
177 if (!target_->is_sched_cc(
block.insns[i]))
gen(ds);
187 auto term =
block.lam->body()->as<
App>();
188 auto callee = term->callee();
189 if (callee == ret)
return nullptr;
191 auto k = term->arg(term->num_args(), term->num_args() - 1);
201 auto ret =
live.blocks().front().lam->ret_var();
202 auto order = fe::Vector<const Liveness::Block*>();
204 for (
auto queue = std::deque<Lam*>{
live.blocks().front().lam}; !queue.empty(); queue.pop_front()) {
205 for (
auto lam = queue.front(); lam && placed.emplace(lam).second;) {
206 auto b =
live.block(lam);
207 order.emplace_back(b);
208 for (
auto s : b->targets)
209 queue.emplace_back(
forwarded(forward,
live.blocks()[s].lam));
210 lam = fall_through(*b, ret);
211 if (lam) lam =
live.block(lam) ?
forwarded(forward, lam) :
nullptr;
218 auto res = fe::Vector<ArgLoc>(num);
219 auto regs = std::array<size_t, Target::Num_Classes>{};
220 auto stack = size_t(0);
221 for (
size_t i = 0; i != num; ++i) {
223 if (target.
is_mem(x))
continue;
225 res[i].reg = (*conv)[i];
226 else if (
auto cls = target.
cls(x); regs[cls] != target.
num_arg_regs(cls))
227 res[i].reg = target.
arg_reg(cls, regs[cls]++);
229 res[i].stack = stack++;
241 auto moved = fe::Vector<size_t>();
242 for (
size_t i = 0; i != res.size(); ++i) {
243 auto x = fun->
var(n, i);
244 if (
auto r = fe::lookup(regs, x); r && !target.
is_mem(x)) {
246 res[i] = *r, taken[cls][*r] =
true;
248 moved.emplace_back(i);
251 for (
auto i : moved) {
252 auto cls = target.
cls(fun->
var(n, i));
253 auto& t = taken[cls];
257 if (r == t.size()) fun->
blame(
"{} backend: too many arguments are not supported yet", target.
name()).bail();
258 res[i] = r, t[r] =
true;
264 for (
const auto& block :
live.blocks()) {
265 auto lam = block.lam;
266 auto filter = rw.
rewrite(lam->filter());
267 auto body = rw.
rewrite(lam->body());
275 if (live_.target().is_in(def)) {
276 auto app = def->as<
App>();
277 return w.app(
rewrite(app->callee()), raw(app->arg()));
279 if (live_.local(def)) {
280 if (
auto r = fe::lookup(regs_, def))
return live_.target().in(live_.target().cls(def), *r, raw(def));
282 if (
auto projs = def->
projs(); projs.size() > 1 && std::ranges::any_of(projs, [&](
const Def* d) {
283 return regs_.contains(d) || d->num_projs() > 1;
295const Def* Assign::raw(
const Def* def) {
297 if (def->isa<
Var>())
return 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.
constexpr auto ops() const noexcept
T * isa_mut() const
If this is mutable, it will cast constness away and perform a dynamic_cast to T.
const Def * var(nat_t a, nat_t i) noexcept
nat_t num_vars() noexcept
auto projs(Projector auto f) const
Splits this Def via Def::projections into an Array (if A == std::dynamic_extent) or std::array (other...
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.
nat_t num_projs() const
Yields Def::arity(), if it is a Lit, or 1 otherwise.
Def * unset()
Unsets all Def::ops; works even, if not set at all or only partially set.
bool is_closed() const
Same as !has_free_vars().
static Lam * isa_mut_basicblock(const Def *d)
static Lam * isa_mut_returning(const Def *d)
static std::optional< T > isa(const Def *def)
Def * mut() const
The mutable capsulated in this Node or nullptr, if it's a virtual root comprising several Nodes.
const auto & topo() const
The SCCs of the children() in topological order: an SCC comes before the ones it depends on.
A dependent function type.
Recurseivly rebuilds part of a program into the provided World w.r.t. Rewriter::map.
virtual const Def * rewrite(const Def *)
std::string_view name() const
The plugin name, used as the prefix of diagnostics.
A variable introduced by a binder (mutable).
const Def * extract(const Def *d, const Def *i)
const Def * rewrite(const Def *) final
Visits the closed Cns with a body of a scheduled World for one Target, each before the ones that call...
Liveness of the values of one scheduled function, as a side table.
const Block * block(Lam *lam) const
const Nest::Node * node
Its Node in nest().
size_t parent
The block it is nested in, or npos for the entry.
static constexpr size_t npos
fe::Vector< size_t > targets
The blocks its terminator jumps to.
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...
std::array< size_t, Num_Classes > Pressure
const Target & target() const
const Nest & nest() const
The late Nest of the function as it is now.
const DefVec & defs(const App *insn) const
The machine facts of a native backend that the phases of mach need.
virtual size_t num_regs(Class cls) const =0
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.
Class
The register classes; Stack values live in a spill slot and are unbounded.
virtual bool reserved(Class cls, size_t r) const =0
Is r never available to register allocation?
Class cls(const Def *def) const
virtual size_t num_arg_regs(Class cls) const =0
virtual bool caller_saved(Class cls, size_t r) const =0
virtual size_t arg_reg(Class cls, size_t i) const =0
The register of the i-th argument of class cls.
fe::Vector< std::optional< size_t > > ParamRegs
The register per parameter of a function with a convention of its own, or none if it is unused.
size_t num_params(Lam *lam)
The parameters of lam without its return continuation.
fe::Vector< const Nest::Node * > sorted(const Nest::Node::SCC &scc)
The Nodes of scc in a deterministic order.
void for_each_succ(const App *term, auto f)
Calls f for each block, possibly repeatedly, that the jump term passes control or a return continuati...
Lam * forwarded(const LamMap< Lam * > &forward, Lam *lam)
Where a jump to lam goes once the blocks that forward skips are skipped.
void rewrite_blocks(const Liveness &live, Rewriter &rw)
Rewrites the filter and body of each block of live in place.
fe::Vector< const Liveness::Block * > layout(const Liveness &live, const LamMap< Lam * > &forward={})
The blocks of live in emission order: each block is followed by the one it falls through to,...
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