-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathemit.cpp
More file actions
2085 lines (1869 loc) · 86.6 KB
/
emit.cpp
File metadata and controls
2085 lines (1869 loc) · 86.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "artic/emit.h"
#include "artic/types.h"
#include "artic/ast.h"
#include "artic/print.h"
#include "artic/locator.h"
#include "artic/parser.h"
#include "artic/bind.h"
#include "artic/check.h"
#include <thorin/def.h>
#include <thorin/type.h>
#include <thorin/world.h>
namespace artic {
/// Pattern matching compiler inspired from
/// "Compiling Pattern Matching to Good Decision Trees",
/// by Luc Maranget.
class PtrnCompiler {
public:
struct MatchCase {
const ast::Ptrn* ptrn;
const ast::Expr* expr;
const ast::Node* node;
bool is_redundant = true;
thorin::Continuation* cont = nullptr;
const thorin::Continuation* target;
std::vector<const struct ast::IdPtrn*> bound_ptrns;
MatchCase(
const ast::Ptrn* ptrn,
const ast::Expr* expr,
const ast::Node* node,
const thorin::Continuation* target)
: ptrn(ptrn)
, expr(expr)
, node(node)
, target(target)
{
ptrn->collect_bound_ptrns(bound_ptrns);
}
const thorin::Def* emit(Emitter&);
};
static void emit(
Emitter& emitter,
const ast::Node& node,
const ast::Expr& expr,
std::vector<MatchCase>&& cases,
std::unordered_map<const ast::IdPtrn*, const thorin::Def*>&& matched_values);
private:
// Note: `nullptr`s are used to denote row elements that are not connected to any pattern
using Row = std::pair<std::vector<const ast::Ptrn*>, MatchCase*>;
using Value = std::pair<const thorin::Def*, const Type*>;
using Cost = size_t;
Emitter& emitter;
const ast::Node& node;
const ast::Expr& expr;
std::vector<Row> rows;
std::vector<Value> values;
std::unordered_map<const ast::IdPtrn*, const thorin::Def*>& matched_values;
PtrVector<ast::Ptrn> tmp_ptrns;
PtrnCompiler(
Emitter& emitter,
const ast::Node& node,
const ast::Expr& expr,
std::vector<Row>&& rows,
std::vector<Value>&& values,
std::unordered_map<const ast::IdPtrn*, const thorin::Def*>& matched_values)
: emitter(emitter)
, node(node)
, expr(expr)
, rows(std::move(rows))
, values(std::move(values))
, matched_values(matched_values)
{}
static bool is_wildcard(const ast::Ptrn* ptrn) {
return !ptrn || ptrn->isa<ast::IdPtrn>();
}
template <typename T>
static void remove_col(std::vector<T>& vector, size_t col) {
std::swap(vector[col], vector.back());
vector.pop_back();
}
template <typename F>
void apply_heuristic(std::vector<bool>& enabled, const F& f) const {
std::vector<Cost> cost(values.size());
Cost min_cost = std::numeric_limits<Cost>::max();
for (size_t i = 0, n = values.size(); i < n; ++i) {
if (enabled[i]) {
cost[i] = f(i);
min_cost = std::min(min_cost, cost[i]);
}
}
for (size_t i = 0, n = values.size(); i < n; ++i)
enabled[i] = enabled[i] & (cost[i] == min_cost);
}
static bool is_complete(const Type* type, size_t ctor_count) {
if (is_bool_type(type) && ctor_count == 2)
return true;
else if (
auto [_, enum_type] = match_app<EnumType>(type);
enum_type && enum_type->member_count() == ctor_count)
return true;
return false;
}
size_t pick_col() const {
// This applies the f, d and b heuristics, as suggested in the article listed above.
std::vector<bool> enabled(values.size(), true);
apply_heuristic(enabled, [this] (size_t i) -> Cost{
return is_wildcard(rows[0].first[i]) ? 1 : 0;
});
apply_heuristic(enabled, [this] (size_t i) -> Cost {
Cost cost = 0;
for (auto& row : rows)
cost += is_wildcard(row.first[i]) ? 1 : 0;
return cost;
});
apply_heuristic(enabled, [this] (size_t i) -> Cost {
std::unordered_set<const thorin::Def*> ctors;
for (auto& row : rows) {
if (!is_wildcard(row.first[i]))
ctors.emplace(emitter.ctor_index(*row.first[i]));
}
// If the match expression is complete, then the default case can be omitted
return is_complete(values[i].second, ctors.size()) ? ctors.size() : ctors.size() + 1;
});
return std::find(enabled.begin(), enabled.end(), true) - enabled.begin();
}
// Transforms the rows such that tuples and structures are completely deconstructed
void expand() {
for (size_t i = 0; i < values.size();) {
// Replace patterns by their sub-patterns, if possible
// i.e if the pattern is `z as (x, y)` then we replace it with `(x, y)`
// and remember that `z` maps to the value bound to `(x, y)`
for (auto& row : rows) {
if (!row.first[i])
continue;
while (true) {
if (auto id_ptrn = row.first[i]->isa<ast::IdPtrn>(); id_ptrn && id_ptrn->sub_ptrn) {
matched_values.emplace(id_ptrn, values[i].first);
row.first[i] = id_ptrn->sub_ptrn.get();
} else
break;
}
}
auto type = values[i].second;
auto [type_app, struct_type] = match_app<StructType>(type);
// Can only expand tuples or structures
size_t member_count = 0;
if (struct_type)
member_count = struct_type->member_count();
else if (auto tuple_type = type->isa<TupleType>())
member_count = tuple_type->args.size();
else if (auto sized_array_type = type->isa<SizedArrayType>())
member_count = sized_array_type->size;
else {
// Move to the next column
i++;
continue;
}
// Expand the patterns in this column, for each row
for (auto& row : rows) {
std::vector<const ast::Ptrn*> new_elems(member_count, nullptr);
if (row.first[i]) {
if (auto struct_ptrn = row.first[i]->isa<ast::RecordPtrn>()) {
for (auto& field : struct_ptrn->fields) {
if (!field->is_etc())
new_elems[field->index] = field->ptrn.get();
}
} else if (auto ctor_ptrn = row.first[i]->isa<ast::CtorPtrn>()) {
// This must be a tuple-like struct.
if (struct_type->member_count() == 1)
new_elems[0] = ctor_ptrn->arg.get();
else {
for (size_t j = 0; j < member_count; ++j)
new_elems[j] = ctor_ptrn->arg->as<ast::TuplePtrn>()->args[j].get();
}
} else if (auto tuple_ptrn = row.first[i]->isa<ast::TuplePtrn>()) {
for (size_t j = 0; j < member_count; ++j)
new_elems[j] = tuple_ptrn->args[j].get();
} else if (auto array_ptrn = row.first[i]->isa<ast::ArrayPtrn>()) {
for (size_t j = 0; j < member_count; ++j)
new_elems[j] = array_ptrn->elems[j].get();
} else if (auto literal_ptrn = row.first[i]->isa<ast::LiteralPtrn>()) {
// This must be a string. In that case we need to create a literal
// pattern for each character.
assert(literal_ptrn->lit.is_string());
assert(literal_ptrn->lit.as_string().size() + 1 == member_count);
const char* str = literal_ptrn->lit.as_string().c_str();
for (size_t j = 0; j < member_count; ++j) {
auto char_ptrn = make_ptr<ast::LiteralPtrn>(literal_ptrn->loc, uint8_t(str[j]));
char_ptrn->type = type->type_table.prim_type(ast::PrimType::U8);
new_elems[j] = char_ptrn.get();
tmp_ptrns.emplace_back(std::move(char_ptrn));
}
} else {
matched_values.emplace(row.first[i]->as<ast::IdPtrn>(), values[i].first);
}
}
remove_col(row.first, i);
row.first.insert(row.first.end(), new_elems.begin(), new_elems.end());
}
// Expand the value to match against
std::vector<Value> new_values(member_count);
for (size_t j = 0; j < member_count; ++j) {
new_values[j].first = emitter.world.extract(values[i].first, j, emitter.debug_info(expr));
new_values[j].second = member_type(type, j);
}
remove_col(values, i);
values.insert(values.end(), new_values.begin(), new_values.end());
}
}
void compile() {
if (rows.empty())
return emitter.non_exhaustive_match(*node.as<ast::MatchExpr>());
expand();
if (std::all_of(
rows.front().first.begin(),
rows.front().first.end(),
[] (const ast::Ptrn* ptrn) {
return is_wildcard(ptrn);
}))
{
// If the first row is made of only wildcards, it is a match
rows.front().second->is_redundant = false;
for (size_t i = 0, n = rows.front().first.size(); i < n; ++i) {
auto ptrn = rows.front().first[i];
// Emit names that are bound in this row
if (ptrn && ptrn->isa<ast::IdPtrn>())
matched_values.emplace(ptrn->as<ast::IdPtrn>(), values[i].first);
}
auto case_block = rows.front().second->emit(emitter);
// Map the matched patterns to arguments of the continuation
auto& bound_ptrns = rows.front().second->bound_ptrns;
thorin::Array<const thorin::Def*> args(bound_ptrns.size());
for (size_t i = 0, n = bound_ptrns.size(); i < n; ++i)
args[i] = matched_values[bound_ptrns[i]];
emitter.jump(case_block, emitter.world.tuple(args));
return;
}
#ifndef NDEBUG
for (auto& row : rows)
assert(row.first.size() == values.size());
#endif
// Map from constructor index (e.g. literal or enumeration option index, encoded as an integer) to row.
std::unordered_map<const thorin::Def*, std::vector<Row>> ctors;
std::vector<Row> wildcards;
auto col = pick_col();
auto col_type = values[col].second;
auto [type_app, enum_type] = match_app<EnumType>(col_type);
// First, collect constructors
for (auto& row : rows) {
if (!is_wildcard(row.first[col]))
ctors.emplace(emitter.ctor_index(*row.first[col]), std::vector<Row>());
}
// Then, build the new rows for each constructor case
for (auto& row : rows) {
if (is_wildcard(row.first[col])) {
if (row.first[col])
matched_values.emplace(row.first[col]->as<ast::IdPtrn>(), values[col].first);
remove_col(row.first, col);
for (auto& [ctor_index, ctor_rows] : ctors) {
// Wildcard rows "fall" in all sub-trees
ctor_rows.push_back(row);
if (enum_type) {
auto index = thorin::primlit_value<uint64_t>(ctor_index);
// If the sub-tree introduces the extracted contents of an enum variant, add a dummy column to the row
if (!is_unit_type(enum_type->member_type(index)))
ctor_rows.back().first.push_back(nullptr);
}
}
wildcards.emplace_back(std::move(row));
} else {
auto ptrn = row.first[col];
remove_col(row.first, col);
if (auto call_ptrn = ptrn->isa<ast::CtorPtrn>(); call_ptrn && call_ptrn->arg) {
row.first.push_back(call_ptrn->arg.get());
} else if (auto record_ptrn = ptrn->isa<ast::RecordPtrn>()) {
// Since expansion uses the type of the value vector to know when to expand,
// the record pattern will be expanded in the next iteration.
row.first.push_back(record_ptrn);
}
ctors[emitter.ctor_index(*ptrn)].emplace_back(std::move(row));
}
}
// Generate jumps to each constructor case
bool no_default = is_complete(col_type, ctors.size());
if (is_bool_type(col_type)) {
auto match_true = emitter.basic_block(emitter.debug_info(node, "match_true"));
auto match_false = emitter.basic_block(emitter.debug_info(node, "match_false"));
emitter.branch(values[col].first, match_true, match_false);
remove_col(values, col);
for (auto& ctor : ctors) {
auto _ = emitter.save_state();
emitter.enter(thorin::is_allset(ctor.first) ? match_true : match_false);
PtrnCompiler(emitter, node, expr, std::move(ctor.second), std::vector<Value>(values), matched_values).compile();
}
if (!no_default) {
emitter.enter(thorin::is_allset(ctors.begin()->first) ? match_false : match_true);
PtrnCompiler(emitter, node, expr, std::move(wildcards), std::move(values), matched_values).compile();
}
} else {
assert(enum_type || is_int_type(col_type));
thorin::Array<thorin::Continuation*> targets(ctors.size());
thorin::Array<const thorin::Def*> defs(ctors.size());
auto otherwise = emitter.basic_block(emitter.debug_info(node, "match_otherwise"));
size_t count = 0;
for (auto& ctor : ctors) {
defs[count] = ctor.first;
targets[count] = emitter.basic_block(emitter.debug_info(node, "match_case"));
count++;
}
if (emitter.state.cont) {
auto match_value = enum_type
? emitter.world.variant_index(values[col].first, emitter.debug_info(node, "variant_index"))
: values[col].first;
emitter.state.cont->match(
match_value, otherwise,
no_default ? defs.skip_back() : defs.ref(),
no_default ? targets.skip_back() : targets.ref(),
emitter.debug_info(node));
}
auto col_value = values[col].first;
remove_col(values, col);
for (size_t i = 0, n = targets.size(); i < n; ++i) {
auto& rows = ctors[defs[i]];
auto _ = emitter.save_state();
emitter.enter(i == n - 1 && no_default ? otherwise : targets[i]);
auto new_values = values;
if (enum_type) {
auto index = thorin::primlit_value<uint64_t>(defs[i]);
auto type = member_type(col_type, index);
auto value = emitter.world.variant_extract(col_value, index);
// If the constructor refers to an option that has a parameter,
// we need to extract it and add it to the values.
if (!is_unit_type(type))
new_values.emplace_back(emitter.world.cast(type->convert(emitter), value), type);
}
PtrnCompiler(emitter, node, expr, std::move(rows), std::move(new_values), matched_values).compile();
}
if (!no_default) {
emitter.enter(otherwise);
PtrnCompiler(emitter, node, expr, std::move(wildcards), std::move(values), matched_values).compile();
}
}
}
#ifndef NDEBUG
void dump() const;
#endif
};
const thorin::Def* PtrnCompiler::MatchCase::emit(Emitter& emitter) {
if (!cont) {
thorin::Array<const thorin::Type*> param_types(bound_ptrns.size());
for (size_t i = 0, n = bound_ptrns.size(); i < n; ++i)
param_types[i] = bound_ptrns[i]->type->convert(emitter);
cont = emitter.basic_block_with_mem(emitter.world.tuple_type(param_types), emitter.debug_info(*node, "case_body"));
auto _ = emitter.save_state();
emitter.enter(cont);
auto tuple = emitter.tuple_from_params(cont);
for (size_t i = 0, n = bound_ptrns.size(); i < n; ++i)
emitter.bind(*bound_ptrns[i], n == 1 ? tuple : emitter.world.extract(tuple, i));
emitter.jump(target, emitter.emit(*expr), emitter.debug_info(*node));
}
return cont;
}
void PtrnCompiler::emit(
Emitter& emitter,
const ast::Node& node,
const ast::Expr& expr,
std::vector<MatchCase>&& cases,
std::unordered_map<const ast::IdPtrn*, const thorin::Def*>&& matched_values)
{
auto rows = std::vector<PtrnCompiler::Row>();
for (auto& case_ : cases)
rows.emplace_back(std::vector<const ast::Ptrn*>{ case_.ptrn }, &case_);
std::vector<PtrnCompiler::Value> values = { { emitter.emit(expr), expr.type } };
auto compiler = PtrnCompiler(emitter, node, expr, std::move(rows), std::move(values), matched_values);
compiler.compile();
for (auto &row : compiler.rows) {
if (row.second->is_redundant)
compiler.emitter.redundant_case(*row.second->node->as<ast::CaseExpr>());
}
}
// Since this code is used for debugging only, it makes sense to hide it in
// the coverage report. This is done using these START/STOP markers.
#ifndef NDEBUG // GCOV_EXCL_START
void PtrnCompiler::dump() const {
Printer p(log::out);
p << "match ";
for (auto& value : values)
p.out << value.first << ' ';
p << '{' << p.indent() << p.endl();
for (size_t i = 0, n = rows.size(); i < n; ++i) {
auto& row = rows[i];
for (auto& elem : row.first) {
if (elem)
elem->print(p);
else
p << '_';
p << ' ';
}
p << "=> ";
row.second->expr->print(p);
if (i != n - 1)
p << ',' << p.endl();
}
p << p.unindent() << p.endl();
p << '}' << p.endl();
p << "(matched: " << p.indent();
for (auto& pair : matched_values) {
p << p.endl();
pair.first->print(p);
p << " = ";
p.out << pair.second;
}
p << ')' << p.unindent() << p.endl();
}
#endif // GCOV_EXCL_STOP
bool Emitter::run(const ast::ModDecl& mod) {
mod.emit(*this);
return errors == 0;
}
thorin::Continuation* Emitter::basic_block(thorin::Debug debug) {
return world.continuation(world.fn_type(), debug);
}
thorin::Continuation* Emitter::basic_block_with_mem(thorin::Debug debug) {
return world.continuation(world.fn_type({ world.mem_type() }), debug);
}
thorin::Continuation* Emitter::basic_block_with_mem(const thorin::Type* param, thorin::Debug debug) {
return world.continuation(continuation_type_with_mem(param), debug);
}
const thorin::Def* Emitter::ctor_index(const ast::Ptrn& ptrn) {
if (auto record_ptrn = ptrn.isa<ast::RecordPtrn>())
return ctor_index(record_ptrn->variant_index, debug_info(ptrn));
return ptrn.isa<ast::LiteralPtrn>()
? emit(ptrn, ptrn.as<ast::LiteralPtrn>()->lit)
: ctor_index(ptrn.as<ast::CtorPtrn>()->variant_index, debug_info(ptrn));
}
const thorin::Def* Emitter::ctor_index(size_t index, thorin::Debug debug) {
return world.literal_qu64(index, debug);
}
void Emitter::redundant_case(const ast::CaseExpr& case_) {
error(case_.loc, "redundant match case");
}
void Emitter::non_exhaustive_match(const ast::MatchExpr& match) {
error(match.loc, "non exhaustive match expression");
}
const thorin::FnType* Emitter::continuation_type_with_mem(const thorin::Type* from) {
if (auto tuple_type = from->isa<thorin::TupleType>()) {
thorin::Array<const thorin::Type*> types(1 + tuple_type->num_ops());
types[0] = world.mem_type();
for (size_t i = 0, n = tuple_type->num_ops(); i < n; ++i)
types[i + 1] = tuple_type->op(i);
return world.fn_type(types);
} else
return world.fn_type({ world.mem_type(), from });
}
const thorin::FnType* Emitter::function_type_with_mem(const thorin::Type* from, const thorin::Type* to) {
// Flatten one level of tuples in the domain and codomain:
// If the input is `fn (i32, i64) -> (f32, f64)`, we produce the
// thorin type `fn (mem, i32, i64, fn (mem, f32, f64))`.
if (auto tuple_type = from->isa<thorin::TupleType>()) {
thorin::Array<const thorin::Type*> types(2 + tuple_type->num_ops());
types[0] = world.mem_type();
for (size_t i = 0, n = tuple_type->num_ops(); i < n; ++i)
types[i + 1] = tuple_type->op(i);
types.back() = continuation_type_with_mem(to);
return world.fn_type(types);
} else
return world.fn_type({ world.mem_type(), from, continuation_type_with_mem(to) });
}
const thorin::Def* Emitter::tuple_from_params(thorin::Continuation* cont, bool ret) {
// One level of tuples is flattened when emitting functions.
// Here, we recreate that tuple from individual parameters.
if (cont->num_params() == (ret ? 3 : 2))
return cont->param(1);
thorin::Array<const thorin::Def*> ops(cont->num_params() - (ret ? 2 : 1));
for (size_t i = 0, n = ops.size(); i < n; ++i)
ops[i] = cont->param(i + 1);
return world.tuple(ops);
}
std::vector<const thorin::Def*> Emitter::call_args(
const thorin::Def* mem,
const thorin::Def* arg,
const thorin::Def* cont)
{
// Create a list of operands for a call to a function/continuation
std::vector<const thorin::Def*> ops;
ops.push_back(mem);
if (auto tuple_type = arg->type()->isa<thorin::TupleType>()) {
for (size_t i = 0, n = tuple_type->num_ops(); i < n; ++i)
ops.push_back(world.extract(arg, i));
} else
ops.push_back(arg);
if (cont)
ops.push_back(cont);
return ops;
}
void Emitter::enter(thorin::Continuation* cont) {
state.cont = cont;
if (cont->num_params() > 0)
state.mem = cont->param(0);
}
void Emitter::jump(const thorin::Def* callee, thorin::Debug debug) {
if (!state.cont)
return;
auto num_params = callee->type()->as<thorin::FnType>()->num_ops();
if (num_params == 1) {
state.cont->jump(callee, { state.mem }, debug);
} else {
assert(num_params == 0);
state.cont->jump(callee, {}, debug);
}
state.cont = nullptr;
}
void Emitter::jump(const thorin::Def* callee, const thorin::Def* arg, thorin::Debug debug) {
if (!state.cont)
return;
state.cont->jump(callee, call_args(state.mem, arg), debug);
state.cont = nullptr;
}
const thorin::Def* Emitter::call(const thorin::Def* callee, const thorin::Def* arg, thorin::Debug debug) {
if (!state.cont)
return nullptr;
auto cont_type = callee->type()->as<thorin::FnType>()->ops().back()->as<thorin::FnType>();
auto cont = world.continuation(cont_type, thorin::Debug("cont"));
return call(callee, arg, cont, debug);
}
const thorin::Def* Emitter::call(
const thorin::Def* callee,
const thorin::Def* arg,
thorin::Continuation* cont,
thorin::Debug debug)
{
if (!state.cont)
return nullptr;
state.cont->jump(callee, call_args(state.mem, arg, cont), debug);
enter(cont);
return tuple_from_params(cont);
}
void Emitter::branch(
const thorin::Def* cond,
const thorin::Def* branch_true,
const thorin::Def* branch_false,
thorin::Debug debug)
{
if (!state.cont)
return;
state.cont->branch(cond, branch_true, branch_false, debug);
state.cont = nullptr;
}
void Emitter::branch_with_mem(
const thorin::Def* cond,
const thorin::Def* branch_true_with_mem,
const thorin::Def* branch_false_with_mem,
thorin::Debug debug)
{
if (!state.cont)
return;
auto branch_true = basic_block(thorin::Debug { "branch_true" });
auto branch_false = basic_block(thorin::Debug { "branch_false" });
branch(cond, branch_true, branch_false, debug);
enter(branch_true);
jump(branch_true_with_mem);
enter(branch_false);
jump(branch_false_with_mem);
}
const thorin::Def* Emitter::alloc(const thorin::Type* type, thorin::Debug debug) {
assert(state.mem);
auto pair = world.enter(state.mem);
state.mem = world.extract(pair, thorin::u32(0));
return world.slot(type, world.extract(pair, thorin::u32(1)), debug);
}
void Emitter::store(const thorin::Def* ptr, const thorin::Def* value, thorin::Debug debug) {
assert(state.mem);
state.mem = world.store(state.mem, ptr, value, debug);
}
const thorin::Def* Emitter::load(const thorin::Def* ptr, thorin::Debug debug) {
// Allow loads from globals at the top level (where `state.mem` is null)
if (auto global = ptr->isa<thorin::Global>(); global && !global->is_mutable())
return global->init();
assert(state.mem);
auto pair = world.load(state.mem, ptr, debug);
state.mem = world.extract(pair, thorin::u32(0));
return world.extract(pair, thorin::u32(1));
}
const thorin::Def* Emitter::addr_of(const thorin::Def* def, thorin::Debug debug) {
if (!def->has_dep(thorin::Dep::Param)) {
return world.global(def, false, debug);
} else {
auto ptr = alloc(def->type(), debug);
store(ptr, def, debug);
return ptr;
}
}
const thorin::Def* Emitter::no_ret() {
// Thorin does not have a type that can encode a no-return type,
// so we return an empty tuple instead.
return world.bottom(world.unit());
}
static inline bool is_compatible(const Type* from, const Type* to) {
// This function allows casting &[&[i32 * 4] * 5] directly to `&[&[i32]]`,
// without loading the pointer and extracting each individual elements.
if (from == to)
return true;
auto from_addr_type = from->isa<AddrType>();
auto to_addr_type = to->isa<AddrType>();
if (from_addr_type && to_addr_type && from_addr_type->addr_space == to_addr_type->addr_space) {
auto from_array_type = from_addr_type->pointee->isa<ArrayType>();
auto to_array_type = to_addr_type->pointee->isa<ArrayType>();
if (from_array_type && to_array_type)
return is_compatible(from_array_type->elem, to_array_type->elem);
return is_compatible(from_addr_type->pointee, to_addr_type->pointee);
}
return false;
}
const thorin::Def* Emitter::cast_pointers(
const thorin::Def* def,
const AddrType* from_addr_type,
const AddrType* to_addr_type,
thorin::Debug debug)
{
const thorin::Def* addr = def;
if (!is_compatible(from_addr_type, to_addr_type)) {
// We have to downcast the value pointed at
assert(from_addr_type->pointee->subtype(to_addr_type->pointee));
auto casted_val = down_cast(load(def, debug), from_addr_type->pointee, to_addr_type->pointee, debug);
addr = addr_of(casted_val, debug);
}
return world.bitcast(to_addr_type->convert(*this), addr, debug);
}
const thorin::Def* Emitter::down_cast(const thorin::Def* def, const Type* from, const Type* to, thorin::Debug debug) {
// This function mirrors the subtyping relation and thus should be kept in sync
assert(from->subtype(to));
if (to == from || to->isa<TopType>())
return def;
if (from->isa<BottomType>())
return world.bottom(to->convert(*this));
auto to_ptr_type = to->isa<PtrType>();
// Casting a value to a pointer to the type of the value effectively creates an allocation
if (to_ptr_type &&
!to_ptr_type->is_mut &&
to_ptr_type->addr_space == 0 &&
from->subtype(to_ptr_type->pointee))
return world.bitcast(to->convert(*this), addr_of(down_cast(def, from, to_ptr_type->pointee, debug)), debug);
if (auto from_ref_type = from->isa<RefType>()) {
if (to_ptr_type && from_ref_type->is_compatible_with(to_ptr_type) && from_ref_type->pointee->subtype(to_ptr_type->pointee))
return cast_pointers(def, from_ref_type, to_ptr_type, debug);
return down_cast(load(def, debug), from_ref_type->pointee, to, debug);
} else if (auto from_ptr_type = from->isa<PtrType>(); from_ptr_type && to_ptr_type) {
assert(from_ptr_type->is_compatible_with(to_ptr_type));
return cast_pointers(def, from_ptr_type, to_ptr_type, debug);
} else if (auto from_sized_array_type = from->isa<SizedArrayType>()) {
// Here, the returned value does not have the target type (it is a definite array instead
// of an indefinite one). This is because Thorin does not have indefinite array values.
// However, this is not important since indefinite arrays can only be used with pointers,
// and we always emit bitcasts when down-casting those.
auto to_elem = to->as<ArrayType>()->elem;
thorin::Array<const thorin::Def*> elems(from_sized_array_type->size);
for (size_t i = 0, n = from_sized_array_type->size; i < n; ++i)
elems[i] = down_cast(world.extract(def, i), from_sized_array_type->elem, to_elem, debug);
return world.definite_array(to_elem->convert(*this), elems, debug);
} else if (auto from_tuple_type = from->isa<TupleType>()) {
thorin::Array<const thorin::Def*> ops(from_tuple_type->args.size());
for (size_t i = 0, n = ops.size(); i < n; ++i)
ops[i] = down_cast(world.extract(def, i, debug), from_tuple_type->args[i], to->as<TupleType>()->args[i], debug);
return world.tuple(ops, debug);
} else if (auto from_fn_type = from->isa<FnType>()) {
auto _ = save_state();
auto cont = world.continuation(to->convert(*this)->as<thorin::FnType>(), debug);
enter(cont);
auto param = down_cast(tuple_from_params(cont, true), to->as<FnType>()->dom, from_fn_type->dom, debug);
// No-ret functions downcast to returning ones, but call() can't work with those (see also CallExpr, IfExpr)
if (from->as<FnType>()->codom->isa<artic::NoRetType>()) {
jump(def, param, debug);
} else {
auto value = down_cast(call(def, param, debug), from_fn_type->codom, to->as<FnType>()->codom, debug);
jump(cont->params().back(), value, debug);
}
return cont;
}
assert(false);
return def;
}
const thorin::Def* Emitter::emit(const ast::Node& node) {
if (node.def)
return node.def;
if (!poly_defs.empty())
poly_defs.back().push_back(&node.def);
return node.def = node.emit(*this);
}
void Emitter::emit(const ast::Ptrn& ptrn, const thorin::Def* value) {
assert(!ptrn.def);
ptrn.emit(*this, value);
}
void Emitter::bind(const ast::IdPtrn& id_ptrn, const thorin::Def* value) {
if (id_ptrn.decl->is_mut) {
auto ptr = alloc(value->type(), debug_info(*id_ptrn.decl));
store(ptr, value);
id_ptrn.decl->def = ptr;
if (!id_ptrn.decl->written_to)
warn(id_ptrn.loc, "mutable variable '{}' is never written to", id_ptrn.decl->id.name);
} else {
id_ptrn.decl->def = value;
value->set_name(id_ptrn.decl->id.name);
}
assert(id_ptrn.type->convert(*this) == value->type());
}
const thorin::Def* Emitter::emit(const ast::Node& node, const Literal& lit) {
if (auto prim_type = node.type->isa<artic::PrimType>()) {
switch (prim_type->tag) {
case ast::PrimType::Bool: return world.literal_bool(lit.as_bool(), debug_info(node));
case ast::PrimType::U8: return world.literal_pu8 (lit.is_integer() ? lit.as_integer() : lit.as_char(), debug_info(node));
case ast::PrimType::U16: return world.literal_pu16(lit.as_integer(), debug_info(node));
case ast::PrimType::U32: return world.literal_pu32(lit.as_integer(), debug_info(node));
case ast::PrimType::U64: return world.literal_pu64(lit.as_integer(), debug_info(node));
case ast::PrimType::I8: return world.literal_qs8 (lit.as_integer(), debug_info(node));
case ast::PrimType::I16: return world.literal_qs16(lit.as_integer(), debug_info(node));
case ast::PrimType::I32: return world.literal_qs32(lit.as_integer(), debug_info(node));
case ast::PrimType::I64: return world.literal_qs64(lit.as_integer(), debug_info(node));
case ast::PrimType::F16:
return world.literal_qf16(thorin::half(lit.is_double() ? lit.as_double() : lit.as_integer()), debug_info(node));
case ast::PrimType::F32:
return world.literal_qf32(lit.is_double() ? lit.as_double() : lit.as_integer(), debug_info(node));
case ast::PrimType::F64:
return world.literal_qf64(lit.is_double() ? lit.as_double() : lit.as_integer(), debug_info(node));
default:
assert(false);
return nullptr;
}
} else {
assert(lit.is_string());
thorin::Array<const thorin::Def*> ops(lit.as_string().size() + 1);
for (size_t i = 0, n = lit.as_string().size(); i < n; ++i)
ops[i] = world.literal_pu8(lit.as_string()[i], {});
ops.back() = world.literal_pu8(0, {});
return world.definite_array(ops, debug_info(node));
}
}
// Note: The following functions assume IEEE-754 representation for floating-point numbers.
template <typename T, std::enable_if_t<std::is_unsigned_v<T>, int> = 0>
static inline T bitmask(size_t first_bit, size_t last_bit) {
return (T(-1) >> (sizeof(T) * CHAR_BIT - (last_bit - first_bit))) << first_bit;
}
static inline const thorin::Def* mantissa_mask(thorin::World& world, const thorin::Type* type, thorin::Debug dbg = {}) {
switch (num_bits(type->as<thorin::PrimType>()->primtype_tag())) {
case 16: return world.literal_pu16(bitmask<uint16_t>(0, 10), dbg);
case 32: return world.literal_pu32(bitmask<uint32_t>(0, 23), dbg);
case 64: return world.literal_pu64(bitmask<uint64_t>(0, 52), dbg);
default:
assert(false);
return nullptr;
}
}
static inline const thorin::Def* exponent_mask(thorin::World& world, const thorin::Type* type, thorin::Debug dbg = {}) {
switch (num_bits(type->as<thorin::PrimType>()->primtype_tag())) {
case 16: return world.literal_pu16(bitmask<uint16_t>(10, 15), dbg);
case 32: return world.literal_pu32(bitmask<uint32_t>(23, 31), dbg);
case 64: return world.literal_pu64(bitmask<uint64_t>(52, 63), dbg);
default:
assert(false);
return nullptr;
}
}
static inline const thorin::Def* sign_mask(thorin::World& world, const thorin::Type* type, thorin::Debug dbg = {}) {
switch (num_bits(type->as<thorin::PrimType>()->primtype_tag())) {
case 16: return world.literal_pu16(bitmask<uint16_t>(15, 16), dbg);
case 32: return world.literal_pu32(bitmask<uint32_t>(31, 32), dbg);
case 64: return world.literal_pu64(bitmask<uint64_t>(63, 64), dbg);
default:
assert(false);
return nullptr;
}
}
static inline const thorin::Def* signbit(const thorin::Def* val) {
auto& world = val->world();
auto sign_mask = artic::sign_mask(world, val->type());
auto uint_val = world.bitcast(sign_mask->type(), val);
auto sign = world.arithop_and(uint_val, sign_mask);
return world.cmp_ne(sign, world.zero(uint_val->type()));
}
static inline const thorin::Def* isnan(const thorin::Def* val) {
auto& world = val->world();
auto exponent_mask = artic::exponent_mask(world, val->type());
auto mantissa_mask = artic::mantissa_mask(world, val->type());
auto uint_val = world.bitcast(exponent_mask->type(), val);
auto exponent = world.arithop_and(uint_val, exponent_mask);
auto mantissa = world.arithop_and(uint_val, mantissa_mask);
return world.arithop_and(
world.cmp_eq(exponent, exponent_mask), // The exponent must be all 1s
world.cmp_ne(mantissa, world.zero(uint_val->type()))); // The mantissa must be non-zero
}
static inline const thorin::Def* isfinite(const thorin::Def* val) {
auto& world = val->world();
auto exponent_mask = artic::exponent_mask(world, val->type());
auto uint_val = world.bitcast(exponent_mask->type(), val);
auto exponent = world.arithop_and(uint_val, exponent_mask);
return world.cmp_ne(exponent, exponent_mask); // The exponent must not be all 1s
}
const thorin::Def* Emitter::builtin(const ast::FnDecl& fn_decl, thorin::Continuation* cont) {
if (cont->name() == "alignof") {
auto target_type = fn_decl.type_params->params[0]->type->convert(*this);
cont->jump(cont->params().back(), { cont->param(0), world.align_of(target_type) }, debug_info(fn_decl));
} else if (cont->name() == "bitcast") {
auto param = tuple_from_params(cont, true);
auto target_type = fn_decl.type->as<ForallType>()->body->as<FnType>()->codom->convert(*this);
cont->jump(cont->params().back(), call_args(cont->param(0), world.bitcast(target_type, param)), debug_info(fn_decl));
} else if (cont->name() == "insert") {
cont->jump(
cont->params().back(),
call_args(cont->param(0), world.insert(cont->param(1), cont->param(2), cont->param(3))),
debug_info(fn_decl));
} else if (cont->name() == "select") {
cont->jump(
cont->params().back(),
call_args(cont->param(0), world.select(cont->param(1), cont->param(2), cont->param(3))),
debug_info(fn_decl));
} else if (cont->name() == "sizeof") {
auto target_type = fn_decl.type_params->params[0]->type->convert(*this);
cont->jump(cont->params().back(), { cont->param(0), world.size_of(target_type) }, debug_info(fn_decl));
} else if (cont->name() == "undef") {
auto target_type = fn_decl.type_params->params[0]->type->convert(*this);
cont->jump(cont->params().back(), call_args(cont->param(0), world.bottom(target_type)), debug_info(fn_decl));
} else if (cont->name() == "compare") {
enter(cont);
auto mono_type = member_type(fn_decl.fn->param->type->replace(type_vars), 1)->as<PtrType>()->pointee;
auto ret_val = call(comparator(fn_decl.loc, mono_type), tuple_from_params(cont, true));
jump(cont->params().back(), ret_val);
} else {
static const std::unordered_map<std::string, std::function<const thorin::Def* (Emitter*, const thorin::Continuation*)>> functions = {
{ "fabs", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.fabs(cont->param(1)); } },
{ "copysign", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.copysign(cont->param(1), cont->param(2)); } },
{ "signbit", [] (Emitter* , const thorin::Continuation* cont) { return signbit(cont->param(1)); } },
{ "round", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.round(cont->param(1)); } },
{ "ceil", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.ceil(cont->param(1)); } },
{ "floor", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.floor(cont->param(1)); } },
{ "fmin", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.fmin(cont->param(1), cont->param(2)); } },
{ "fmax", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.fmax(cont->param(1), cont->param(2)); } },
{ "cos", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.cos(cont->param(1)); } },
{ "sin", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.sin(cont->param(1)); } },
{ "tan", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.tan(cont->param(1)); } },
{ "acos", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.acos(cont->param(1)); } },
{ "asin", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.asin(cont->param(1)); } },
{ "atan", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.atan(cont->param(1)); } },
{ "atan2", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.atan2(cont->param(1), cont->param(2)); } },
{ "sqrt", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.sqrt(cont->param(1)); } },
{ "cbrt", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.cbrt(cont->param(1)); } },
{ "pow", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.pow(cont->param(1), cont->param(2)); } },
{ "exp", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.exp(cont->param(1)); } },
{ "exp2", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.exp2(cont->param(1)); } },
{ "log", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.log(cont->param(1)); } },
{ "log2", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.log2(cont->param(1)); } },
{ "log10", [] (Emitter* self, const thorin::Continuation* cont) { return self->world.log10(cont->param(1)); } },
{ "isnan", [] (Emitter* , const thorin::Continuation* cont) { return isnan(cont->param(1)); } },
{ "isfinite", [] (Emitter* , const thorin::Continuation* cont) { return isfinite(cont->param(1)); } },
};
assert(functions.count(cont->name()) > 0);
enter(cont);
jump(cont->params().back(), functions.at(cont->name())(this, cont));
}
cont->set_filter(cont->all_true_filter());
return cont;
}
const thorin::Def* Emitter::comparator(const Loc& loc, const Type* type) {
if (auto it = comparators.find(type); it != comparators.end())
return it->second;
auto converted_type = type->convert(*this);
auto operand_type = world.ptr_type(converted_type);
auto comparator_type = function_type_with_mem(
world.tuple_type({ operand_type, operand_type }), world.type_bool());
auto comparator_fn = world.continuation(comparator_type);
auto _ = save_state();
enter(comparator_fn);
auto left = static_cast<const thorin::Def*>(comparator_fn->param(1));
auto right = static_cast<const thorin::Def*>(comparator_fn->param(2));
auto ret = comparator_fn->param(3);
switch (converted_type->tag()) {
#define THORIN_ALL_TYPE(T, M) case thorin::Node_PrimType_##T:
#include <thorin/tables/primtypetable.h>
case thorin::Node_PtrType:
jump(ret, world.cmp_eq(load(left), load(right)));
break;
case thorin::Node_TupleType:
case thorin::Node_StructType: {
auto branch_false = basic_block_with_mem();
for (size_t i = 0, n = converted_type->num_ops(); i < n; ++i) {
auto branch_true = basic_block_with_mem();
auto index = world.literal_qu64(i, {});
auto is_eq = call(comparator(loc, member_type(type, i)),
world.tuple({ world.lea(left, index, {}), world.lea(right, index, {}) }));
branch_with_mem(is_eq, branch_true, branch_false);
enter(branch_true);
}
jump(ret, world.literal_bool(true, {}));
enter(branch_false);
jump(ret, world.literal_bool(false, {}));
break;
}
case thorin::Node_VariantType: {
// TODO: Change thorin to be able to extract the address of the index,
// along with the address of the contained object, instead of always loading it.
left = load(left);
right = load(right);
auto is_eq = world.cmp_eq(world.variant_index(left), world.variant_index(right));
auto branch_false = basic_block();
auto branch_true = basic_block();
branch(is_eq, branch_true, branch_false);
enter(branch_false);
jump(ret, world.literal_bool(false, {}));
enter(branch_true);
// Optimisation: When all the operands of the variant carry no payload,
// just compare the tags.
if (!match_app<EnumType>(type).second->is_trivial()) {
thorin::Array<thorin::Continuation*> targets(
converted_type->num_ops() - 1, [&] (auto) { return basic_block(); });
thorin::Array<const thorin::Def*> defs(