Thorin 1.9.0
The Higher ORder INtermediate representation
Loading...
Searching...
No Matches
branch_clos_elim.cpp
Go to the documentation of this file.
2
4
5namespace thorin::plug::clos {
6
7namespace {
8
9std::tuple<std::vector<ClosLit>, Ref> isa_branch(Ref callee) {
10 if (auto closure_proj = callee->isa<Extract>()) {
11 auto inner_proj = closure_proj->tuple()->isa<Extract>();
12 if (inner_proj && inner_proj->tuple()->isa<Tuple>() && isa_clos_type(inner_proj->type())) {
13 auto branches = std::vector<ClosLit>();
14 for (auto op : inner_proj->tuple()->ops())
15 if (auto c = isa_clos_lit(op))
16 branches.push_back(std::move(c));
17 else
18 return {};
19 return {branches, inner_proj->index()};
20 }
21 }
22 return {};
23}
24
25} // namespace
26
28 auto& w = world();
29 auto app = def->isa<App>();
30 if (!app || !Pi::isa_cn(app->callee_type())) return def;
31
32 if (auto [branches, index] = isa_branch(app->callee()); index) {
33 w.DLOG("FLATTEN BRANCH {}", app->callee());
34 auto new_branches = w.tuple(DefVec(branches.size(), [&](auto i) {
35 auto c = branches[i];
36 auto [entry, inserted] = branch2dropped_.emplace(c, nullptr);
37 auto& dropped_lam = entry->second;
38 if (inserted || !dropped_lam) {
39 auto clam = c.fnc_as_lam();
40 dropped_lam = clam->stub(clos_type_to_pi(c.type()));
41 auto new_vars = clos_insert_env(c.env(), dropped_lam->var());
42 dropped_lam->set(clam->reduce(new_vars));
43 }
44 return dropped_lam;
45 }));
46 return w.app(w.extract(new_branches, index), clos_remove_env(app->arg()));
47 }
48
49 return def;
50}
51
52}; // namespace thorin::plug::clos
size_t index() const
Definition pass.h:33
World & world()
Definition pass.h:296
static const Pi * isa_cn(Ref d)
Is this a continuation - i.e. is the Pi::codom thorin::Bottom?
Definition lam.h:50
Helper class to retrieve Infer::arg if present.
Definition def.h:87
Definition span.h:103
@ Extract
Definition def.h:41
@ Tuple
Definition def.h:41
The clos Plugin
Definition clos.h:7
const Sigma * isa_clos_type(Ref def)
Returns def if def is a closure and nullptr otherwise.
Definition clos.cpp:111
ClosLit isa_clos_lit(Ref def, bool fn_isa_lam=true)
Tries to match a closure literal.
Definition clos.cpp:64
Ref clos_remove_env(size_t i, std::function< Ref(size_t)> f)
Definition clos.cpp:139
Ref op(trait o, Ref type)
Definition core.h:35
Vector< const Def * > DefVec
Definition def.h:63