Repository navigation
Expand file tree
/
Copy pathallocation.cpp
More file actions
1568 lines (1526 loc) · 60.4 KB
/
Copy pathallocation.cpp
File metadata and controls
1568 lines (1526 loc) · 60.4 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 "aarch64/selector.h"
#include "aarch64/lifetimes.h"
#include "opt/function_ir.h"
#include "opt/loops.h"
#include "machine/frame_lifetimes.h"
#include "machine/interval_slots.h"
#include "machine/register_pressure.h"
#include "machine/shrink_region.h"
#include <algorithm>
#include <cmath>
namespace aarch64 {
using namespace lowir;
namespace {
using Segments = std::vector<std::pair<uint32_t, uint32_t>>;
constexpr uint32_t kPreservedSimd = 0xffu << 8;
template<typename F>
void each_interval(const LiveRange& range, const Segments& segments, F f)
{
if (!range.count)
f(range.first, range.last);
else
for (uint32_t i = range.segments; i < range.segments + range.count; ++i)
f(segments[i].first, segments[i].second);
}
enum class RegisterPressure
{
Fits,
AcrossCalls,
Saturated
};
bool uses_simd(const FunctionBody& body, const LiveRange& range)
{
const auto kind = body.temps[range.id].type.kind();
return kind == TypeKind::F32 || kind == TypeKind::F64 || (kind == TypeKind::V128 && !range.vector_address);
}
// Count values that are definitely live at the same time. Half-open
// segments omit values dying at a call and its newly defined result.
RegisterPressure register_pressure(const FunctionBody& body, const std::vector<LiveRange>& ranges,
const Segments& segments, const std::vector<uint32_t>& calls, uint32_t slots, int preserved, Bank bank)
{
if (segments.empty() || ranges.size() <= static_cast<unsigned>(preserved))
return RegisterPressure::Fits;
const bool simd = bank == Bank::Simd;
const auto belongs = [&](const LiveRange& range) {
const auto type = body.temps[range.id].type;
return range.first != kNoId &&
(simd ? uses_simd(body, range)
: type.is_pointer() || (type.is_integer() && integer_bits(type.kind()) <= 64));
};
if (simd && std::count_if(ranges.begin(), ranges.end(), belongs) <= preserved)
return RegisterPressure::Fits;
std::vector<int32_t> change(slots + 1);
for (const auto& range : ranges)
{
if (!belongs(range))
continue;
each_interval(range, segments, [&](uint32_t first, uint32_t last) {
++change[first];
--change[last];
});
}
uint32_t next = 0;
int live = 0;
bool across_calls = false;
const int capacity = preserved + (simd ? 22 : 11);
for (uint32_t slot = 0; slot < slots; ++slot)
{
live += change[slot];
if (live > capacity)
return RegisterPressure::Saturated;
if (next < calls.size() && calls[next] == slot)
{
if (live > preserved)
{
if (!simd)
return RegisterPressure::AcrossCalls;
across_calls = true;
}
++next;
}
}
return across_calls ? RegisterPressure::AcrossCalls : RegisterPressure::Fits;
}
// The factor of a range of `slots` read/write slots against the reference range.
double length_factor(uint32_t slots)
{
constexpr double reference_length = 1024; // Read/write slots in the reference range.
return std::sqrt(reference_length / std::max(1u, slots));
}
// In a saturated SIMD bank, one long range can force many short arithmetic
// results into integer registers. Discount long ranges while retaining
// the block frequency and use counts in the ordinary spill weights.
double simd_spill_priority(const FunctionBody& body, const LiveRange& range, const Segments& segments, uint64_t weight)
{
if (range.first == kNoId || !uses_simd(body, range))
return static_cast<double>(weight);
uint32_t slots = 0;
each_interval(range, segments, [&](uint32_t first, uint32_t last) { slots += last - first; });
return static_cast<double>(weight) * length_factor(slots);
}
// In a saturated general bank, the spill-weight order can leave a short
// range no register where the heavier long ranges already fill the bank, so
// each of many short results pays a store and a reload on its own chain
// although one register would hold them in turn. Such a range takes the
// SIMD bank's discounted priority, which puts it before the long ranges it
// meets: a short integer or address range (at most `short_length` slots)
// that would find no register in a model of the order. In the model a range
// holds a register where fewer than `assignable` ranges before it hold one,
// and, crossing a call, fewer than `preserved` crossing ranges. A phi's or a
// move's partner keeps its place, where it shares its partner's register.
// Returns whether a range was raised.
bool raise_crowded_short_ranges(const FunctionBody& body, const std::vector<uint32_t>& aliases,
const std::vector<LiveRange>& ranges, const Segments& segments, const std::vector<uint32_t>& calls, uint32_t slots,
int32_t assignable, int32_t preserved, const std::vector<uint32_t>& order, std::vector<double>& priority)
{
constexpr uint32_t short_length = 16;
std::vector<uint8_t> partner(body.temps.size(), 0);
for (BlockId b : body.layout)
for (InstId i = body.blocks[b].first; i != kNoId; i = body.instructions[i].next)
{
const auto& inst = body.instructions[i];
if ((inst.op == Opcode::Copy || inst.op == Opcode::Convert) && inst.result != kNoId &&
inst.ops[0].is(ValueKind::Temp))
{
partner[representative(aliases, inst.result)] = 1;
partner[representative(aliases, inst.ops[0].index)] = 1;
}
}
machine::PressureTree held, crossing;
bool raised = false;
held.build(std::vector<int32_t>(slots + 1, 0));
crossing.build(std::vector<int32_t>(slots + 1, 0));
for (uint32_t index : order)
{
const auto& range = ranges[index];
const auto type = body.temps[range.id].type;
if (range.first == kNoId || !(type.is_pointer() || (type.is_integer() && integer_bits(type.kind()) <= 64)))
continue;
uint32_t length = 0;
int32_t most = 0, most_crossing = 0;
bool across = false;
each_interval(range, segments, [&](uint32_t first, uint32_t last) {
length += last - first;
most = std::max(most, held.max(first, last));
const auto call = std::lower_bound(calls.begin(), calls.end(), first);
across |= call != calls.end() && *call < last;
});
if (across)
each_interval(range, segments, [&](uint32_t first, uint32_t last) {
most_crossing = std::max(most_crossing, crossing.max(first, last));
});
if (most < assignable && (!across || most_crossing < preserved))
{
each_interval(range, segments, [&](uint32_t first, uint32_t last) {
held.add(first, last, 1);
if (across)
crossing.add(first, last, 1);
});
}
else if (length <= short_length && range.affinity == kNoId && !partner[range.id])
{
priority[index] *= length_factor(length);
raised = true;
}
}
return raised;
}
// Let each scalar phi web's call-crossing members choose before its other
// members. Otherwise a hot join can reserve a caller register the crossing
// members cannot use, leaving transfers on its incoming edges and backedge.
// With spill priorities, a crossing member takes the priority of the web's
// heaviest other member when that is higher, so a cold web still leaves the
// preserved registers to hotter values. Without them, the crossing members
// simply choose first.
void prioritize_call_webs(const FunctionBody& body, const std::vector<LiveRange>& ranges, const Segments& segments,
const std::vector<uint32_t>& calls, machine::PhiWebs& webs, const std::vector<double>& priority,
std::vector<uint32_t>& order)
{
std::vector<uint8_t> constrained(ranges.size());
for (uint32_t index : order)
{
const auto& range = ranges[index];
const auto type = body.temps[range.id].type;
if (range.affinity == kNoId ||
!(type.kind() == TypeKind::F32 || type.kind() == TypeKind::F64 || type.is_pointer() ||
(type.is_integer() && integer_bits(type.kind()) <= 64)))
continue;
each_interval(range, segments, [&](uint32_t first, uint32_t last) {
const auto call = std::lower_bound(calls.begin(), calls.end(), first);
constrained[index] |= call != calls.end() && *call < last;
});
}
if (priority.empty())
{
std::stable_partition(order.begin(), order.end(), [&](uint32_t index) { return constrained[index]; });
return;
}
std::vector<double> heaviest(body.temps.size(), 0.0), key(priority);
for (uint32_t index : order)
if (ranges[index].affinity != kNoId && !constrained[index])
{
auto& web = heaviest[webs.root(ranges[index].id)];
web = std::max(web, priority[index]);
}
for (uint32_t index : order)
if (constrained[index])
key[index] = std::max(key[index], heaviest[webs.root(ranges[index].id)]);
std::stable_sort(order.begin(), order.end(),
[&](uint32_t a, uint32_t b) { return key[a] != key[b] ? key[a] > key[b] : constrained[a] > constrained[b]; });
}
// Give scalar SIMD phis and their backedge values first choice over short
// intermediates. Their shared web preference can then eliminate a transfer
// cycle on each iteration. When one header's phis alone outnumber the SIMD
// registers (v0-v15, v18-v31), some of them spill anyway, and a value read
// more often than any of them (by spill weight) keeps its place.
void prioritize_loop_webs(const FunctionBody& body, const opt::Cfg& cfg, const std::vector<LiveRange>& ranges,
const std::vector<uint32_t>& aliases, const std::vector<uint64_t>& weight, std::vector<uint32_t>& order)
{
if (cfg.rpo_index.empty())
return;
std::vector<uint8_t> carried;
uint32_t phis = 0;
for (BlockId b : body.layout)
{
if (cfg.rpo_index[b] == kNoId)
continue;
uint32_t here = 0;
for (InstId i = body.blocks[b].first; i != kNoId && body.instructions[i].op == Opcode::Phi;
i = body.instructions[i].next)
{
const auto& phi = body.instructions[i];
if (phi.type.kind() != TypeKind::F32 && phi.type.kind() != TypeKind::F64)
continue;
for (unsigned k = 0; k < phi.extra_count; k += 2)
{
const BlockId pred = body.operands[phi.extra_first + k].index;
const Value incoming = body.operands[phi.extra_first + k + 1];
const uint32_t from = cfg.rpo_index[pred];
if (!incoming.is(ValueKind::Temp) || from == kNoId || from < cfg.rpo_index[b])
continue;
if (carried.empty())
carried.assign(body.temps.size(), 0);
here += !carried[phi.result];
carried[phi.result] = 1;
carried[representative(aliases, incoming.index)] = 1;
}
}
phis = std::max(phis, here);
}
if (carried.empty())
return;
if (order.empty())
{
order.resize(ranges.size());
for (uint32_t i = 0; i < order.size(); ++i)
order[i] = i;
}
uint64_t top = 0;
const bool crowded = !weight.empty() && phis > 30;
if (crowded)
for (const auto& range : ranges)
if (range.first != kNoId && carried[range.id])
top = std::max(top, weight[range.id]);
std::stable_partition(order.begin(), order.end(), [&](uint32_t i) {
const auto id = ranges[i].id;
return carried[id] || (crowded && weight[id] > top);
});
}
// A guarded call that cannot repeat has a path to a return on which
// preserving its live registers would be unnecessary.
bool guarded_call(const FunctionBody& body, const opt::Cfg& cfg, BlockId site)
{
if (cfg.succ_first.empty() || body.layout.size() < 3 || body.layout.size() > 96 || site == body.layout.front())
return false;
std::vector<uint8_t> seen(body.blocks.size());
std::vector<BlockId> pending;
auto successors = [&](BlockId b) {
pending.insert(pending.end(), cfg.succs.begin() + cfg.succ_first[b], cfg.succs.begin() + cfg.succ_first[b + 1]);
};
successors(site);
while (!pending.empty())
{
const auto b = pending.back();
pending.pop_back();
if (b == site)
return false;
if (!seen[b])
{
seen[b] = 1;
successors(b);
}
}
std::fill(seen.begin(), seen.end(), 0);
seen[site] = 1;
pending.push_back(body.layout.front());
while (!pending.empty())
{
const auto b = pending.back();
pending.pop_back();
if (seen[b])
continue;
seen[b] = 1;
const auto last = body.blocks[b].last;
if (last != kNoId && body.instructions[last].op == Opcode::Return)
return true;
successors(b);
}
return false;
}
// Whether the range is live at one of the sorted positions.
bool live_into(const LiveRange& range, const Segments& segments, const std::vector<uint32_t>& positions)
{
bool live = false;
if (!positions.empty())
each_interval(range, segments, [&](uint32_t a, uint32_t b) {
const auto it = std::lower_bound(positions.begin(), positions.end(), a);
live |= it != positions.end() && *it <= b;
});
return live;
}
// The first and last positions of each block, as live_ranges numbers them.
void block_positions(const FunctionBody& body, std::vector<uint32_t>& first, std::vector<uint32_t>& last)
{
first.assign(body.blocks.size(), 0);
last.assign(body.blocks.size(), 0);
uint32_t at = 2;
for (BlockId b : body.layout)
{
first[b] = b == body.layout.front() ? 0 : at;
for (InstId i = body.blocks[b].first; i != kNoId; i = body.instructions[i].next)
at += 2;
last[b] = at + 1;
at += 2;
}
}
// The positions [first, last] of the entry and the short returns it
// enters when shrink_wrap.cpp can run them without the frame, found on
// LowIR with the region analysis it uses (its narrowest plan: other blocks
// may need the frame for spills). A block needs the frame when it calls, or
// names a slot, a symbol or a floating value. The positions are those of
// live_ranges.
std::vector<uint32_t> frameless_spans(const FunctionBody& body, const opt::Cfg& cfg)
{
std::vector<uint32_t> spans;
const auto n = static_cast<uint32_t>(body.layout.size());
if (n < 2 || cfg.succ_first.empty())
return spans;
std::vector<uint32_t> index(body.blocks.size(), kNoId), first(n), last(n);
for (uint32_t k = 0; k < n; ++k)
index[body.layout[k]] = k;
machine::ShrinkGraph graph;
graph.succs.resize(n);
graph.needs.assign(n, 0);
graph.tabled.assign(n, 0);
graph.returns.assign(n, 0);
graph.short_return.assign(n, 0);
graph.counts.assign(n, 0);
uint32_t at = 2;
for (uint32_t k = 0; k < n; ++k)
{
const BlockId b = body.layout[k];
first[k] = k ? at : 0;
for (InstId i = body.blocks[b].first; i != kNoId; i = body.instructions[i].next, at += 2)
{
const auto& inst = body.instructions[i];
bool needs = inst.op == Opcode::Call || inst.type.is_float() || inst.type.is_vector();
opt::for_each_operand(body, inst,
[&](Value v) { needs |= v.is(ValueKind::Slot) || v.is(ValueKind::Symbol) || v.is(ValueKind::Float); });
graph.needs[k] |= needs;
graph.tabled[k] |= inst.op == Opcode::Switch;
graph.returns[k] = inst.op == Opcode::Return;
++graph.counts[k];
}
last[k] = at + 1;
at += 2;
for (uint32_t s = cfg.succ_first[b]; s < cfg.succ_first[b + 1]; ++s)
graph.succs[k].push_back(index[cfg.succs[s]]);
graph.short_return[k] = !graph.needs[k] && graph.returns[k] && graph.counts[k] <= 4;
}
std::vector<uint8_t> framed;
machine::framed_blocks(graph, framed);
machine::ShrinkRegion region;
if (framed[0] || !machine::shrink_region(graph, framed, machine::ShrinkPlan::Minimal, 0, 0, region))
return spans;
for (uint32_t k = 0; k < n; ++k)
if (region.region[k] || region.copied[k])
{
spans.push_back(first[k]);
spans.push_back(last[k]);
}
return spans;
}
// Whether the range is live within one of the spans.
bool live_within(const LiveRange& range, const Segments& segments, const std::vector<uint32_t>& spans)
{
bool live = false;
if (!spans.empty())
each_interval(range, segments, [&](uint32_t a, uint32_t b) {
for (size_t k = 0; !live && k < spans.size(); k += 2)
live = a <= spans[k + 1] && spans[k] <= b;
});
return live;
}
// The register each parameter arrives in, when it stays there. An indirect
// result parameter takes x8.
std::vector<unsigned> incoming_registers(
const Program& program, const lowir::Signature& signature, const FunctionBody& body, bool darwin, bool& free_x8)
{
std::vector<unsigned> incoming(body.parameter_count, kNoId);
Arguments args(darwin);
for (TempId id = 0; id < body.parameter_count; ++id)
{
const auto& param = program.parameters_of(signature)[id];
if (param.pass == ir_model::PPM_INDIRECT_RESULT)
{
free_x8 = false;
continue;
}
const auto arg = args.next(param.type, param.shape);
if ((arg.bank == Bank::General && !memory_value(param.type)) ||
(arg.bank == Bank::Simd && (param.type.kind() == TypeKind::V128 || !memory_value(param.type))))
incoming[id] = arg.first;
}
return incoming;
}
// Reuse the tail of the slot area when all its remaining owners live in
// registers: the frame ends after the last slot still in memory. The
// original slot offsets below it stay valid.
uint32_t reused_slot_tail(const FunctionBody& body, const std::vector<uint32_t>& slots,
const std::vector<uint8_t>& object_words, uint32_t base)
{
uint32_t frame = base;
for (SlotId i = 0; i < slots.size(); ++i)
if (!object_words[i] && slots[i] != kNoId)
{
const Type type = body.slots[i].type;
const uint64_t bytes = (storage_bytes(type) + 7) & ~uint64_t(7);
const unsigned align = data_alignment(type);
frame = std::max(frame, static_cast<uint32_t>(slots[i] + bytes + (align > 16 ? align - 16 : 0)));
}
return frame;
}
// The order in which ranges choose homes: by spill priority when the
// registers may not suffice, with the phi web adjustments above; empty
// (program order) otherwise. `general_registers` counts the preserved
// general registers, `assignable` every general register a range can take.
std::vector<uint32_t> allocation_order(const Program& program, const FunctionBody& body, opt::Cfg& cfg,
const std::vector<uint32_t>& aliases, std::vector<uint64_t>& block_weights, const std::vector<LiveRange>& ranges,
const Segments& segments, const std::vector<uint32_t>& calls, machine::PhiWebs& webs, uint32_t slots,
unsigned level, unsigned general_registers, unsigned assignable, std::vector<uint64_t>& weight)
{
std::vector<uint32_t> order;
std::vector<double> priority;
const auto simd_pressure = register_pressure(body, ranges, segments, calls, slots, 8, Bank::Simd);
const auto general_pressure = register_pressure(
body, ranges, segments, calls, slots, general_registers, Bank::General);
if (simd_pressure != RegisterPressure::Fits || general_pressure != RegisterPressure::Fits)
{
weight = spill_weights(program, body, cfg, aliases, block_weights);
order.resize(ranges.size());
priority.reserve(ranges.size());
for (uint32_t i = 0; i < order.size(); ++i)
{
order[i] = i;
const auto& range = ranges[i];
priority.push_back(simd_pressure == RegisterPressure::Saturated
? simd_spill_priority(body, range, segments, weight[range.id])
: static_cast<double>(weight[range.id]));
}
const auto by_priority = [&](uint32_t a, uint32_t b) { return priority[a] > priority[b]; };
std::stable_sort(order.begin(), order.end(), by_priority);
if (general_pressure == RegisterPressure::Saturated &&
raise_crowded_short_ranges(body, aliases, ranges, segments, calls, slots, static_cast<int32_t>(assignable),
static_cast<int32_t>(general_registers), order, priority))
std::stable_sort(order.begin(), order.end(), by_priority);
if (level >= 2 && !calls.empty() && !webs.empty())
prioritize_call_webs(body, ranges, segments, calls, webs, priority, order);
}
if (level >= 3 && !segments.empty() && !webs.empty())
prioritize_loop_webs(body, cfg, ranges, aliases, weight, order);
if (level >= 2 && priority.empty() && !order.empty() && !calls.empty() && !webs.empty())
prioritize_call_webs(body, ranges, segments, calls, webs, priority, order);
return order;
}
// Phi transfers whose two ends never overlap can use one register. Join
// them into groups, forward transfers first, while no two members of a group
// overlap. A group crosses a call when one of its members does.
class PhiGroups
{
public:
PhiGroups(const FunctionBody& body, const std::vector<uint32_t>& aliases, const std::vector<LiveRange>& ranges,
const Segments& segments, const std::vector<PhiCopy>& copies, const std::vector<uint32_t>& calls)
{
if (copies.empty() || segments.empty())
return;
const size_t count = body.temps.size();
std::vector<uint32_t> range_of(count, kNoId), position(body.blocks.size(), 0), order(copies.size());
for (uint32_t i = 0; i < ranges.size(); ++i)
if (ranges[i].first != kNoId)
range_of[ranges[i].id] = i;
for (uint32_t k = 0; k < body.layout.size(); ++k)
position[body.layout[k]] = k;
for (uint32_t c = 0; c < copies.size(); ++c)
order[c] = c;
std::stable_partition(
order.begin(), order.end(), [&](uint32_t c) { return position[copies[c].from] < position[copies[c].to]; });
root_.assign(count, kNoId);
Spans spans{ ranges, segments, range_of, std::vector<uint32_t>(count, kNoId), {} };
std::vector<uint32_t> target(copies.size());
for (uint32_t c = 0; c < copies.size(); ++c)
target[c] = copies[c].phi;
split_inputs(body, aliases, copies, position, spans, target);
for (uint32_t c : order)
{
uint32_t ends[] = { copies[c].source, target[c] };
if (range_of[ends[0]] == kNoId || range_of[ends[1]] == kNoId)
continue;
for (auto& end : ends)
{
if (root_[end] == kNoId)
{
root_[end] = end;
spans.get(end);
}
end = find(end);
}
if (ends[0] == ends[1] || spans.overlap(ends[0], ends[1]))
continue;
const auto keep = std::min(ends[0], ends[1]), gone = std::max(ends[0], ends[1]);
auto& kept = spans.list[spans.index[keep]];
auto& lost = spans.list[spans.index[gone]];
Segments joined;
joined.reserve(kept.size() + lost.size());
std::merge(kept.begin(), kept.end(), lost.begin(), lost.end(), std::back_inserter(joined));
kept = std::move(joined);
lost = Segments();
root_[gone] = keep;
}
first_.assign(count + 1, 0);
for (TempId t = 0; t < count; ++t)
if (root_[t] != kNoId)
++first_[(root_[t] = find(t)) + 1];
for (size_t t = 0; t < count; ++t)
first_[t + 1] += first_[t];
members_.resize(first_[count]);
crosses_.assign(count, 0);
std::vector<uint32_t> fill(first_.begin(), first_.end() - 1);
for (TempId t = 0; t < count; ++t)
if (root_[t] != kNoId)
{
members_[fill[root_[t]]++] = range_of[t];
each_interval(ranges[range_of[t]], segments, [&](uint32_t a, uint32_t b) {
const auto call = std::lower_bound(calls.begin(), calls.end(), a);
crosses_[root_[t]] |= call != calls.end() && *call < b;
});
}
}
bool crosses_call(TempId root) const { return crosses_[root]; }
// A phi whose inputs share a register without it.
bool split(TempId id) const { return !split_.empty() && split_[id]; }
bool empty() const { return root_.empty(); }
TempId root(TempId id) const { return root_.empty() ? kNoId : root_[id]; }
// The range indices of a group's members.
template<typename F>
void each_member(TempId root, F f) const
{
for (uint32_t k = first_[root]; k < first_[root + 1]; ++k)
f(members_[k]);
}
private:
TempId find(TempId t)
{
while (root_[t] != t)
t = root_[t] = root_[root_[t]];
return t;
}
static bool overlap(const Segments& a, const Segments& b)
{
for (size_t i = 0, j = 0; i < a.size() && j < b.size();)
{
if (a[i].first <= b[j].second && b[j].first <= a[i].second)
return true;
if (a[i].second < b[j].second)
++i;
else
++j;
}
return false;
}
// A scalar loop phi that overlaps every value it takes on a back edge, or
// every input of the phi of a merge block that it takes, needs a copy on
// that edge. When the copy needs its own block there, join the inputs
// instead: every edge then makes the same copy, which the loop header
// makes once while the branches go to it directly.
// Sorted intervals of temps, computed once each. A group's root holds
// the merged intervals of its members.
struct Spans
{
const std::vector<LiveRange>& ranges;
const Segments& segments;
const std::vector<uint32_t>& range_of;
std::vector<uint32_t> index;
std::vector<Segments> list;
uint32_t get(TempId t)
{
if (index[t] == kNoId)
{
index[t] = list.size();
list.emplace_back();
each_interval(
ranges[range_of[t]], segments, [&](uint32_t a, uint32_t b) { list.back().push_back({ a, b }); });
std::sort(list.back().begin(), list.back().end());
}
return index[t];
}
bool overlap(TempId a, TempId b)
{
const auto x = get(a), y = get(b);
return PhiGroups::overlap(list[x], list[y]);
}
};
// A scalar loop phi that overlaps every value it takes on a back edge, or
// every input of the phi of a merge block that it takes, needs a copy on
// that edge. When the copy needs its own block there, join the inputs
// instead: every edge then makes the same copy, which the loop header
// makes once while the branches go to it directly.
void split_inputs(const FunctionBody& body, const std::vector<uint32_t>& aliases,
const std::vector<PhiCopy>& copies, const std::vector<uint32_t>& position, Spans& spans,
std::vector<uint32_t>& target)
{
const auto& range_of = spans.range_of;
// The transfers of each phi are adjacent.
std::vector<uint32_t> first_copy;
const auto inputs_of = [&](TempId phi) {
if (first_copy.empty())
{
first_copy.assign(body.temps.size(), kNoId);
for (uint32_t c = copies.size(); c-- > 0;)
first_copy[copies[c].phi] = c;
}
uint32_t end = first_copy[phi];
while (end < copies.size() && copies[end].phi == phi)
++end;
return std::make_pair(first_copy[phi], end);
};
// A block of phis and its jump needs a jump for the copy, and a
// conditional branch a block, unless the copy can run before the
// branch; two such branches need two blocks.
const auto needs_block = [&](BlockId block) -> uint32_t {
const auto end = body.blocks[block].last;
if (end == kNoId || body.instructions[end].op != Opcode::Jump)
return end != kNoId;
for (auto i = body.blocks[block].first; i != end; i = body.instructions[i].next)
if (body.instructions[i].op != Opcode::Phi)
return 0;
return 2;
};
const auto back = [&](uint32_t c) { return position[copies[c].from] >= position[copies[c].to]; };
// The header makes the copy only when its other phis need none: each
// takes temps that can share its register.
const auto others_join = [&](BlockId header, TempId split) {
for (auto i = body.blocks[header].first; i != kNoId && body.instructions[i].op == Opcode::Phi;
i = body.instructions[i].next)
{
const auto& phi = body.instructions[i];
if (phi.result == split)
continue;
if (range_of[phi.result] == kNoId)
return false;
for (uint32_t k = 0; k < phi.extra_count; k += 2)
{
const auto v = body.operands[phi.extra_first + k + 1];
if (!v.is(ValueKind::Temp))
return false;
const auto t = representative(aliases, v.index);
if (t != phi.result && (range_of[t] == kNoId || spans.overlap(phi.result, t)))
return false;
}
}
return true;
};
std::vector<TempId> seen;
for (uint32_t first = 0, last = 0; first < copies.size(); first = last)
{
const TempId phi = copies[first].phi;
for (last = first; last < copies.size() && copies[last].phi == phi;)
++last;
if (range_of[phi] == kNoId || body.temps[phi].type.is_float() || body.temps[phi].type.is_vector())
continue;
// Every source needs a range, and some transfer must come from
// before the loop and the back edges need two blocks or a jump.
bool forward = false, valid = true;
uint32_t block = 0;
for (uint32_t c = first; valid && c < last; ++c)
{
valid = range_of[copies[c].source] != kNoId && copies[c].source != phi;
forward |= !back(c);
block += back(c) ? needs_block(copies[c].from) : 0;
}
if (!valid || !forward || block < 2)
continue;
// Each source counts at its first transfer.
forward = false;
TempId joined = kNoId;
seen.clear();
for (uint32_t c = first; valid && c < last; ++c)
{
const auto source = copies[c].source;
if (std::find(seen.begin(), seen.end(), source) != seen.end())
continue;
seen.push_back(source);
forward |= !back(c);
if (!back(c))
continue;
joined = joined == kNoId ? source : joined;
if (spans.overlap(phi, source))
continue;
const auto merged = inputs_of(source);
valid = merged.first < merged.second;
for (auto m = merged.first; valid && m < merged.second; ++m)
valid = copies[m].to == copies[c].from && copies[m].source != phi &&
range_of[copies[m].source] != kNoId && spans.overlap(phi, copies[m].source);
}
for (size_t a = 0; valid && a < seen.size(); ++a)
for (size_t b = a + 1; valid && b < seen.size(); ++b)
valid = !spans.overlap(seen[a], seen[b]);
if (!valid || !forward || joined == kNoId || !others_join(copies[first].to, phi))
continue;
if (split_.empty())
split_.assign(body.temps.size(), 0);
split_[phi] = 1;
for (uint32_t c = first; c < last; ++c)
target[c] = joined;
}
}
std::vector<TempId> root_;
std::vector<uint32_t> first_, members_;
std::vector<uint8_t> crosses_, split_;
};
// A straight-line function only needs the end of each register's last use.
// When a register has holes, query the same interference tree used on x86.
class RegisterBank
{
public:
// `caller` is the bank's class of registers a call may clobber.
RegisterBank(const Segments& segments, uint32_t slots, uint32_t caller)
: segments_(segments), slots_(slots), caller_(caller)
{}
uint32_t live_at(uint32_t slot) const { return initialized_ ? tree_.regs(slot, slot) : 0; }
// The registers that ranges hold somewhere in [a, b], and taking one there.
uint32_t busy(uint32_t a, uint32_t b) const { return initialized_ ? tree_.regs(a, b) : ~0u; }
void take(uint32_t a, uint32_t b, unsigned reg) { tree_.add(a, b, 1, 1u << reg); }
// Ask later ranges without a usable preference to leave `reg` free over
// `range`, which would remove one of its phi transfers.
void hint(const LiveRange& range, unsigned reg)
{
if (segments_.empty())
return;
if (!hinted_)
{
hints_.build_regs(slots_);
hinted_ = true;
}
each_interval(range, segments_, [&](uint32_t a, uint32_t b) {
hints_.add_regs(a, b, 1u << reg);
hint_from_[reg] = std::min(hint_from_[reg], a);
hint_to_[reg] = std::max(hint_to_[reg], b);
});
}
// Without a usable preference, a register in `partners` comes next;
// those are the registers of the range's phi partners.
unsigned assign(
const LiveRange& range, uint32_t allowed, unsigned preferred, unsigned alternate = kNoId, uint32_t partners = 0)
{
if (!allowed)
return kNoId;
if (segments_.empty())
{
for (uint32_t regs = allowed; regs; regs &= regs - 1)
{
unsigned reg = __builtin_ctz(regs);
if (until_[reg] > range.first)
allowed &= ~(1u << reg);
}
}
else
{
// Retries for the same range reuse its interference.
if (&range != queried_)
{
if (!initialized_)
{
tree_.build(std::vector<int32_t>(slots_, 0));
initialized_ = true;
}
busy_ = 0;
each_interval(range, segments_, [&](uint32_t a, uint32_t b) { busy_ |= tree_.regs(a, b); });
queried_ = ⦥
}
allowed &= ~busy_;
}
if (!allowed)
return kNoId;
const unsigned reg = preferred != kNoId && (allowed & (1u << preferred)) ? preferred
: alternate != kNoId && (allowed & (1u << alternate)) ? alternate
: (allowed & partners) ? __builtin_ctz(allowed & partners)
: unhinted(range, allowed, partners);
if (segments_.empty())
until_[reg] = range.last + 1;
else
each_interval(range, segments_, [&](uint32_t a, uint32_t b) { tree_.add(a, b, 1, 1u << reg); });
queried_ = nullptr;
return reg;
}
private:
// The lowest register of the lowest one's class that no other range's
// hint holds over `range`, else the lowest register.
unsigned unhinted(const LiveRange& range, uint32_t allowed, uint32_t partners) const
{
const unsigned lowest = __builtin_ctz(allowed);
if (!hinted_)
return lowest;
uint32_t open = allowed & ((1u << lowest) & caller_ ? caller_ : ~caller_);
// Only registers hinted somewhere within the range's extent can be
// hinted over it.
uint32_t from = ~0u, to = 0, near = 0;
each_interval(range, segments_, [&](uint32_t a, uint32_t b) {
from = std::min(from, a);
to = std::max(to, b);
});
for (uint32_t regs = open & ~partners; regs; regs &= regs - 1)
{
const unsigned reg = __builtin_ctz(regs);
if (hint_from_[reg] <= to && hint_to_[reg] >= from)
near |= 1u << reg;
}
if (near)
each_interval(
range, segments_, [&](uint32_t a, uint32_t b) { open &= ~(hints_.regs(a, b) & ~partners & near); });
return open ? __builtin_ctz(open) : lowest;
}
const Segments& segments_;
const LiveRange* queried_ = nullptr;
uint32_t slots_, caller_, until_[32] = {}, busy_ = 0, hint_to_[32] = {};
uint32_t hint_from_[32] = { ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u,
~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u };
machine::PressureTree tree_, hints_;
bool initialized_ = false, hinted_ = false;
};
// The one block outside a loop that enters its header (the preheader, or a
// block that also branches elsewhere), or kNoId.
BlockId loop_entry(const opt::Cfg& cfg, const opt::LoopForest& forest, uint32_t loop)
{
const auto& l = forest.loops[loop];
if (l.preheader != kNoId)
return l.preheader;
BlockId entry = kNoId;
for (uint32_t p = cfg.pred_first[l.header]; p < cfg.pred_first[l.header + 1]; ++p)
{
uint32_t in = forest.innermost[cfg.preds[p]];
while (in != kNoId && in != loop)
in = forest.loops[in].parent;
if (in == loop)
continue;
if (entry != kNoId && entry != cfg.preds[p])
return kNoId;
entry = cfg.preds[p];
}
return entry;
}
// A division by a literal that constant_division selects needs its
// multiplier, and a remainder its divisor, in registers. In a loop each is
// built once at the start of the block that enters the loop when one
// register is free there and over every block of the loop: a caller register
// in a loop without calls, or a preserved register the function saves anyway.
// The divisions of one loop share equal constants.
void hold_division_constants(const FunctionBody& body, opt::Cfg& cfg, RegisterBank& bank, uint32_t caller,
uint32_t saved, std::vector<HeldConstant>& held, std::vector<std::pair<InstId, uint32_t>>& divisions)
{
opt::LoopForest forest;
std::vector<uint32_t> first, last, busy, holder, entries;
// The registers held over a loop's entry and blocks, and taking one there.
const auto held_over = [&](const opt::Loop& l, BlockId entry) {
uint32_t regs = bank.busy(first[entry], last[entry]);
for (BlockId member : l.blocks)
regs |= bank.busy(first[member], last[member]);
return regs;
};
const auto take_over = [&](const opt::Loop& l, BlockId entry, unsigned reg) {
bank.take(first[entry], last[entry], reg);
for (BlockId member : l.blocks)
bank.take(first[member], last[member], reg);
};
for (BlockId b : body.layout)
for (InstId i = body.blocks[b].first; i != kNoId; i = body.instructions[i].next)
{
uint64_t values[2];
if (!division_constants(body.instructions[i], body, values[0], values[1]))
continue;
if (first.empty())
{
if (cfg.dom_in.size() != cfg.block_count)
opt::complete_cfg(cfg);
opt::find_loops(body, cfg, forest);
block_positions(body, first, last);
busy.assign(forest.loops.size(), 0);
entries.assign(forest.loops.size(), kNoId - 1);
}
const uint32_t loop = forest.innermost[b];
if (loop == kNoId)
continue;
const auto& l = forest.loops[loop];
if (entries[loop] == kNoId - 1)
{
const BlockId entry = loop_entry(cfg, forest, loop);
entries[loop] = entry != kNoId && last[entry] ? entry : kNoId;
if (entries[loop] == kNoId)
continue;
// A constant built at the start of the entry block lives through its calls too.
bool calls = false;
const auto calling = [&](BlockId member) {
for (InstId k = body.blocks[member].first; k != kNoId; k = body.instructions[k].next)
calls |= body.instructions[k].op == Opcode::Call;
};
calling(entry);
for (BlockId member : l.blocks)
calling(member);
busy[loop] = ~(saved | (calls ? 0 : caller)) | held_over(l, entry);
}
if (entries[loop] == kNoId)
continue;
uint32_t regs = 0;
for (unsigned k = 0; k < 2; ++k)
{
unsigned reg = 255;
for (uint32_t h = 0; h < held.size() && reg == 255 && values[k]; ++h)
if (holder[h] == loop && held[h].value == values[k])
reg = held[h].reg;
// A loop nested in this one or sharing its entry may have
// taken a register over these blocks since.
if (reg == 255 && values[k])
busy[loop] |= held_over(l, entries[loop]);
if (reg == 255 && values[k] && ~busy[loop])
{
reg = __builtin_ctz(~busy[loop]);
busy[loop] |= 1u << reg;
take_over(l, entries[loop], reg);
held.push_back(HeldConstant{ entries[loop], reg, values[k] });
holder.push_back(loop);
}
regs |= reg << (8 * k);
}
if (regs != 0xffff)
divisions.push_back(std::make_pair(i, regs));
}
std::sort(divisions.begin(), divisions.end());
}
// The phi groups' registers as ranges choose theirs. A group's first member
// to get a register asks the later ones, and the ranges assigned in between,
// to leave it to them.
class GroupRegisters
{
public:
GroupRegisters(const FunctionBody& body, const std::vector<uint32_t>& aliases, const std::vector<LiveRange>& ranges,
const Segments& segments, const std::vector<PhiCopy>& copies, const std::vector<uint32_t>& calls)
: ranges_(ranges), groups_(body, aliases, ranges, segments, copies, calls),
regs_(groups_.empty() ? 0 : body.temps.size(), kNoId), assigned_(groups_.empty() ? 0 : ranges.size())
{}
void start(uint32_t index)
{