MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
liveness.cpp
Go to the documentation of this file.
2
3#include <deque>
4#include <ranges>
5
6#include <mim/tuple.h>
7#include <mim/world.h>
8
9namespace mim::plug::mach {
10
11Liveness::Liveness(const FunPhase& phase, Lam* fun, bool solve)
12 : target_(&phase.target()) {
13 if (!fun->is_closed()) fun->blame("{} backend: `{}` is no closed function", target_->name(), fun).bail();
14 auto reach = LamSet{fun};
15 for (auto todo = fe::Vector<Lam*>{fun}; !todo.empty();) {
16 auto lam = todo.back();
17 auto term = lam->body()->isa<App>();
18 todo.pop_back();
19 if (!term) lam->blame("{} backend: `{}` does not end in a jump", target_->name(), lam).bail();
20 for_each_succ(term, [&](Lam* bb) {
21 if ((bb == fun || !bb->is_closed()) && reach.emplace(bb).second) todo.emplace_back(bb);
22 });
23 }
24 nest_ = std::make_unique<Nest>(fun, Nest::Place::Late);
25 order(nest()[fun], reach, npos);
26 assert(blocks_.size() == reach.size());
27 for (size_t i = 0; i != blocks_.size(); ++i)
28 chain(i, fun);
29 for (auto& block : blocks_)
30 values(block);
31
32 // A block with live-ins comes after the one block that jumps to it, so one backward pass is exact.
33 for (bool todo = true; todo; todo &= solve) {
34 todo = false;
35 for (size_t i = blocks_.size(); i-- != 0;)
36 todo |= flow(blocks_[i]);
37 }
38 if (!solve)
39 for (const auto& block : blocks_)
40 for (auto s : block.targets)
41 for (auto v : blocks_[s].live_in)
42 if (!block.live_out.contains(v))
43 blocks_[s]
44 .lam->blame("{} backend: `{}` is not closed over `{}`", target_->name(), blocks_[s].lam, v)
45 .bail();
46
47 for (auto& block : blocks_)
48 sweep(block);
49}
50
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);
55 block.node = node;
56 block.parent = std::exchange(parent, blocks_.size() - 1);
57 }
58 for (const auto& scc : node->topo())
59 for (auto n : sorted(*scc))
60 order(n, reach, parent);
61}
62
63void Liveness::chain(size_t b, Lam* fun) {
64 auto lam = blocks_[b].lam;
65 auto term = lam->body()->as<App>();
66
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();
71
72 auto insns = fe::Vector<const App*>();
73 for (auto m = end; !(m->isa<Extract>() && m->as<Extract>()->tuple() == lam->var()) && m != lam->var();) {
74 auto node = m->isa<Extract>() ? m->as<Extract>()->tuple() : m;
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);
79 m = prev;
80 }
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);
85
86 for_each_succ(term, [&](Lam* bb) {
87 if (bb == fun || !bb->is_closed()) blocks_[b].targets.emplace_back(lam2block_[bb]);
88 });
89}
90
91bool Liveness::local(const Def* def) const {
92 auto root = def;
93 while (auto ex = root->isa<Extract>()) {
94 if (!Lit::isa(ex->index())) break;
95 root = ex->tuple();
96 }
97 auto var = root->isa<Var>();
98 return var ? lam2block_.contains(var->binder()->isa<Lam>()) : insn2block_.contains(root);
99}
100
101void Liveness::values(const Def* def, DefVec& res, DefSet& done) const {
102 if (def->isa_mut() || !done.emplace(def).second) return;
103
104 if (local(def)) {
105 if (target_->is_mem(def) || def->type()->isa<Pi>()) return;
106 if (auto n = def->num_projs(); n == 1)
107 res.emplace_back(def);
108 else
109 for (size_t i = 0; i != n; ++i)
110 values(def->proj(n, i), res, done);
111 } else {
112 for (auto op : def->ops())
113 values(op, res, done);
114 }
115}
116
117void Liveness::values(Block& block) {
118 auto run = [this](auto... defs) {
119 auto res = DefVec();
120 auto done = DefSet();
121 (values(defs, res, done), ...);
122 return res;
123 };
124
125 block.params = run(block.lam->var());
126 for (auto insn : block.insns) {
127 block.defs.emplace_back(run(insn));
128 block.uses.emplace_back(run(insn->callee(), insn->arg()));
129 }
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)
133 block.term_uses = run(cc->arg());
134 else
135 block.term_uses = run(term);
136}
137
138bool Liveness::flow(Block& block) {
139 auto live = DefSet();
140 for (auto s : block.targets)
141 live.insert(blocks_[s].live_in.begin(), blocks_[s].live_in.end());
142 block.live_out = live;
143 live.insert(block.term_uses.begin(), block.term_uses.end());
144 for (size_t i = block.insns.size(); i-- != 0;) {
145 for (auto d : block.defs[i])
146 live.erase(d);
147 live.insert(block.uses[i].begin(), block.uses[i].end());
148 }
149 for (auto x : block.params)
150 live.erase(x);
151 if (live.size() == block.live_in.size()) return false;
152 block.live_in = std::move(live);
153 return true;
154}
155
156void Liveness::sweep(Block& block) {
157 auto live = block.live_out;
158 auto count = Pressure{};
159 for (auto value : live)
160 ++count[target_->cls(value)];
161
162 auto gen = [&](const DefVec& values) {
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]);
167 };
168 auto kill = [&](const DefVec& values) {
169 for (auto value : values)
170 if (live.erase(value)) --count[target_->cls(value)];
171 };
172
173 gen(block.term_uses);
174 for (size_t i = block.insns.size(); i-- != 0;) {
175 const auto& ds = block.defs[i];
176 // A dead result occupies a register nonetheless, unless it is a condition that only a branch consumes.
177 if (!target_->is_sched_cc(block.insns[i])) gen(ds);
178 kill(ds);
179 gen(block.uses[i]);
180 }
181}
182
183namespace {
184
185/// The block that @p block should fall through to; @p ret is the return continuation of its function.
186Lam* fall_through(const Liveness::Block& block, const Def* ret) {
187 auto term = block.lam->body()->as<App>();
188 auto callee = term->callee();
189 if (callee == ret) return nullptr;
190 if (Lam::isa_mut_returning(callee)) {
191 auto k = term->arg(term->num_args(), term->num_args() - 1);
192 return k == ret ? nullptr : Lam::isa_mut_basicblock(k);
193 }
194 if (auto select = Select(callee)) return Lam::isa_mut_basicblock(select.ff());
195 return Lam::isa_mut_basicblock(callee);
196}
197
198} // namespace
199
200fe::Vector<const Liveness::Block*> layout(const Liveness& live, const LamMap<Lam*>& forward) {
201 auto ret = live.blocks().front().lam->ret_var();
202 auto order = fe::Vector<const Liveness::Block*>();
203 auto placed = LamSet();
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;
212 }
213 }
214 return order;
215}
216
217fe::Vector<ArgLoc> arg_locs(const Target& target, const Def* arg, size_t n, size_t num, const ParamRegs* conv) {
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) {
222 auto x = Target::strip(arg->proj(n, i));
223 if (target.is_mem(x)) continue;
224 if (conv)
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]++);
228 else
229 res[i].stack = stack++;
230 }
231 return res;
232}
233
234ParamRegs param_regs(const Target& target, Lam* fun, const DefMap<size_t>& regs) {
235 auto n = fun->num_vars();
236 auto res = ParamRegs(num_params(fun));
237 auto taken = std::array<fe::Vector<bool>, Target::Num_Classes>{};
238 for (size_t c = 0; c != Target::Num_Classes; ++c)
239 taken[c].resize(target.num_regs(Target::Class(c)));
240
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)) {
245 if (auto cls = target.cls(x); target.caller_saved(cls, *r))
246 res[i] = *r, taken[cls][*r] = true;
247 else
248 moved.emplace_back(i);
249 }
250 }
251 for (auto i : moved) {
252 auto cls = target.cls(fun->var(n, i));
253 auto& t = taken[cls];
254 auto r = size_t(0);
255 while (r != t.size() && (t[r] || !target.caller_saved(cls, r) || target.reserved(cls, r)))
256 ++r;
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;
259 }
260 return res;
261}
262
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());
268 lam->unset()->set(filter, body);
269 }
270}
271
272const Def* Assign::rewrite(const Def* def) {
273 auto& w = world();
274 if (def->isa_mut() || def->is_closed()) return def;
275 if (live_.target().is_in(def)) {
276 auto app = def->as<App>();
277 return w.app(rewrite(app->callee()), raw(app->arg()));
278 }
279 if (live_.local(def)) {
280 if (auto r = fe::lookup(regs_, def)) return live_.target().in(live_.target().cls(def), *r, raw(def));
281 // A tuple of values, e.g. the whole variable of a block or an instruction, is used through its projections.
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;
284 })) {
285 auto ops = DefVec();
286 for (auto d : projs)
287 ops.emplace_back(rewrite(d));
288 return w.tuple(ops);
289 }
290 return raw(def);
291 }
292 return Rewriter::rewrite(def);
293}
294
295const Def* Assign::raw(const Def* def) {
296 if (auto ex = def->isa<Extract>()) return world().extract(raw(ex->tuple()), ex->index());
297 if (def->isa<Var>()) return def;
298 return Rewriter::rewrite(def);
299}
300
301} // namespace mim::plug::mach
Base class for all Defs.
Definition def.h:285
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.
Definition def.cpp:659
Def * set(size_t i, const Def *)
Successively set from left to right.
Definition def.cpp:188
constexpr auto ops() const noexcept
Definition def.h:370
T * isa_mut() const
If this is mutable, it will cast constness away and perform a dynamic_cast to T.
Definition def.h:584
const Def * var(nat_t a, nat_t i) noexcept
Definition def.h:488
nat_t num_vars() noexcept
Definition def.h:488
auto projs(Projector auto f) const
Splits this Def via Def::projections into an Array (if A == std::dynamic_extent) or std::array (other...
Definition def.h:453
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
nat_t num_projs() const
Yields Def::arity(), if it is a Lit, or 1 otherwise.
Definition def.h:1137
Def * unset()
Unsets all Def::ops; works even, if not set at all or only partially set.
Definition def.cpp:205
bool is_closed() const
Same as !has_free_vars().
Definition def.cpp:358
Extracts from a Sigma or Array-typed Extract::tuple the element at position Extract::index.
Definition tuple.h:360
const Def * tuple() const
Definition tuple.h:370
A function.
Definition lam.h:91
static Lam * isa_mut_basicblock(const Def *d)
Definition lam.h:130
static Lam * isa_mut_returning(const Def *d)
Definition lam.h:129
static std::optional< T > isa(const Def *def)
Definition def.h:974
Def * mut() const
The mutable capsulated in this Node or nullptr, if it's a virtual root comprising several Nodes.
Definition nest.h:39
const auto & topo() const
The SCCs of the children() in topological order: an SCC comes before the ones it depends on.
Definition nest.h:142
A dependent function type.
Definition lam.h:14
Recurseivly rebuilds part of a program into the provided World w.r.t. Rewriter::map.
Definition rewrite.h:21
World & world()
Definition rewrite.h:33
virtual const Def * rewrite(const Def *)
Definition rewrite.cpp:62
Select(const Def *)
Definition tuple.cpp:92
std::string_view name() const
The plugin name, used as the prefix of diagnostics.
Definition target.h:18
A variable introduced by a binder (mutable).
Definition def.h:855
const Def * extract(const Def *d, const Def *i)
Definition world.cpp:634
const Def * rewrite(const Def *) final
Definition liveness.cpp:272
Visits the closed Cns with a body of a scheduled World for one Target, each before the ones that call...
Definition phase.h:55
Liveness of the values of one scheduled function, as a side table.
Definition liveness.h:35
const Block * block(Lam *lam) const
Definition liveness.h:64
const Nest::Node * node
Its Node in nest().
Definition liveness.h:47
size_t parent
The block it is nested in, or npos for the entry.
Definition liveness.h:48
static constexpr size_t npos
Definition liveness.h:53
fe::Vector< size_t > targets
The blocks its terminator jumps to.
Definition liveness.h:46
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?
Definition liveness.cpp:91
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...
Definition liveness.cpp:11
std::array< size_t, Num_Classes > Pressure
Definition liveness.h:39
const Target & target() const
Definition liveness.h:69
const Nest & nest() const
The late Nest of the function as it is now.
Definition liveness.h:60
const DefVec & defs(const App *insn) const
Definition liveness.h:73
The machine facts of a native backend that the phases of mach need.
Definition target.h:45
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.
Definition target.h:195
static bool is_mem(const Def *def)
Definition target.h:205
const Def * prev_mem(const App *app) const
The memory app continues, if app is an instruction on a mem.M 0 chain.
Definition target.h:210
Class
The register classes; Stack values live in a spill slot and are unbounded.
Definition target.h:48
virtual bool reserved(Class cls, size_t r) const =0
Is r never available to register allocation?
Class cls(const Def *def) const
Definition target.h:105
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.
The mach Plugin
Definition asm.h:15
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.
Definition target.h:40
size_t num_params(Lam *lam)
The parameters of lam without its return continuation.
Definition liveness.h:145
fe::Vector< const Nest::Node * > sorted(const Nest::Node::SCC &scc)
The Nodes of scc in a deterministic order.
Definition phase.h:24
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...
Definition liveness.h:18
Lam * forwarded(const LamMap< Lam * > &forward, Lam *lam)
Where a jump to lam goes once the blocks that forward skips are skipped.
Definition liveness.h:103
void rewrite_blocks(const Liveness &live, Rewriter &rw)
Rewrites the filter and body of each block of live in place.
Definition liveness.cpp:263
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,...
Definition liveness.cpp:200
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.
Definition liveness.cpp:217
ParamRegs param_regs(const Target &target, Lam *fun, const DefMap< size_t > &regs)
Where the known() function fun receives its parameters, given the registers regs that Color assigned ...
Definition liveness.cpp:234
GIDSet< Lam * > LamSet
Definition lam.h:211
GIDMap< const Def *, To > DefMap
Definition def.h:91
GIDMap< Lam *, To > LamMap
Definition lam.h:210
fe::Vector< const Def * > DefVec
Definition def.h:96
GIDSet< const Def * > DefSet
Definition def.h:92
@ Lam
Definition def.h:123
@ Extract
Definition def.h:123
@ App
Definition def.h:123