MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
emit.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <optional>
5#include <print>
6#include <sstream>
7#include <utility>
8
9#include <fe/algo.h>
10
11#include <mim/driver.h>
12
13#include "mim/plug/mach/asm.h"
15
16namespace mim::plug::mach {
17
18class Emitter;
19class Liveness;
20
21/// Emitter::emit, compiled once into `libmim_mach`; Emitter reaches it via `GET_FUN_PTR`.
22extern "C" MIM_EXPORT void mim_mach_emit(Emitter&, bool global);
23
24/// A physical register of a register class.
25struct Reg {
26 size_t num;
28 bool operator==(const Reg&) const = default;
29};
30
31/// The source of a copy: a register or a literal; `reg.cls` is the class of either.
32struct Src {
33 Reg reg = {};
34 const Def* imm = nullptr;
35};
36
37using Moves = fe::Vector<std::pair<Reg, Src>>;
38
39/// Writes the GNU assembler code of one function on the registers that Color assigned.
40/// The control flow is target-independent: jumps, calls, returns, and the entry are parallel copies, the blocks are
41/// laid out by layout(), and the callee-saved registers that hold values are saved.
42/// A backend derives from it and emits its instructions, moves, branches, prologue, and epilogue.
43class Emitter {
44public:
45 Emitter(const Target& target, std::ostream& os, AsmEmit& emit, Lam* fun)
46 : target_(target)
47 , os_(os)
48 , emit_(emit)
49 , fun_(fun)
50 , ret_(fun->ret_var()) {}
51 virtual ~Emitter() = default;
52
53 void emit(bool global) { fun_->world().driver().GET_FUN_PTR("mach", mim_mach_emit)(*this, global); }
54
55protected:
56 /// @name Hooks
57 ///@{
58 /// Emits the instruction @p app on the chain.
59 virtual void step(const App* app) = 0;
60 virtual void move(Reg dst, Reg src) = 0;
61 virtual void mov_imm(Reg dst, const Def* lit) = 0;
62 /// Exchanges two registers of one class; only called if there is no scratch().
63 virtual void swap(Reg, Reg) { std::unreachable(); }
64 /// A register of class @p cls that breaks a copy cycle instead of swap(), if any.
65 virtual std::optional<Reg> scratch(Target::Class) const { return {}; }
66 /// Pushes the spill slot @p i; the pops come in reverse order.
67 virtual void push_slot(size_t i) = 0;
68 virtual void pop_slot(size_t i) = 0;
69 /// Stores @p src, a value of @p type, into the spill slot @p i.
70 virtual void spill(Src src, const Def* type, size_t i) = 0;
71 /// Loads the spill slot @p i, a value of @p type, into @p dst.
72 virtual void reload(Reg dst, const Def* type, size_t i) = 0;
73 /// Loads the @p i-th argument that the caller passed on the stack, a value of @p type, into @p dst.
74 virtual void load_arg(Reg dst, const Def* type, size_t i) = 0;
75 /// Puts the address of the @p n slots from @p first on into the register @p dst.
76 virtual void slot_addr(size_t dst, size_t first, size_t n) = 0;
77 virtual void jmp(std::string_view label) = 0;
78 /// Branches to @p label if the condition code @p cc holds.
79 virtual void branch_cc(size_t cc, std::string_view label) = 0;
80 /// Branches to @p label if the `Bool` in register @p r is set, or with @p unless, if it is clear.
81 virtual void branch_if(size_t r, std::string_view label, bool unless = false) = 0;
82 /// Calls @p sym with @p num_args arguments per register class in the ABI's argument registers.
83 /// A known() callee has no @p num_args: it is not variadic and its parameters may be in any register.
84 virtual void call_insn(std::string_view sym, std::optional<std::array<size_t, Target::Num_Classes>> num_args) = 0;
85 /// The code between the function's label and its body; slots() and saved() are final by then.
86 virtual void prologue(std::ostream& os) = 0;
87 /// Tears down the frame that prologue() built.
88 virtual void leave() = 0;
89 /// The argument of `.type`, e.g. `@function`.
90 virtual std::string_view function_type() const { return "@function"; }
91 ///@}
92
93 template<class... Args>
94 void line(std::format_string<Args...> fmt, Args&&... args) {
95 std::print(body_, "\t");
96 std::println(body_, fmt, std::forward<Args>(args)...);
97 }
98 void label_here(std::string_view label) { std::println(body_, "{}:", label); }
99
100 const Target& target() const { return target_; }
101 std::string_view backend() const { return target_.name(); }
102 Lam* fun() const { return fun_; }
103 std::string label(Lam* lam) const { return std::format("{}{}", Target::local_prefix(), lam->unique_name()); }
104 std::string symbol(Lam* lam) { return emit_.symbol(lam); }
105 nat_t nat(const Def* def) const {
106 if (auto l = Lit::isa(def)) return *l;
107 def->blame("{} backend: expected a literal, got `{}`", backend(), def).bail();
108 }
109
110 /// The register of the result @p def.
111 size_t def_reg(const Def* def) const {
112 if (auto r = fe::lookup(regs_, def)) return *r;
113 def->blame("{} backend: `{}` has no register", backend(), def).bail();
114 }
115 /// The register of the operand @p def, a Target::in, possibly under a Target::is_view.
116 size_t use_reg(const Def* def) const {
117 if (auto in = Target::unview(def); Target::is_in(in)) return Target::in_reg(in);
118 if (Lit::isa(def)) def->blame("{} backend: literal `{}` cannot be an operand here", backend(), def).bail();
119 def->blame("{} backend: `{}` is not in a register", backend(), def).bail();
120 }
121 std::optional<size_t> isa_reg(const Def* def) const {
122 if (auto r = fe::lookup(regs_, def)) return *r;
123 return {};
124 }
125 Src source(const Def* def) const {
126 auto cls = target_.cls(Target::strip(def));
127 return Lit::isa(def) ? Src{.reg = {0, cls}, .imm = def} : Src{.reg = {use_reg(def), cls}};
128 }
129
130 /// @name Flags
131 ///@{
132 /// Records that the flags hold the result @p fl.
133 void set_flags(const Def* fl) { flags_ = fl; }
134 void clobber_flags() { flags_ = nullptr; }
135 bool flags_clobbered() const { return flags_ == nullptr; }
136 /// Rejects a use of the flags @p fl if something clobbered them since.
137 void use_flags(const Def* fl) const {
138 if (fl != flags_) fl->blame("{} backend: flags `{}` are clobbered before their use", backend(), fl).bail();
139 }
140 ///@}
141
142 /// @name Frame
143 /// The frame holds 8-byte slots: spill slots and the areas of `slot` instructions.
144 ///@{
145 /// The slot of the spilled value @p def.
146 size_t spill_slot(const Def* def) {
147 auto [i, ins] = slots_.emplace(def, num_slots_);
148 if (ins) ++num_slots_;
149 return i->second;
150 }
151 /// Reserves @p bytes and yields the index of their first slot.
152 size_t alloc_slots(nat_t bytes) {
153 auto res = num_slots_;
154 num_slots_ += (bytes + 7) / 8;
155 return res;
156 }
157 size_t num_slots() const { return num_slots_; }
158 /// The callee-saved registers of class @p cls that hold values.
159 const fe::Vector<size_t>& saved(Target::Class cls) const { return saved_[cls]; }
160 size_t num_saved() const {
161 return std::ranges::fold_left(saved_, size_t(0), [](size_t n, const auto& rs) { return n + rs.size(); });
162 }
163 ///@}
164
165 std::ostringstream& body() { return body_; }
166
167 /// The bytes of the callee-saved registers, slots, and spill slots, rounded up to keep `sp` 16-byte aligned.
168 size_t frame_size() const { return fe::pad(8 * (num_saved() + num_slots_), 16); }
169
170private:
171 friend void mim_mach_emit(Emitter&, bool);
172
173 void run(bool global);
174 void insn(const App*);
175 void block(Lam* lam, const fe::Vector<const App*>& insns);
176 using SlotMoves = fe::Vector<std::pair<size_t, size_t>>;
177
178 void parallel(Moves moves, SlotMoves slot_moves);
179 /// The register and slot moves that a jump with @p arg to @p target needs.
180 std::pair<Moves, SlotMoves> moves(Lam* target, const Def* arg);
181 void copy(Lam* target, const Def* arg);
182 /// Where a jump to @p target goes once the blocks that are only a jump without moves are skipped.
183 Lam* forward(Lam* target) const { return forwarded(forward_, target); }
184 void jump(Lam* target);
185 /// Moves the first @p num_args arguments in @p arg to the registers @p conv or the argument registers.
186 std::array<size_t, Target::Num_Classes> pass(const Def* arg, size_t num_args, const ParamRegs* conv);
187 /// The param_regs() of @p lam if it is a known() function.
188 const ParamRegs* params(Lam* lam);
189 void call(Lam* callee, const Def* arg);
190 void epilogue() {
191 leave();
192 line("ret");
193 }
194
195 const Target& target_;
196 std::ostream& os_;
197 AsmEmit& emit_;
198 Lam* fun_;
199 const Def* ret_;
200 const Liveness* live_ = nullptr;
201 std::ostringstream body_;
202 DefMap<size_t> regs_;
203 DefMap<size_t> slots_;
204 size_t num_slots_ = 0;
205 std::array<fe::Vector<size_t>, Target::Num_Classes> saved_;
206 LamMap<Lam*> forward_;
207 bool inlining_ = false; ///< Is a block being emitted in place of a jump to it?
208 bool fell_ = false; ///< Did the last block fall through to the next one, which then keeps the flags?
209 Lam* next_ = nullptr;
210 const Def* flags_ = nullptr; ///< The result of the instruction that set the flags.
211};
212
213} // namespace mim::plug::mach
Base class for all Defs.
Definition def.h:285
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
std::string unique_name() const
name + "_" + Def::gid
Definition def.cpp:646
A function.
Definition lam.h:91
static std::optional< T > isa(const Def *def)
Definition def.h:974
The machine a native backend compiles for, as far as libmim needs to know it.
Definition target.h:11
The emit Phase of a native backend: writes GNU assembler code for each external function and each fun...
Definition asm.h:19
Writes the GNU assembler code of one function on the registers that Color assigned.
Definition emit.h:43
virtual void spill(Src src, const Def *type, size_t i)=0
Stores src, a value of type, into the spill slot i.
virtual void mov_imm(Reg dst, const Def *lit)=0
virtual void prologue(std::ostream &os)=0
The code between the function's label and its body; slots() and saved() are final by then.
size_t spill_slot(const Def *def)
Definition emit.h:146
std::string label(Lam *lam) const
Definition emit.h:103
Src source(const Def *def) const
Definition emit.h:125
virtual void pop_slot(size_t i)=0
virtual void branch_if(size_t r, std::string_view label, bool unless=false)=0
Branches to label if the Bool in register r is set, or with unless, if it is clear.
const Target & target() const
Definition emit.h:100
std::ostringstream & body()
Definition emit.h:165
virtual void reload(Reg dst, const Def *type, size_t i)=0
Loads the spill slot i, a value of type, into dst.
void set_flags(const Def *fl)
Definition emit.h:133
Lam * fun() const
Definition emit.h:102
void use_flags(const Def *fl) const
Rejects a use of the flags fl if something clobbered them since.
Definition emit.h:137
virtual std::string_view function_type() const
The argument of .type, e.g. @function.
Definition emit.h:90
virtual void jmp(std::string_view label)=0
void emit(bool global)
Definition emit.h:53
friend void mim_mach_emit(Emitter &, bool)
Emitter::emit, compiled once into libmim_mach; Emitter reaches it via GET_FUN_PTR.
Definition emit.cpp:371
virtual void push_slot(size_t i)=0
Pushes the spill slot i; the pops come in reverse order.
virtual void move(Reg dst, Reg src)=0
void line(std::format_string< Args... > fmt, Args &&... args)
Definition emit.h:94
virtual void swap(Reg, Reg)
Exchanges two registers of one class; only called if there is no scratch().
Definition emit.h:63
size_t use_reg(const Def *def) const
The register of the operand def, a Target::in, possibly under a Target::is_view.
Definition emit.h:116
virtual void slot_addr(size_t dst, size_t first, size_t n)=0
Puts the address of the n slots from first on into the register dst.
virtual void leave()=0
Tears down the frame that prologue() built.
virtual void step(const App *app)=0
const fe::Vector< size_t > & saved(Target::Class cls) const
The callee-saved registers of class cls that hold values.
Definition emit.h:159
virtual void branch_cc(size_t cc, std::string_view label)=0
Branches to label if the condition code cc holds.
bool flags_clobbered() const
Definition emit.h:135
nat_t nat(const Def *def) const
Definition emit.h:105
virtual std::optional< Reg > scratch(Target::Class) const
A register of class cls that breaks a copy cycle instead of swap(), if any.
Definition emit.h:65
std::string symbol(Lam *lam)
Definition emit.h:104
size_t frame_size() const
The bytes of the callee-saved registers, slots, and spill slots, rounded up to keep sp 16-byte aligne...
Definition emit.h:168
size_t def_reg(const Def *def) const
The register of the result def.
Definition emit.h:111
virtual void call_insn(std::string_view sym, std::optional< std::array< size_t, Target::Num_Classes > > num_args)=0
Calls sym with num_args arguments per register class in the ABI's argument registers.
size_t num_saved() const
Definition emit.h:160
void label_here(std::string_view label)
Definition emit.h:98
std::string_view backend() const
Definition emit.h:101
size_t alloc_slots(nat_t bytes)
Reserves bytes and yields the index of their first slot.
Definition emit.h:152
std::optional< size_t > isa_reg(const Def *def) const
Definition emit.h:121
virtual ~Emitter()=default
virtual void load_arg(Reg dst, const Def *type, size_t i)=0
Loads the i-th argument that the caller passed on the stack, a value of type, into dst.
size_t num_slots() const
Definition emit.h:157
Emitter(const Target &target, std::ostream &os, AsmEmit &emit, Lam *fun)
Definition emit.h:45
Liveness of the values of one scheduled function, as a side table.
Definition liveness.h:35
The machine facts of a native backend that the phases of mach need.
Definition target.h:45
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 size_t in_reg(const Def *in)
The register r of in r v.
Definition target.h:187
Class
The register classes; Stack values live in a spill slot and are unbounded.
Definition target.h:48
static bool is_in(const Def *def)
Definition target.h:180
static const Def * unview(const Def *def)
The v of zext d v, otherwise def.
Definition target.h:193
static constexpr std::string_view local_prefix()
The prefix of an assembler-local label.
Definition target.h:72
#define MIM_EXPORT
Definition config.h:21
The mach Plugin
Definition asm.h:15
const Def * imm
Definition emit.h:34
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
void mim_mach_emit(Emitter &, bool global)
Emitter::emit, compiled once into libmim_mach; Emitter reaches it via GET_FUN_PTR.
Definition emit.cpp:371
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
fe::Vector< std::pair< Reg, Src > > Moves
Definition emit.h:37
The source of a copy: a register or a literal; reg.cls is the class of either.
Definition emit.h:32
u64 nat_t
Definition types.h:37
GIDMap< const Def *, To > DefMap
Definition def.h:91
GIDMap< Lam *, To > LamMap
Definition lam.h:210
A physical register of a register class.
Definition emit.h:25
bool operator==(const Reg &) const =default
Target::Class cls
Definition emit.h:27