MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
liveness.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <array>
5#include <memory>
6#include <ranges>
7
8#include <mim/def.h>
9#include <mim/lam.h>
10#include <mim/rewrite.h>
11
12#include "mim/plug/mach/phase.h"
14
15namespace mim::plug::mach {
16
17/// Calls @p f for each block, possibly repeatedly, that the jump @p term passes control or a return continuation to.
18inline void for_each_succ(const App* term, auto f) {
19 auto succ = [&](const Def* def) {
20 if (auto bb = Lam::isa_mut_basicblock(def); bb && bb->is_set()) f(bb);
21 };
22 succ(term->callee());
23 if (auto ex = term->callee()->isa<Extract>())
24 for (auto target : ex->tuple()->projs())
25 succ(target);
26 for (auto arg : term->args())
27 succ(arg);
28}
29
30/// Liveness of the values of one scheduled function, as a side table.
31/// A *value* is a non-memory result of an instruction on a `mem.M 0` chain or a non-memory parameter.
32/// A parameter is defined at the entry of its block and a jump uses its arguments, so a parameter is never live-in.
33/// A branch on a condition code uses its flags; the `Bool` is a value only if something else uses it.
34/// After `mach.close`, only a block nested in the one block that jumps to it has live-in values.
35class Liveness {
36public:
38 using enum Target::Class;
39 using Pressure = std::array<size_t, Num_Classes>;
40
41 struct Block {
43 fe::Vector<const App*> insns; ///< The `mem.M 0` chain in execution order.
44 fe::Vector<DefVec> defs, uses; ///< Per instruction.
46 fe::Vector<size_t> targets; ///< The blocks its terminator jumps to.
47 const Nest::Node* node; ///< Its Node in nest().
48 size_t parent; ///< The block it is nested in, or `npos` for the entry.
50 Pressure max_live = {}; ///< Maximum over all program points, per Class; Stack is unbounded.
51 };
52
53 static constexpr size_t npos = size_t(-1);
54
55 /// Bails unless the blocks of the function @p fun are closed; with @p solve, it iterates to the fixed point
56 /// instead.
57 Liveness(const FunPhase& phase, Lam* fun, bool solve = false);
58
59 /// The late Nest of the function as it is now.
60 const Nest& nest() const { return *nest_; }
61
62 /// In pre-order of the Nest with siblings in topological order, so a block comes after the block it is nested in.
63 const auto& blocks() const { return blocks_; }
64 const Block* block(Lam* lam) const {
65 auto i = lam2block_.find(lam);
66 return i == lam2block_.end() ? nullptr : &blocks_[i->second];
67 }
68
69 const Target& target() const { return *target_; }
70 /// Is @p def a parameter of a block or a result of an instruction on a chain, or a projection thereof?
71 bool local(const Def* def) const;
72 const DefVec& params(const Block& block) const { return block.params; }
73 const DefVec& defs(const App* insn) const { return at(insn, &Block::defs); }
74 const DefVec& uses(const App* insn) const { return at(insn, &Block::uses); }
75 /// The values the jump at the end reads.
76 const DefVec& term_uses(const Block& block) const { return block.term_uses; }
77
78private:
79 void order(const Nest::Node*, const LamSet& reach, size_t parent);
80 void chain(size_t, Lam* fun);
81 void values(const Def*, DefVec&, DefSet&) const;
82 void values(Block&);
83 const DefVec& at(const App* insn, fe::Vector<DefVec> Block::* vecs) const {
84 auto [b, i] = insn2block_.find(insn)->second;
85 return (blocks_[b].*vecs)[i];
86 }
87 bool flow(Block&);
88 void sweep(Block&);
89
90 const Target* target_;
91 std::unique_ptr<Nest> nest_;
92 fe::Vector<Block> blocks_;
93 LamMap<size_t> lam2block_;
94 DefMap<std::pair<size_t, size_t>> insn2block_; ///< Block and position.
95};
96
97/// Is @p value a value of class @p cls?
98inline bool is_value(const Def* value, Liveness::Class cls, const Target& target) {
99 return !target.is_mem(value) && !value->type()->isa<Pi>() && target.cls(value) == cls;
100}
101
102/// Where a jump to @p lam goes once the blocks that @p forward skips are skipped.
103inline Lam* forwarded(const LamMap<Lam*>& forward, Lam* lam) {
104 if (auto to = fe::lookup(forward, lam)) return to;
105 return lam;
106}
107
108/// The blocks of @p live in emission order: each block is followed by the one it falls through to, where possible.
109/// A block that @p forward skips is not placed, and jumps to it count as jumps to its target.
110fe::Vector<const Liveness::Block*> layout(const Liveness& live, const LamMap<Lam*>& forward = {});
111
112/// Calls @p f for each use of a value in @p live.
113void for_each_use(const Liveness& live, auto f) {
114 for (const auto& block : live.blocks()) {
115 for (const auto& uses : block.uses)
116 for (auto u : uses)
117 f(u);
118 for (auto u : block.term_uses)
119 f(u);
120 }
121}
122
123/// Rewrites the filter and body of each block of @p live in place.
124void rewrite_blocks(const Liveness& live, Rewriter& rw);
125
126/// Wraps every use of a value that @p regs assigns a register in `in`.
127class Assign : public Rewriter {
128public:
130 : Rewriter(world)
131 , live_(live)
132 , regs_(regs) {}
133
134 const Def* rewrite(const Def*) final;
135
136private:
137 /// @p def, a parameter, an instruction, or a projection thereof, without wrapping it.
138 const Def* raw(const Def* def);
139
140 const Liveness& live_;
141 const DefMap<size_t>& regs_;
142};
143
144/// The parameters of @p lam without its return continuation.
145inline size_t num_params(Lam* lam) { return lam->num_vars() - (lam->ret_pi() ? 1 : 0); }
146
147/// Where the known() function @p fun receives its parameters, given the registers @p regs that Color assigned to them.
148/// A parameter in a callee-saved register arrives in a free caller-saved one, so the callee clobbers only those.
149ParamRegs param_regs(const Target& target, Lam* fun, const DefMap<size_t>& regs);
150
151/// Where an argument goes: a register of its class, an incoming stack slot, or neither (memory or a dead parameter).
152struct ArgLoc {
153 std::optional<size_t> reg;
154 std::optional<size_t> stack;
155};
156
157/// The ArgLoc%s of the first @p num of the @p n arguments in @p arg under @p conv, or the ABI if it is `nullptr`.
158fe::Vector<ArgLoc> arg_locs(const Target& target, const Def* arg, size_t n, size_t num, const ParamRegs* conv);
159
160/// The convention of a known() function: its param_regs() and the registers a call of it clobbers, all caller-saved.
161struct Conv {
163 std::array<fe::Vector<bool>, Target::Num_Classes> clobbers;
164};
165
166/// The Conv of the callee that the call at the end of @p block returns from, if it has one.
167inline const Conv* callee_conv(const LamMap<Conv>& convs, const Liveness::Block& block) {
168 auto f = Lam::isa_mut_returning(block.lam->body()->as<App>()->callee());
169 return f ? fe::lookup(convs, f) : nullptr;
170}
171
172/// Does a call of a function with the convention @p conv, or of an ABI function if there is none, clobber @p r?
173inline bool clobbered(const Target& target, const Conv* conv, Target::Class cls, size_t r) {
174 return conv ? conv->clobbers[cls][r] : target.caller_saved(cls, r);
175}
176
177/// The block that a call at the end of @p block returns to, if any.
178inline const Liveness::Block* call_cont(const Liveness& live, Lam* fun, const Liveness::Block& block) {
179 auto term = block.lam->body()->as<App>();
180 if (term->callee() == fun->ret_var() || !Lam::isa_mut_returning(term->callee())) return nullptr;
181 if (auto k = Lam::isa_mut_basicblock(term->arg(term->num_args(), term->num_args() - 1))) return live.block(k);
182 return nullptr;
183}
184
185/// Calls @p f `(d, v)` for each value `v` that is live at the definition of `d` or defined along with it.
186/// Only values that satisfy @p keep take part.
187template<class Keep, class F>
188void interferences(const Liveness& live, const Liveness::Block& block, Keep keep, F f) {
189 auto alive = DefSet();
190 auto gen = [&](const auto& values) {
191 for (auto v : values)
192 if (keep(v)) alive.emplace(v);
193 };
194 auto def = [&](DefVec ds) {
195 std::erase_if(ds, [&](const Def* d) { return !keep(d); });
196 for (auto d : ds)
197 alive.erase(d);
198 for (size_t i = 0; i != ds.size(); ++i) {
199 for (auto v : alive)
200 f(ds[i], v);
201 for (size_t j = i + 1; j != ds.size(); ++j)
202 f(ds[i], ds[j]);
203 }
204 };
205
206 gen(block.live_out);
207 gen(live.term_uses(block));
208 for (auto insn : block.insns | std::views::reverse) {
209 def(live.defs(insn));
210 gen(live.uses(insn));
211 }
212 def(live.params(block));
213}
214
215} // namespace mim::plug::mach
auto args(Projector auto f) const noexcept
Definition lam.h:252
const Def * callee() const
Definition lam.h:237
Base class for all Defs.
Definition def.h:285
nat_t num_vars() noexcept
Definition def.h:488
const Def * type() const noexcept
Yields the "raw" type of this Def (maybe nullptr).
Definition def.h:1116
Extracts from a Sigma or Array-typed Extract::tuple the element at position Extract::index.
Definition tuple.h:360
A function.
Definition lam.h:91
static Lam * isa_mut_basicblock(const Def *d)
Definition lam.h:130
const Pi * ret_pi() const
Definition lam.h:133
static Lam * isa_mut_returning(const Def *d)
Definition lam.h:129
const Def * ret_var()
Yields the Lam::var of the Lam::ret_pi.
Definition lam.h:136
Builds a nesting tree for all mutables/binders.
Definition nest.h:26
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
Rewriter(World &world)
Definition rewrite.cpp:16
The machine a native backend compiles for, as far as libmim needs to know it.
Definition target.h:11
The World represents the whole program and manages creation of MimIR nodes (Defs).
Definition world.h:43
Assign(World &world, const Liveness &live, const DefMap< size_t > &regs)
Definition liveness.h:129
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 auto & blocks() const
In pre-order of the Nest with siblings in topological order, so a block comes after the block it is n...
Definition liveness.h:63
const Block * block(Lam *lam) const
Definition liveness.h:64
const DefVec & uses(const App *insn) const
Definition liveness.h:74
const DefVec & params(const Block &block) const
Definition liveness.h:72
const Nest::Node * node
Its Node in nest().
Definition liveness.h:47
fe::Vector< DefVec > defs
Definition liveness.h:44
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< DefVec > uses
Per instruction.
Definition liveness.h:44
Target::Class Class
Definition liveness.h:37
const DefVec & term_uses(const Block &block) const
The values the jump at the end reads.
Definition liveness.h:76
fe::Vector< size_t > targets
The blocks its terminator jumps to.
Definition liveness.h:46
Pressure max_live
Maximum over all program points, per Class; Stack is unbounded.
Definition liveness.h:50
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
fe::Vector< const App * > insns
The mem.M 0 chain in execution order.
Definition liveness.h:43
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
static bool is_mem(const Def *def)
Definition target.h:205
Class
The register classes; Stack values live in a spill slot and are unbounded.
Definition target.h:48
Class cls(const Def *def) const
Definition target.h:105
virtual bool caller_saved(Class cls, size_t r) const =0
The mach Plugin
Definition asm.h:15
void for_each_use(const Liveness &live, auto f)
Calls f for each use of a value in live.
Definition liveness.h:113
bool clobbered(const Target &target, const Conv *conv, Target::Class cls, size_t r)
Does a call of a function with the convention conv, or of an ABI function if there is none,...
Definition liveness.h:173
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
bool is_value(const Def *value, Liveness::Class cls, const Target &target)
Is value a value of class cls?
Definition liveness.h:98
size_t num_params(Lam *lam)
The parameters of lam without its return continuation.
Definition liveness.h:145
const Liveness::Block * call_cont(const Liveness &live, Lam *fun, const Liveness::Block &block)
The block that a call at the end of block returns to, if any.
Definition liveness.h:178
void interferences(const Liveness &live, const Liveness::Block &block, Keep keep, F f)
Calls f (d, v) for each value v that is live at the definition of d or defined along with it.
Definition liveness.h:188
std::optional< size_t > reg
Definition liveness.h:153
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
const Conv * callee_conv(const LamMap< Conv > &convs, const Liveness::Block &block)
The Conv of the callee that the call at the end of block returns from, if it has one.
Definition liveness.h:167
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
std::optional< size_t > stack
Definition liveness.h:154
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
Where an argument goes: a register of its class, an incoming stack slot, or neither (memory or a dead...
Definition liveness.h:152
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
The convention of a known() function: its param_regs() and the registers a call of it clobbers,...
Definition liveness.h:161
std::array< fe::Vector< bool >, Target::Num_Classes > clobbers
Definition liveness.h:163