MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
legalize.cpp
Go to the documentation of this file.
2
4#include <mim/plug/mem/mem.h>
5
7
8namespace mim::plug::mach {
9
10namespace {
11
12core::icmp unsigned_cmp(core::ncmp id) {
13 switch (id) {
14 case core::ncmp::e: return core::icmp::e;
15 case core::ncmp::ne: return core::icmp::ne;
16 case core::ncmp::l: return core::icmp::ul;
18 case core::ncmp::g: return core::icmp::ug;
20 default: std::unreachable(); // `f` and `t` normalize to literals.
21 }
22}
23
24nat_t trait(core::trait t, const Def* type) {
25 if (auto n = Lit::isa(core::op(t, type))) return *n;
26 type->blame("type `{}` has no static size or alignment", type).bail();
27}
28
29/// The byte offset of field @p i of @p sigma.
30nat_t field_offset(const Def* sigma, nat_t i) {
31 auto fields = sigma->projs();
32 if (auto l = core::layout(Defs(fields).first(i + 1))) return l->offsets[i];
33 sigma->blame("type `{}` has no static size or alignment", sigma).bail();
34}
35
36} // namespace
37
38bool Legalize::is_value(const Def* args) {
39 for (auto arg : args->projs()) {
40 auto res = rewrite(arg);
41 if (res->type()->isa<Nat>() && !Lit::isa(res)) return false;
42 }
43 return true;
44}
45
46const Def* Legalize::val(const Def* def) {
47 auto res = rewrite(def);
48 if (auto l = Lit::isa(res); l && res->type()->isa<Nat>()) return new_world().lit_i64(*l);
49 return res;
50}
51
52/// A literal odd `n` of `conv.u n y` is a remainder, a dynamic one is ignored.
53const Def* Legalize::index(const Def* i) {
54 if (auto conv = Axm::isa(core::conv::u, i)) {
55 if (!Idx::isa_lit(i->type())) return rewrite(conv->arg());
56 if (auto n = core::isa_odd_idx(i->type()))
57 return new_world().call<core::rem>(new_world().lit_nat(*n), rewrite(conv->arg()));
58 }
59 return rewrite(i);
60}
61
62std::array<const Def*, 2> Legalize::rewrite_filter_body(Lam* old_lam, Lam* new_lam) {
63 auto body = RWPhase::rewrite_filter_body(old_lam, new_lam)[1];
64 if (auto br = Branch(body)) body = split(br.cond(), br.ff(), br.tt(), br.arg());
65 // A later rewrite must not inline a block into a wrapper of split(), which would duplicate its edges.
66 return {new_world().lit_ff(), body};
67}
68
69const Def* Legalize::split(const Def* cond, const Def* ff, const Def* tt, const Def* arg) {
70 auto& w = new_world();
71 if (auto bit2 = Axm::isa<core::bit2>(cond);
72 bit2 && (bit2.id() == core::bit2::or_ || bit2.id() == core::bit2::and_)) {
73 auto [a, b] = bit2->args<2>();
74 auto rest = w.mut_con(arg->type());
75 // Each edge gets its own wrapper, so no critical edge arises.
76 auto wrap = [&](const Def* f) {
77 auto eta = w.mut_lam(f->type()->as<Pi>());
78 return eta->set(false, w.app<false>(f, eta->var()));
79 };
80 if (bit2.id() == core::bit2::or_) {
81 rest->set(false, split(b, ff, wrap(tt), rest->var()));
82 return split(a, rest, wrap(tt), arg);
83 }
84 rest->set(false, split(b, wrap(ff), tt, rest->var()));
85 return split(a, wrap(ff), rest, arg);
86 }
87 return w.app(w.select(cond, tt, ff), arg);
88}
89
91 if (lit->type()->isa<Nat>()) return new_world().lit_nat(lit->get());
93}
94
95const Def* Legalize::coerce_leaf(const Def* type, const Def* val) {
96 auto& w = new_world();
97 if (auto l = Lit::isa(val); l && type == w.type_i64() && val->type()->isa<Nat>()) return w.lit_i64(*l);
98 return nullptr;
99}
100
102 // A select of `Nat`s is a value, so its literals become `I64`.
103 if (auto tuple = ex->tuple()->isa<Tuple>(); tuple && ex->type()->isa<Nat>() && !Lit::isa(ex->index())) {
104 auto ops = DefVec(tuple->ops(), [this](const Def* op) { return val(op); });
105 return new_world().extract(new_world().tuple(ops), rewrite(ex->index()));
106 }
108}
109
111 auto& w = new_world();
112 if (Axm::isa<core::Ptr>(app)) return w.type_i64();
113
114 // A `Nat` that a type computes stays a `Nat`, which no C function takes.
115 if (auto decl = app->callee()->isa_mut<Lam>(); decl && !decl->is_set())
116 for (auto arg : app->args())
117 if (auto a = rewrite(arg); a->type()->isa<Nat>() && !Lit::isa(a))
118 arg->blame("native backend: argument `{}` of `{}` is no value", arg, decl).bail();
119
120 if (auto lea = Axm::isa<mem::lea>(app)) {
121 auto [p, i] = lea->args<2>();
122 auto pointee = mem::pointee(p);
123 auto l = Lit::isa(i);
124 const Def* off = nullptr;
125 if (!pointee->isa<Arr>()) {
126 if (!l) i->blame("index `{}` into `{}` must be a literal", i, pointee).bail();
127 off = w.lit_i64(field_offset(pointee, *l));
128 } else if (auto size = trait(core::trait::size, mem::pointee(lea)); l) {
129 off = w.lit_i64(*l * size);
130 } else {
131 off = core::zext(w, index(i));
132 if (size != 1) off = w.call(core::wrap::mul, core::Mode::none, Defs{off, w.lit_i64(size)});
133 }
134 return w.call(core::wrap::add, core::Mode::none, Defs{rewrite(p), off});
135 }
136
137 if (auto load = Axm::isa<mem::load>(app)) {
138 auto [T, a] = load->decurry()->args<2>();
139 auto [m, p] = load->args<2>();
140 check_addr_space(app, a);
141 return w.call<mach::load>(rewrite(T), Defs{rewrite(m), rewrite(p)});
142 }
143
144 if (auto store = Axm::isa<mem::store>(app)) {
145 auto [m, p, x] = store->args<3>();
146 check_addr_space(app, store->decurry()->arg(2, 1));
147 return w.call<mach::store>(Defs{rewrite(m), rewrite(p), rewrite(x)});
148 }
149
150 // A view of an array changes only the pointee.
151 if (auto assume = Axm::isa<mem::assume>(app)) return rewrite(assume->arg(2, 0));
152
153 if (auto mslot = Axm::isa<mem::mslot>(app)) {
154 auto [msz, k] = mslot->args<2>();
155 auto [m, size] = msz->projs<2>();
156 check_addr_space(app, mslot->decurry()->arg(2, 1));
157 auto n = Lit::isa(size);
158 if (!n) app->blame("native backend: `mem.mslot` needs a literal size").bail();
159 return w.app(rewrite(k), w.call<slot>(w.lit_nat(*n), rewrite(m)));
160 }
161
162 if (auto nat = Axm::isa<core::nat>(app); nat && is_value(nat->arg())) {
163 auto [a, b] = nat->args<2>([this](const Def* def) { return val(def); });
164 auto div = [&](core::div op) {
165 auto m = w.bot(w.call<core::M>(w.lit_nat_0()));
166 return w.call(op, Defs{m, w.tuple({a, b})})->proj(2, 1);
167 };
168 switch (nat.id()) {
169 case core::nat::add: return w.call(core::wrap::add, core::Mode::none, Defs{a, b});
170 case core::nat::mul: return w.call(core::wrap::mul, core::Mode::none, Defs{a, b});
171 case core::nat::sub: {
172 auto diff = w.call(core::wrap::sub, core::Mode::none, Defs{a, b});
173 return w.extract(w.tuple({diff, w.lit_i64(0)}), w.call(core::icmp::ul, Defs{a, b}));
174 }
175 case core::nat::div: return div(core::div::udiv);
176 case core::nat::rem: return div(core::div::urem);
177 }
178 }
179
180 if (auto ncmp = Axm::isa<core::ncmp>(app); ncmp && is_value(ncmp->arg())) {
181 auto [a, b] = ncmp->args<2>([this](const Def* def) { return val(def); });
182 return w.call(unsigned_cmp(ncmp.id()), Defs{a, b});
183 }
184
185 if (auto idx = Axm::isa<core::idx>(app); idx && is_value(idx->arg()))
186 return w.call(core::conv::u, rewrite(Idx::isa(idx->type())), val(idx->arg()));
187
188 if (auto i2n = Axm::isa<core::idx2nat>(app)) return core::zext(w, rewrite(i2n->arg()));
189
190 if (auto cast = Axm::isa<core::bitcast>(app)) {
191 auto type = rewrite(cast->type());
192 auto x = val(cast->arg());
193 return x->type() == type ? x : w.call<core::bitcast>(type, x);
194 }
195
196 return RWPhase::rewrite_imm_App(app);
197}
198
199} // namespace mim::plug::mach
auto args(Projector auto f) const noexcept
Definition lam.h:252
const Def * callee() const
Definition lam.h:237
A (possibly paramterized) Array.
Definition tuple.h:305
static auto isa(const Def *def)
Definition axm.h:112
Branch(const Def *)
Definition tuple.cpp:97
Base class for all Defs.
Definition def.h:285
bool is_set() const
Definition def.h:392
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 * 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
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
const Def * index() const
Definition tuple.h:371
static const Def * isa(const Def *def)
Checks if def is a Idx s and returns s or nullptr otherwise.
Definition def.cpp:682
static std::optional< nat_t > isa_lit(const Def *def)
Definition def.cpp:689
A function.
Definition lam.h:91
static std::optional< T > isa(const Def *def)
Definition def.h:974
const fe::Vector< std::string > & args()
Command-line arguments passed to this Phase's plugin via -X <plugin>:<arg>.
Definition phase.cpp:23
A dependent function type.
Definition lam.h:14
World & new_world()
Create new Defs into this.
Definition phase.h:418
virtual std::array< const Def *, 2 > rewrite_filter_body(Lam *old_lam, Lam *)
The rewritten filter and body of old_lam for its stub new_lam, before the body is coerce()d.
Definition phase.h:434
const Def * rewrite_imm_App(const App *) override
Definition phase.cpp:317
virtual const Def * rewrite_imm_Extract(const Extract *)
virtual const Def * rewrite(const Def *)
Definition rewrite.cpp:62
virtual const Def * rewrite_imm_Lit(const Lit *)
Data constructor for a Sigma.
Definition tuple.h:84
const Def * call(const Def *callee, auto &&arg, Args &&... args)
Definition world.h:693
const Lit * lit_i64()
Definition world.h:589
const Def * extract(const Def *d, const Def *i)
Definition world.cpp:634
const Lit * lit_ff()
Definition world.h:614
const Lit * lit_nat(nat_t a)
Definition world.h:577
std::array< const Def *, 2 > rewrite_filter_body(Lam *, Lam *) final
The rewritten filter and body of old_lam for its stub new_lam, before the body is coerce()d.
Definition legalize.cpp:62
const Def * rewrite_imm_Lit(const Lit *) final
Definition legalize.cpp:90
const Def * rewrite_imm_Extract(const Extract *) final
Definition legalize.cpp:101
const Def * rewrite_imm_App(const App *) final
Definition legalize.cpp:110
const Def * coerce_leaf(const Def *, const Def *) final
Converts the new leaf new_val into the new new_type, whose representation this phase changed.
Definition legalize.cpp:95
std::optional< nat_t > isa_odd_idx(const Def *type)
The literal size of the Idx type if it is no Bool, I8, I16, I32, or I64.
Definition core.h:42
std::optional< Layout > layout(Defs fields, bool overlap=false)
The Layout of fields, unless one of them has no literal size or alignment.
Definition core.h:104
const Def * zext(World &w, const Def *x)
Zero-extends x to I64.
Definition core.h:47
const Def * op(trait o, const Def *type)
Definition core.h:91
@ none
Wrap around.
Definition core.h:21
The mach Plugin
Definition asm.h:15
void check_addr_space(const App *app, const Def *a)
Bails unless the address space a of the mem operation app is 0.
Definition mach.h:31
const Def * pointee(const Def *ptr)
Definition core.h:192
The tuple Plugin
u64 nat_t
Definition types.h:37
fe::View< const Def * > Defs
Definition def.h:94
fe::Vector< const Def * > DefVec
Definition def.h:96