aboutsummaryrefslogtreecommitdiffstats
path: root/src/freedreno/ir3/ir3_ra.c
blob: 05bcdcc60b1164ad57e3335f0cb988fa4063a971 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
/*
 * Copyright (C) 2014 Rob Clark <robclark@freedesktop.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Authors:
 *    Rob Clark <robclark@freedesktop.org>
 */

#include "util/u_math.h"
#include "util/register_allocate.h"
#include "util/ralloc.h"
#include "util/bitset.h"

#include "ir3.h"
#include "ir3_compiler.h"

/*
 * Register Assignment:
 *
 * Uses the register_allocate util, which implements graph coloring
 * algo with interference classes.  To handle the cases where we need
 * consecutive registers (for example, texture sample instructions),
 * we model these as larger (double/quad/etc) registers which conflict
 * with the corresponding registers in other classes.
 *
 * Additionally we create additional classes for half-regs, which
 * do not conflict with the full-reg classes.  We do need at least
 * sizes 1-4 (to deal w/ texture sample instructions output to half-
 * reg).  At the moment we don't create the higher order half-reg
 * classes as half-reg frequently does not have enough precision
 * for texture coords at higher resolutions.
 *
 * There are some additional cases that we need to handle specially,
 * as the graph coloring algo doesn't understand "partial writes".
 * For example, a sequence like:
 *
 *   add r0.z, ...
 *   sam (f32)(xy)r0.x, ...
 *   ...
 *   sam (f32)(xyzw)r0.w, r0.x, ...  ; 3d texture, so r0.xyz are coord
 *
 * In this scenario, we treat r0.xyz as class size 3, which is written
 * (from a use/def perspective) at the 'add' instruction and ignore the
 * subsequent partial writes to r0.xy.  So the 'add r0.z, ...' is the
 * defining instruction, as it is the first to partially write r0.xyz.
 *
 * To address the fragmentation that this can potentially cause, a
 * two pass register allocation is used.  After the first pass the
 * assignment of scalars is discarded, but the assignment of vecN (for
 * N > 1) is used to pre-color in the second pass, which considers
 * only scalars.
 *
 * Arrays of arbitrary size are handled via pre-coloring a consecutive
 * sequence of registers.  Additional scalar (single component) reg
 * names are allocated starting at ctx->class_base[total_class_count]
 * (see arr->base), which are pre-colored.  In the use/def graph direct
 * access is treated as a single element use/def, and indirect access
 * is treated as use or def of all array elements.  (Only the first
 * def is tracked, in case of multiple indirect writes, etc.)
 *
 * TODO arrays that fit in one of the pre-defined class sizes should
 * not need to be pre-colored, but instead could be given a normal
 * vreg name.  (Ignoring this for now since it is a good way to work
 * out the kinks with arbitrary sized arrays.)
 *
 * TODO might be easier for debugging to split this into two passes,
 * the first assigning vreg names in a way that we could ir3_print()
 * the result.
 */

static const unsigned class_sizes[] = {
	1, 2, 3, 4,
	4 + 4, /* txd + 1d/2d */
	4 + 6, /* txd + 3d */
};
#define class_count ARRAY_SIZE(class_sizes)

static const unsigned half_class_sizes[] = {
	1, 2, 3, 4,
};
#define half_class_count  ARRAY_SIZE(half_class_sizes)

/* seems to just be used for compute shaders?  Seems like vec1 and vec3
 * are sufficient (for now?)
 */
static const unsigned high_class_sizes[] = {
	1, 3,
};
#define high_class_count ARRAY_SIZE(high_class_sizes)

#define total_class_count (class_count + half_class_count + high_class_count)

/* Below a0.x are normal regs.  RA doesn't need to assign a0.x/p0.x. */
#define NUM_REGS             (4 * 48)  /* r0 to r47 */
#define NUM_HIGH_REGS        (4 * 8)   /* r48 to r55 */
#define FIRST_HIGH_REG       (4 * 48)
/* Number of virtual regs in a given class: */
#define CLASS_REGS(i)        (NUM_REGS - (class_sizes[i] - 1))
#define HALF_CLASS_REGS(i)   (NUM_REGS - (half_class_sizes[i] - 1))
#define HIGH_CLASS_REGS(i)   (NUM_HIGH_REGS - (high_class_sizes[i] - 1))

#define HALF_OFFSET          (class_count)
#define HIGH_OFFSET          (class_count + half_class_count)

/* register-set, created one time, used for all shaders: */
struct ir3_ra_reg_set {
	struct ra_regs *regs;
	unsigned int classes[class_count];
	unsigned int half_classes[half_class_count];
	unsigned int high_classes[high_class_count];
	/* maps flat virtual register space to base gpr: */
	uint16_t *ra_reg_to_gpr;
	/* maps cls,gpr to flat virtual register space: */
	uint16_t **gpr_to_ra_reg;
};

static void
build_q_values(unsigned int **q_values, unsigned off,
		const unsigned *sizes, unsigned count)
{
	for (unsigned i = 0; i < count; i++) {
		q_values[i + off] = rzalloc_array(q_values, unsigned, total_class_count);

		/* From register_allocate.c:
		 *
		 * q(B,C) (indexed by C, B is this register class) in
		 * Runeson/Nyström paper.  This is "how many registers of B could
		 * the worst choice register from C conflict with".
		 *
		 * If we just let the register allocation algorithm compute these
		 * values, is extremely expensive.  However, since all of our
		 * registers are laid out, we can very easily compute them
		 * ourselves.  View the register from C as fixed starting at GRF n
		 * somewhere in the middle, and the register from B as sliding back
		 * and forth.  Then the first register to conflict from B is the
		 * one starting at n - class_size[B] + 1 and the last register to
		 * conflict will start at n + class_size[B] - 1.  Therefore, the
		 * number of conflicts from B is class_size[B] + class_size[C] - 1.
		 *
		 *   +-+-+-+-+-+-+     +-+-+-+-+-+-+
		 * B | | | | | |n| --> | | | | | | |
		 *   +-+-+-+-+-+-+     +-+-+-+-+-+-+
		 *             +-+-+-+-+-+
		 * C           |n| | | | |
		 *             +-+-+-+-+-+
		 *
		 * (Idea copied from brw_fs_reg_allocate.cpp)
		 */
		for (unsigned j = 0; j < count; j++)
			q_values[i + off][j + off] = sizes[i] + sizes[j] - 1;
	}
}

/* One-time setup of RA register-set, which describes all the possible
 * "virtual" registers and their interferences.  Ie. double register
 * occupies (and conflicts with) two single registers, and so forth.
 * Since registers do not need to be aligned to their class size, they
 * can conflict with other registers in the same class too.  Ie:
 *
 *    Single (base) |  Double
 *    --------------+---------------
 *       R0         |  D0
 *       R1         |  D0 D1
 *       R2         |     D1 D2
 *       R3         |        D2
 *           .. and so on..
 *
 * (NOTE the disassembler uses notation like r0.x/y/z/w but those are
 * really just four scalar registers.  Don't let that confuse you.)
 */
struct ir3_ra_reg_set *
ir3_ra_alloc_reg_set(struct ir3_compiler *compiler)
{
	struct ir3_ra_reg_set *set = rzalloc(compiler, struct ir3_ra_reg_set);
	unsigned ra_reg_count, reg, first_half_reg, first_high_reg, base;
	unsigned int **q_values;

	/* calculate # of regs across all classes: */
	ra_reg_count = 0;
	for (unsigned i = 0; i < class_count; i++)
		ra_reg_count += CLASS_REGS(i);
	for (unsigned i = 0; i < half_class_count; i++)
		ra_reg_count += HALF_CLASS_REGS(i);
	for (unsigned i = 0; i < high_class_count; i++)
		ra_reg_count += HIGH_CLASS_REGS(i);

	/* allocate and populate q_values: */
	q_values = ralloc_array(set, unsigned *, total_class_count);

	build_q_values(q_values, 0, class_sizes, class_count);
	build_q_values(q_values, HALF_OFFSET, half_class_sizes, half_class_count);
	build_q_values(q_values, HIGH_OFFSET, high_class_sizes, high_class_count);

	/* allocate the reg-set.. */
	set->regs = ra_alloc_reg_set(set, ra_reg_count, true);
	set->ra_reg_to_gpr = ralloc_array(set, uint16_t, ra_reg_count);
	set->gpr_to_ra_reg = ralloc_array(set, uint16_t *, total_class_count);

	/* .. and classes */
	reg = 0;
	for (unsigned i = 0; i < class_count; i++) {
		set->classes[i] = ra_alloc_reg_class(set->regs);

		set->gpr_to_ra_reg[i] = ralloc_array(set, uint16_t, CLASS_REGS(i));

		for (unsigned j = 0; j < CLASS_REGS(i); j++) {
			ra_class_add_reg(set->regs, set->classes[i], reg);

			set->ra_reg_to_gpr[reg] = j;
			set->gpr_to_ra_reg[i][j] = reg;

			for (unsigned br = j; br < j + class_sizes[i]; br++)
				ra_add_transitive_reg_conflict(set->regs, br, reg);

			reg++;
		}
	}

	first_half_reg = reg;
	base = HALF_OFFSET;

	for (unsigned i = 0; i < half_class_count; i++) {
		set->half_classes[i] = ra_alloc_reg_class(set->regs);

		set->gpr_to_ra_reg[base + i] =
				ralloc_array(set, uint16_t, HALF_CLASS_REGS(i));

		for (unsigned j = 0; j < HALF_CLASS_REGS(i); j++) {
			ra_class_add_reg(set->regs, set->half_classes[i], reg);

			set->ra_reg_to_gpr[reg] = j;
			set->gpr_to_ra_reg[base + i][j] = reg;

			for (unsigned br = j; br < j + half_class_sizes[i]; br++)
				ra_add_transitive_reg_conflict(set->regs, br + first_half_reg, reg);

			reg++;
		}
	}

	first_high_reg = reg;
	base = HIGH_OFFSET;

	for (unsigned i = 0; i < high_class_count; i++) {
		set->high_classes[i] = ra_alloc_reg_class(set->regs);

		set->gpr_to_ra_reg[base + i] =
				ralloc_array(set, uint16_t, HIGH_CLASS_REGS(i));

		for (unsigned j = 0; j < HIGH_CLASS_REGS(i); j++) {
			ra_class_add_reg(set->regs, set->high_classes[i], reg);

			set->ra_reg_to_gpr[reg] = j;
			set->gpr_to_ra_reg[base + i][j] = reg;

			for (unsigned br = j; br < j + high_class_sizes[i]; br++)
				ra_add_transitive_reg_conflict(set->regs, br + first_high_reg, reg);

			reg++;
		}
	}

	/* starting a6xx, half precision regs conflict w/ full precision regs: */
	if (compiler->gpu_id >= 600) {
		/* because of transitivity, we can get away with just setting up
		 * conflicts between the first class of full and half regs:
		 */
		for (unsigned i = 0; i < half_class_count; i++) {
			/* NOTE there are fewer half class sizes, but they match the
			 * first N full class sizes.. but assert in case that ever
			 * accidentally changes:
			 */
			debug_assert(class_sizes[i] == half_class_sizes[i]);
			for (unsigned j = 0; j < CLASS_REGS(i) / 2; j++) {
				unsigned freg  = set->gpr_to_ra_reg[i][j];
				unsigned hreg0 = set->gpr_to_ra_reg[i + HALF_OFFSET][(j * 2) + 0];
				unsigned hreg1 = set->gpr_to_ra_reg[i + HALF_OFFSET][(j * 2) + 1];

				ra_add_transitive_reg_pair_conflict(set->regs, freg, hreg0, hreg1);
			}
		}

		// TODO also need to update q_values, but for now:
		ra_set_finalize(set->regs, NULL);
	} else {
		ra_set_finalize(set->regs, q_values);
	}

	ralloc_free(q_values);

	return set;
}

/* additional block-data (per-block) */
struct ir3_ra_block_data {
	BITSET_WORD *def;        /* variables defined before used in block */
	BITSET_WORD *use;        /* variables used before defined in block */
	BITSET_WORD *livein;     /* which defs reach entry point of block */
	BITSET_WORD *liveout;    /* which defs reach exit point of block */
};

/* additional instruction-data (per-instruction) */
struct ir3_ra_instr_data {
	/* cached instruction 'definer' info: */
	struct ir3_instruction *defn;
	int off, sz, cls;
};

/* register-assign context, per-shader */
struct ir3_ra_ctx {
	struct ir3_shader_variant *v;
	struct ir3 *ir;

	struct ir3_ra_reg_set *set;
	struct ra_graph *g;

	/* Are we in the scalar assignment pass?  In this pass, all larger-
	 * than-vec1 vales have already been assigned and pre-colored, so
	 * we only consider scalar values.
	 */
	bool scalar_pass;

	unsigned alloc_count;
	/* one per class, plus one slot for arrays: */
	unsigned class_alloc_count[total_class_count + 1];
	unsigned class_base[total_class_count + 1];
	unsigned instr_cnt;
	unsigned *def, *use;     /* def/use table */
	struct ir3_ra_instr_data *instrd;

	/* Mapping vreg name back to instruction, used select reg callback: */
	struct hash_table *name_to_instr;

	/* Tracking for max half/full register assigned.  We don't need to
	 * track high registers.
	 *
	 * The feedback about registers used in first pass is used to choose
	 * a target register usage to round-robin between in the 2nd pass.
	 */
	unsigned max_assigned;
	unsigned max_half_assigned;

	/* Tracking for select_reg callback */
	unsigned start_search_reg;
	unsigned max_target;
};

static int scalar_name(struct ir3_ra_ctx *ctx, struct ir3_instruction *instr, unsigned n);

/* does it conflict? */
static inline bool
intersects(unsigned a_start, unsigned a_end, unsigned b_start, unsigned b_end)
{
	return !((a_start >= b_end) || (b_start >= a_end));
}

static unsigned
reg_size_for_array(struct ir3_array *arr)
{
	if (arr->half)
		return DIV_ROUND_UP(arr->length, 2);

	return arr->length;
}

static int
size_to_class(unsigned sz, bool half, bool high)
{
	if (high) {
		for (unsigned i = 0; i < high_class_count; i++)
			if (high_class_sizes[i] >= sz)
				return i + HIGH_OFFSET;
	} else if (half) {
		for (unsigned i = 0; i < half_class_count; i++)
			if (half_class_sizes[i] >= sz)
				return i + HALF_OFFSET;
	} else {
		for (unsigned i = 0; i < class_count; i++)
			if (class_sizes[i] >= sz)
				return i;
	}
	debug_assert(0);
	return -1;
}

static bool
writes_gpr(struct ir3_instruction *instr)
{
	if (dest_regs(instr) == 0)
		return false;
	/* is dest a normal temp register: */
	struct ir3_register *reg = instr->regs[0];
	debug_assert(!(reg->flags & (IR3_REG_CONST | IR3_REG_IMMED)));
	if ((reg->num == regid(REG_A0, 0)) ||
			(reg->num == regid(REG_P0, 0)))
		return false;
	return true;
}

static bool
instr_before(struct ir3_instruction *a, struct ir3_instruction *b)
{
	if (a->flags & IR3_INSTR_UNUSED)
		return false;
	return (a->ip < b->ip);
}

static struct ir3_instruction *
get_definer(struct ir3_ra_ctx *ctx, struct ir3_instruction *instr,
		int *sz, int *off)
{
	struct ir3_ra_instr_data *id = &ctx->instrd[instr->ip];
	struct ir3_instruction *d = NULL;

	if (ctx->scalar_pass) {
		id->defn = instr;
		id->off = 0;
		id->sz = 1;     /* considering things as N scalar regs now */
	}

	if (id->defn) {
		*sz = id->sz;
		*off = id->off;
		return id->defn;
	}

	if (instr->opc == OPC_META_COLLECT) {
		/* What about the case where collect is subset of array, we
		 * need to find the distance between where actual array starts
		 * and collect..  that probably doesn't happen currently.
		 */
		struct ir3_register *src;
		int dsz, doff;

		/* note: don't use foreach_ssa_src as this gets called once
		 * while assigning regs (which clears SSA flag)
		 */
		foreach_src_n (src, n, instr) {
			struct ir3_instruction *dd;
			if (!src->instr)
				continue;

			dd = get_definer(ctx, src->instr, &dsz, &doff);

			if ((!d) || instr_before(dd, d)) {
				d = dd;
				*sz = dsz;
				*off = doff - n;
			}
		}

	} else if (instr->cp.right || instr->cp.left) {
		/* covers also the meta:fo case, which ends up w/ single
		 * scalar instructions for each component:
		 */
		struct ir3_instruction *f = ir3_neighbor_first(instr);

		/* by definition, the entire sequence forms one linked list
		 * of single scalar register nodes (even if some of them may
		 * be splits from a texture sample (for example) instr.  We
		 * just need to walk the list finding the first element of
		 * the group defined (lowest ip)
		 */
		int cnt = 0;

		/* need to skip over unused in the group: */
		while (f && (f->flags & IR3_INSTR_UNUSED)) {
			f = f->cp.right;
			cnt++;
		}

		while (f) {
			if ((!d) || instr_before(f, d))
				d = f;
			if (f == instr)
				*off = cnt;
			f = f->cp.right;
			cnt++;
		}

		*sz = cnt;

	} else {
		/* second case is looking directly at the instruction which
		 * produces multiple values (eg, texture sample), rather
		 * than the split nodes that point back to that instruction.
		 * This isn't quite right, because it may be part of a larger
		 * group, such as:
		 *
		 *     sam (f32)(xyzw)r0.x, ...
		 *     add r1.x, ...
		 *     add r1.y, ...
		 *     sam (f32)(xyzw)r2.x, r0.w  <-- (r0.w, r1.x, r1.y)
		 *
		 * need to come up with a better way to handle that case.
		 */
		if (instr->address) {
			*sz = instr->regs[0]->size;
		} else {
			*sz = util_last_bit(instr->regs[0]->wrmask);
		}
		*off = 0;
		d = instr;
	}

	if (d->opc == OPC_META_SPLIT) {
		struct ir3_instruction *dd;
		int dsz, doff;

		dd = get_definer(ctx, d->regs[1]->instr, &dsz, &doff);

		/* by definition, should come before: */
		debug_assert(instr_before(dd, d));

		*sz = MAX2(*sz, dsz);

		if (instr->opc == OPC_META_SPLIT)
			*off = MAX2(*off, instr->split.off);

		d = dd;
	}

	debug_assert(d->opc != OPC_META_SPLIT);

	id->defn = d;
	id->sz = *sz;
	id->off = *off;

	return d;
}

static void
ra_block_find_definers(struct ir3_ra_ctx *ctx, struct ir3_block *block)
{
	foreach_instr (instr, &block->instr_list) {
		struct ir3_ra_instr_data *id = &ctx->instrd[instr->ip];
		if (instr->regs_count == 0)
			continue;
		/* couple special cases: */
		if (writes_addr(instr) || writes_pred(instr)) {
			id->cls = -1;
		} else if (instr->regs[0]->flags & IR3_REG_ARRAY) {
			id->cls = total_class_count;
		} else {
			/* and the normal case: */
			id->defn = get_definer(ctx, instr, &id->sz, &id->off);
			id->cls = size_to_class(id->sz, is_half(id->defn), is_high(id->defn));

			/* this is a bit of duct-tape.. if we have a scenario like:
			 *
			 *   sam (f32)(x) out.x, ...
			 *   sam (f32)(x) out.y, ...
			 *
			 * Then the fanout/split meta instructions for the two different
			 * tex instructions end up grouped as left/right neighbors.  The
			 * upshot is that in when you get_definer() on one of the meta:fo's
			 * you get definer as the first sam with sz=2, but when you call
			 * get_definer() on the either of the sam's you get itself as the
			 * definer with sz=1.
			 *
			 * (We actually avoid this scenario exactly, the neighbor links
			 * prevent one of the output mov's from being eliminated, so this
			 * hack should be enough.  But probably we need to rethink how we
			 * find the "defining" instruction.)
			 *
			 * TODO how do we figure out offset properly...
			 */
			if (id->defn != instr) {
				struct ir3_ra_instr_data *did = &ctx->instrd[id->defn->ip];
				if (did->sz < id->sz) {
					did->sz = id->sz;
					did->cls = id->cls;
				}
			}
		}
	}
}

/* give each instruction a name (and ip), and count up the # of names
 * of each class
 */
static void
ra_block_name_instructions(struct ir3_ra_ctx *ctx, struct ir3_block *block)
{
	foreach_instr (instr, &block->instr_list) {
		struct ir3_ra_instr_data *id = &ctx->instrd[instr->ip];

#ifdef DEBUG
		instr->name = ~0;
#endif

		ctx->instr_cnt++;

		if (!writes_gpr(instr))
			continue;

		if (id->defn != instr)
			continue;

		/* In scalar pass, collect/split don't get their own names,
		 * but instead inherit them from their src(s):
		 *
		 * Possibly we don't need this because of scalar_name(), but
		 * it does make the ir3_print() dumps easier to read.
		 */
		if (ctx->scalar_pass) {
			if (instr->opc == OPC_META_SPLIT) {
				instr->name = instr->regs[1]->instr->name + instr->split.off;
				continue;
			}

			if (instr->opc == OPC_META_COLLECT) {
				instr->name = instr->regs[1]->instr->name;
				continue;
			}
		}

		/* arrays which don't fit in one of the pre-defined class
		 * sizes are pre-colored:
		 */
		if ((id->cls >= 0) && (id->cls < total_class_count)) {
			/* in the scalar pass, we generate a name for each
			 * scalar component, instr->name is the name of the
			 * first component.
			 */
			unsigned n = ctx->scalar_pass ? dest_regs(instr) : 1;
			instr->name = ctx->class_alloc_count[id->cls];
			ctx->class_alloc_count[id->cls] += n;
			ctx->alloc_count += n;
		}
	}
}

static int
pick_in_range(BITSET_WORD *regs, unsigned min, unsigned max)
{
	for (unsigned i = min; i < max; i++) {
		if (BITSET_TEST(regs, i)) {
			return i;
		}
	}
	return -1;
}

/* register selector for the a6xx+ merged register file: */
static unsigned int
ra_select_reg_merged(unsigned int n, BITSET_WORD *regs, void *data)
{
	struct ir3_ra_ctx *ctx = data;
	unsigned int class = ra_get_node_class(ctx->g, n);

	/* dimensions within the register class: */
	unsigned max_target, start;

	/* the regs bitset will include *all* of the virtual regs, but we lay
	 * out the different classes consecutively in the virtual register
	 * space.  So we just need to think about the base offset of a given
	 * class within the virtual register space, and offset the register
	 * space we search within by that base offset.
	 */
	unsigned base;

	/* NOTE: this is only used in scalar pass, so the register
	 * class will be one of the scalar classes (ie. idx==0):
	 */
	if (class == ctx->set->high_classes[0]) {
		max_target = HIGH_CLASS_REGS(0);
		start = 0;
		base = ctx->set->gpr_to_ra_reg[HIGH_OFFSET][0];
	} else if (class == ctx->set->half_classes[0]) {
		max_target = ctx->max_target;
		start = ctx->start_search_reg;
		base = ctx->set->gpr_to_ra_reg[HALF_OFFSET][0];
	} else if (class == ctx->set->classes[0]) {
		max_target = ctx->max_target / 2;
		start = ctx->start_search_reg;
		base = ctx->set->gpr_to_ra_reg[0][0];
	} else {
		unreachable("unexpected register class!");
	}

	/* For cat4 instructions, if the src reg is already assigned, and
	 * avail to pick, use it.  Because this doesn't introduce unnecessary
	 * dependencies, and it potentially avoids needing (ss) syncs to
	 * for write after read hazards:
	 */
	struct hash_entry *entry = _mesa_hash_table_search(ctx->name_to_instr, &n);
	if (entry) {
		struct ir3_instruction *instr = entry->data;

		if (is_sfu(instr) && instr->regs[1]->instr) {
			struct ir3_instruction *src = instr->regs[1]->instr;
			unsigned src_n = scalar_name(ctx, src, 0);

			unsigned reg = ra_get_node_reg(ctx->g, src_n);

			/* Check if the src register has been assigned yet: */
			if (reg != NO_REG) {
				if (BITSET_TEST(regs, reg)) {
					return reg;
				}
			}
		}
	}

	int r = pick_in_range(regs, base + start, base + max_target);
	if (r < 0) {
		/* wrap-around: */
		r = pick_in_range(regs, base, base + start);
	}

	if (r < 0) {
		/* overflow, we need to increase max_target: */
		ctx->max_target++;
		return ra_select_reg_merged(n, regs, data);
	}

	if (class == ctx->set->half_classes[0]) {
		int n = r - base;
		ctx->start_search_reg = (n + 1) % ctx->max_target;
	} else if (class == ctx->set->classes[0]) {
		int n = (r - base) * 2;
		ctx->start_search_reg = (n + 1) % ctx->max_target;
	}

	return r;
}

static void
ra_init(struct ir3_ra_ctx *ctx)
{
	unsigned n, base;

	ir3_clear_mark(ctx->ir);
	n = ir3_count_instructions(ctx->ir);

	ctx->instrd = rzalloc_array(NULL, struct ir3_ra_instr_data, n);

	foreach_block (block, &ctx->ir->block_list) {
		ra_block_find_definers(ctx, block);
	}

	foreach_block (block, &ctx->ir->block_list) {
		ra_block_name_instructions(ctx, block);
	}

	/* figure out the base register name for each class.  The
	 * actual ra name is class_base[cls] + instr->name;
	 */
	ctx->class_base[0] = 0;
	for (unsigned i = 1; i <= total_class_count; i++) {
		ctx->class_base[i] = ctx->class_base[i-1] +
				ctx->class_alloc_count[i-1];
	}

	/* and vreg names for array elements: */
	base = ctx->class_base[total_class_count];
	foreach_array (arr, &ctx->ir->array_list) {
		arr->base = base;
		ctx->class_alloc_count[total_class_count] += reg_size_for_array(arr);
		base += reg_size_for_array(arr);
	}
	ctx->alloc_count += ctx->class_alloc_count[total_class_count];

	ctx->g = ra_alloc_interference_graph(ctx->set->regs, ctx->alloc_count);
	ralloc_steal(ctx->g, ctx->instrd);
	ctx->def = rzalloc_array(ctx->g, unsigned, ctx->alloc_count);
	ctx->use = rzalloc_array(ctx->g, unsigned, ctx->alloc_count);

	/* TODO add selector callback for split (pre-a6xx) register file: */
	if (ctx->scalar_pass && (ctx->ir->compiler->gpu_id >= 600)) {
		ra_set_select_reg_callback(ctx->g, ra_select_reg_merged, ctx);

		ctx->name_to_instr = _mesa_hash_table_create(ctx->g,
				_mesa_hash_int, _mesa_key_int_equal);
	}
}

static unsigned
__ra_name(struct ir3_ra_ctx *ctx, int cls, struct ir3_instruction *defn)
{
	unsigned name;
	debug_assert(cls >= 0);
	debug_assert(cls < total_class_count);  /* we shouldn't get arrays here.. */
	name = ctx->class_base[cls] + defn->name;
	debug_assert(name < ctx->alloc_count);
	return name;
}

static int
ra_name(struct ir3_ra_ctx *ctx, struct ir3_ra_instr_data *id)
{
	/* TODO handle name mapping for arrays */
	return __ra_name(ctx, id->cls, id->defn);
}

/* Get the scalar name of the n'th component of an instruction dst: */
static int
scalar_name(struct ir3_ra_ctx *ctx, struct ir3_instruction *instr, unsigned n)
{
	if (ctx->scalar_pass) {
		if (instr->opc == OPC_META_SPLIT) {
			debug_assert(n == 0);     /* split results in a scalar */
			struct ir3_instruction *src = instr->regs[1]->instr;
			return scalar_name(ctx, src, instr->split.off);
		} else if (instr->opc == OPC_META_COLLECT) {
			debug_assert(n < (instr->regs_count + 1));
			struct ir3_instruction *src = instr->regs[n + 1]->instr;
			return scalar_name(ctx, src, 0);
		}
	} else {
		debug_assert(n == 0);
	}

	return ra_name(ctx, &ctx->instrd[instr->ip]) + n;
}

static void
ra_destroy(struct ir3_ra_ctx *ctx)
{
	ralloc_free(ctx->g);
}

static void
__def(struct ir3_ra_ctx *ctx, struct ir3_ra_block_data *bd, unsigned name,
		struct ir3_instruction *instr)
{
	debug_assert(name < ctx->alloc_count);
	/* defined on first write: */
	if (!ctx->def[name])
		ctx->def[name] = instr->ip;
	ctx->use[name] = MAX2(ctx->use[name], instr->ip);
	BITSET_SET(bd->def, name);
}

static void
__use(struct ir3_ra_ctx *ctx, struct ir3_ra_block_data *bd, unsigned name,
		struct ir3_instruction *instr)
{
	debug_assert(name < ctx->alloc_count);
	ctx->use[name] = MAX2(ctx->use[name], instr->ip);
	if (!BITSET_TEST(bd->def, name))
		BITSET_SET(bd->use, name);
}

static void
ra_block_compute_live_ranges(struct ir3_ra_ctx *ctx, struct ir3_block *block)
{
	struct ir3_ra_block_data *bd;
	unsigned bitset_words = BITSET_WORDS(ctx->alloc_count);

#define def(name, instr) __def(ctx, bd, name, instr)
#define use(name, instr) __use(ctx, bd, name, instr)

	bd = rzalloc(ctx->g, struct ir3_ra_block_data);

	bd->def     = rzalloc_array(bd, BITSET_WORD, bitset_words);
	bd->use     = rzalloc_array(bd, BITSET_WORD, bitset_words);
	bd->livein  = rzalloc_array(bd, BITSET_WORD, bitset_words);
	bd->liveout = rzalloc_array(bd, BITSET_WORD, bitset_words);

	block->data = bd;

	struct ir3_instruction *first_non_input = NULL;
	foreach_instr (instr, &block->instr_list) {
		if (instr->opc != OPC_META_INPUT) {
			first_non_input = instr;
			break;
		}
	}

	foreach_instr (instr, &block->instr_list) {
		struct ir3_instruction *src;
		struct ir3_register *reg;

		if (writes_gpr(instr)) {
			struct ir3_ra_instr_data *id = &ctx->instrd[instr->ip];
			struct ir3_register *dst = instr->regs[0];

			if (dst->flags & IR3_REG_ARRAY) {
				struct ir3_array *arr =
					ir3_lookup_array(ctx->ir, dst->array.id);
				unsigned i;

				arr->start_ip = MIN2(arr->start_ip, instr->ip);
				arr->end_ip = MAX2(arr->end_ip, instr->ip);

				/* set the node class now.. in case we don't encounter
				 * this array dst again.  From register_alloc algo's
				 * perspective, these are all single/scalar regs:
				 */
				for (i = 0; i < arr->length; i++) {
					unsigned name = arr->base + i;
					if(arr->half)
						ra_set_node_class(ctx->g, name, ctx->set->half_classes[0]);
					else
						ra_set_node_class(ctx->g, name, ctx->set->classes[0]);
				}

				/* indirect write is treated like a write to all array
				 * elements, since we don't know which one is actually
				 * written:
				 */
				if (dst->flags & IR3_REG_RELATIV) {
					for (i = 0; i < arr->length; i++) {
						unsigned name = arr->base + i;
						def(name, instr);
					}
				} else {
					unsigned name = arr->base + dst->array.offset;
					def(name, instr);
				}
			} else if (id->defn == instr) {
				/* in scalar pass, we aren't considering virtual register
				 * classes, ie. if an instruction writes a vec2, then it
				 * defines two different scalar register names.
				 */
				unsigned n = ctx->scalar_pass ? dest_regs(instr) : 1;
				for (unsigned i = 0; i < n; i++) {
					unsigned name = scalar_name(ctx, instr, i);

					/* tex instructions actually have a wrmask, and
					 * don't touch masked out components.  We can't do
					 * anything useful about that in the first pass,
					 * but in the scalar pass we can realize these
					 * registers are available:
					 */
					if (ctx->scalar_pass && is_tex_or_prefetch(instr) &&
							!(instr->regs[0]->wrmask & (1 << i)))
						continue;

					def(name, instr);

					if (ctx->name_to_instr && is_sfu(instr)) {
						/* this is slightly annoying, we can't just use an
						 * integer on the stack
						 */
						unsigned *key = ralloc(ctx->name_to_instr, unsigned);
						*key = name;
						debug_assert(!_mesa_hash_table_search(ctx->name_to_instr, key));
						_mesa_hash_table_insert(ctx->name_to_instr, key, instr);
					}

					if ((instr->opc == OPC_META_INPUT) && first_non_input)
						use(name, first_non_input);

					if (is_high(instr)) {
						ra_set_node_class(ctx->g, name,
								ctx->set->high_classes[id->cls - HIGH_OFFSET]);
					} else if (is_half(instr)) {
						ra_set_node_class(ctx->g, name,
								ctx->set->half_classes[id->cls - HALF_OFFSET]);
					} else {
						ra_set_node_class(ctx->g, name,
								ctx->set->classes[id->cls]);
					}
				}
			}
		}

		foreach_src(reg, instr) {
			if (reg->flags & IR3_REG_ARRAY) {
				struct ir3_array *arr =
					ir3_lookup_array(ctx->ir, reg->array.id);
				arr->start_ip = MIN2(arr->start_ip, instr->ip);
				arr->end_ip = MAX2(arr->end_ip, instr->ip);

				/* indirect read is treated like a read from all array
				 * elements, since we don't know which one is actually
				 * read:
				 */
				if (reg->flags & IR3_REG_RELATIV) {
					unsigned i;
					for (i = 0; i < arr->length; i++) {
						unsigned name = arr->base + i;
						use(name, instr);
						BITSET_SET(bd->use, name);
					}
				} else {
					unsigned name = arr->base + reg->array.offset;
					use(name, instr);
					/* NOTE: arrays are not SSA so unconditionally
					 * set use bit:
					 */
					BITSET_SET(bd->use, name);
					debug_assert(reg->array.offset < arr->length);
				}
			} else if (ctx->scalar_pass) {
				struct ir3_instruction *src = reg->instr;
				/* skip things that aren't SSA: */
				unsigned n = src ? dest_regs(src) : 0;

				/* in scalar pass, we aren't considering virtual register
				 * classes, ie. if an instruction writes a vec2, then it
				 * defines two different scalar register names.
				 *
				 * We need to traverse up thru collect/split to find the
				 * actual non-meta instruction names for each of the
				 * components:
				 */
				for (unsigned i = 0; i < n; i++) {
					/* Need to filter out a couple special cases, ie.
					 * writes to a0.x or p0.x:
					 */
					if (!writes_gpr(src))
						continue;

					/* split takes a src w/ wrmask potentially greater
					 * than 0x1, but it really only cares about a single
					 * component.  This shows up in splits coming out of
					 * a tex instruction w/ wrmask=.z, for example.
					 */
					if (ctx->scalar_pass && (instr->opc == OPC_META_SPLIT) &&
							!(i == instr->split.off))
						continue;

					use(scalar_name(ctx, src, i), instr);
				}
			} else if ((src = ssa(reg)) && writes_gpr(src)) {
				unsigned name = ra_name(ctx, &ctx->instrd[src->ip]);
				use(name, instr);
			}
		}
	}
}

static bool
ra_compute_livein_liveout(struct ir3_ra_ctx *ctx)
{
	unsigned bitset_words = BITSET_WORDS(ctx->alloc_count);
	bool progress = false;

	foreach_block (block, &ctx->ir->block_list) {
		struct ir3_ra_block_data *bd = block->data;

		/* update livein: */
		for (unsigned i = 0; i < bitset_words; i++) {
			BITSET_WORD new_livein =
				(bd->use[i] | (bd->liveout[i] & ~bd->def[i]));

			if (new_livein & ~bd->livein[i]) {
				bd->livein[i] |= new_livein;
				progress = true;
			}
		}

		/* update liveout: */
		for (unsigned j = 0; j < ARRAY_SIZE(block->successors); j++) {
			struct ir3_block *succ = block->successors[j];
			struct ir3_ra_block_data *succ_bd;

			if (!succ)
				continue;

			succ_bd = succ->data;

			for (unsigned i = 0; i < bitset_words; i++) {
				BITSET_WORD new_liveout =
					(succ_bd->livein[i] & ~bd->liveout[i]);

				if (new_liveout) {
					bd->liveout[i] |= new_liveout;
					progress = true;
				}
			}
		}
	}

	return progress;
}

static void
print_bitset(const char *name, BITSET_WORD *bs, unsigned cnt)
{
	bool first = true;
	debug_printf("  %s:", name);
	for (unsigned i = 0; i < cnt; i++) {
		if (BITSET_TEST(bs, i)) {
			if (!first)
				debug_printf(",");
			debug_printf(" %04u", i);
			first = false;
		}
	}
	debug_printf("\n");
}

static void
ra_add_interference(struct ir3_ra_ctx *ctx)
{
	struct ir3 *ir = ctx->ir;

	/* initialize array live ranges: */
	foreach_array (arr, &ir->array_list) {
		arr->start_ip = ~0;
		arr->end_ip = 0;
	}

	/* compute live ranges (use/def) on a block level, also updating
	 * block's def/use bitmasks (used below to calculate per-block
	 * livein/liveout):
	 */
	foreach_block (block, &ir->block_list) {
		ra_block_compute_live_ranges(ctx, block);
	}

	/* update per-block livein/liveout: */
	while (ra_compute_livein_liveout(ctx)) {}

	if (ir3_shader_debug & IR3_DBG_OPTMSGS) {
		debug_printf("AFTER LIVEIN/OUT:\n");
		foreach_block (block, &ir->block_list) {
			struct ir3_ra_block_data *bd = block->data;
			debug_printf("block%u:\n", block_id(block));
			print_bitset("  def", bd->def, ctx->alloc_count);
			print_bitset("  use", bd->use, ctx->alloc_count);
			print_bitset("  l/i", bd->livein, ctx->alloc_count);
			print_bitset("  l/o", bd->liveout, ctx->alloc_count);
		}
		foreach_array (arr, &ir->array_list) {
			debug_printf("array%u:\n", arr->id);
			debug_printf("  length:   %u\n", arr->length);
			debug_printf("  start_ip: %u\n", arr->start_ip);
			debug_printf("  end_ip:   %u\n", arr->end_ip);
		}
		debug_printf("INSTRUCTION VREG NAMES:\n");
		foreach_block (block, &ctx->ir->block_list) {
			foreach_instr (instr, &block->instr_list) {
				if (!ctx->instrd[instr->ip].defn)
					continue;
				debug_printf("%04u: ", scalar_name(ctx, instr, 0));
				ir3_print_instr(instr);
			}
		}
		debug_printf("ARRAY VREG NAMES:\n");
		foreach_array (arr, &ctx->ir->array_list) {
			debug_printf("%04u: arr%u\n", arr->base, arr->id);
		}
	}

	/* extend start/end ranges based on livein/liveout info from cfg: */
	foreach_block (block, &ir->block_list) {
		struct ir3_ra_block_data *bd = block->data;

		for (unsigned i = 0; i < ctx->alloc_count; i++) {
			if (BITSET_TEST(bd->livein, i)) {
				ctx->def[i] = MIN2(ctx->def[i], block->start_ip);
				ctx->use[i] = MAX2(ctx->use[i], block->start_ip);
			}

			if (BITSET_TEST(bd->liveout, i)) {
				ctx->def[i] = MIN2(ctx->def[i], block->end_ip);
				ctx->use[i] = MAX2(ctx->use[i], block->end_ip);
			}
		}

		foreach_array (arr, &ctx->ir->array_list) {
			for (unsigned i = 0; i < arr->length; i++) {
				if (BITSET_TEST(bd->livein, i + arr->base)) {
					arr->start_ip = MIN2(arr->start_ip, block->start_ip);
				}
				if (BITSET_TEST(bd->livein, i + arr->base)) {
					arr->end_ip = MAX2(arr->end_ip, block->end_ip);
				}
			}
		}
	}

	/* need to fix things up to keep outputs live: */
	struct ir3_instruction *out;
	foreach_output(out, ir) {
		unsigned name = ra_name(ctx, &ctx->instrd[out->ip]);
		ctx->use[name] = ctx->instr_cnt;
	}

	for (unsigned i = 0; i < ctx->alloc_count; i++) {
		for (unsigned j = 0; j < ctx->alloc_count; j++) {
			if (intersects(ctx->def[i], ctx->use[i],
					ctx->def[j], ctx->use[j])) {
				ra_add_node_interference(ctx->g, i, j);
			}
		}
	}
}

/* some instructions need fix-up if dst register is half precision: */
static void fixup_half_instr_dst(struct ir3_instruction *instr)
{
	switch (opc_cat(instr->opc)) {
	case 1: /* move instructions */
		instr->cat1.dst_type = half_type(instr->cat1.dst_type);
		break;
	case 3:
		switch (instr->opc) {
		case OPC_MAD_F32:
			/* Available for that dest is half and srcs are full.
			 * eg. mad.f32 hr0, r0.x, r0.y, r0.z
			 */
			if (instr->regs[1]->flags & IR3_REG_HALF)
				instr->opc = OPC_MAD_F16;
			break;
		case OPC_SEL_B32:
			instr->opc = OPC_SEL_B16;
			break;
		case OPC_SEL_S32:
			instr->opc = OPC_SEL_S16;
			break;
		case OPC_SEL_F32:
			instr->opc = OPC_SEL_F16;
			break;
		case OPC_SAD_S32:
			instr->opc = OPC_SAD_S16;
			break;
		/* instructions may already be fixed up: */
		case OPC_MAD_F16:
		case OPC_SEL_B16:
		case OPC_SEL_S16:
		case OPC_SEL_F16:
		case OPC_SAD_S16:
			break;
		default:
			assert(0);
			break;
		}
		break;
	case 4:
		switch (instr->opc) {
		case OPC_RSQ:
			instr->opc = OPC_HRSQ;
			break;
		case OPC_LOG2:
			instr->opc = OPC_HLOG2;
			break;
		case OPC_EXP2:
			instr->opc = OPC_HEXP2;
			break;
		default:
			break;
		}
		break;
	case 5:
		instr->cat5.type = half_type(instr->cat5.type);
		break;
	}
}
/* some instructions need fix-up if src register is half precision: */
static void fixup_half_instr_src(struct ir3_instruction *instr)
{
	switch (instr->opc) {
	case OPC_MOV:
		instr->cat1.src_type = half_type(instr->cat1.src_type);
		break;
	default:
		break;
	}
}

/* NOTE: instr could be NULL for IR3_REG_ARRAY case, for the first
 * array access(es) which do not have any previous access to depend
 * on from scheduling point of view
 */
static void
reg_assign(struct ir3_ra_ctx *ctx, struct ir3_register *reg,
		struct ir3_instruction *instr)
{
	struct ir3_ra_instr_data *id;

	if (reg->flags & IR3_REG_ARRAY) {
		struct ir3_array *arr =
			ir3_lookup_array(ctx->ir, reg->array.id);
		unsigned name = arr->base + reg->array.offset;
		unsigned r = ra_get_node_reg(ctx->g, name);
		unsigned num = ctx->set->ra_reg_to_gpr[r];

		if (reg->flags & IR3_REG_RELATIV) {
			reg->array.offset = num;
		} else {
			reg->num = num;
			reg->flags &= ~IR3_REG_SSA;
		}

		reg->flags &= ~IR3_REG_ARRAY;
	} else if ((id = &ctx->instrd[instr->ip]) && id->defn) {
		unsigned first_component = 0;

		/* Special case for tex instructions, which may use the wrmask
		 * to mask off the first component(s).  In the scalar pass,
		 * this means the masked off component(s) are not def'd/use'd,
		 * so we get a bogus value when we ask the register_allocate
		 * algo to get the assigned reg for the unused/untouched
		 * component.  So we need to consider the first used component:
		 */
		if (ctx->scalar_pass && is_tex_or_prefetch(id->defn)) {
			unsigned n = ffs(id->defn->regs[0]->wrmask);
			debug_assert(n > 0);
			first_component = n - 1;
		}

		unsigned name = scalar_name(ctx, id->defn, first_component);
		unsigned r = ra_get_node_reg(ctx->g, name);
		unsigned num = ctx->set->ra_reg_to_gpr[r] + id->off;

		debug_assert(!(reg->flags & IR3_REG_RELATIV));

		debug_assert(num >= first_component);

		if (is_high(id->defn))
			num += FIRST_HIGH_REG;

		reg->num = num - first_component;

		reg->flags &= ~IR3_REG_SSA;

		if (is_half(id->defn))
			reg->flags |= IR3_REG_HALF;
	}
}

static void
account_assignment(struct ir3_ra_ctx *ctx, struct ir3_instruction *instr)
{
	struct ir3_ra_instr_data *id;
	struct ir3_register *dst = instr->regs[0];
	unsigned max;

	if (is_high(instr))
		return;

	if (dst->flags & IR3_REG_ARRAY) {
		struct ir3_array *arr =
			ir3_lookup_array(ctx->ir, dst->array.id);
		max = arr->reg + arr->length;
	} else if ((id = &ctx->instrd[instr->ip]) && id->defn) {
		unsigned name = scalar_name(ctx, id->defn, 0);
		unsigned r = ra_get_node_reg(ctx->g, name);
		max = ctx->set->ra_reg_to_gpr[r] + id->off;
	} else {
		return;
	}

	if (is_half(instr)) {
		ctx->max_half_assigned = MAX2(ctx->max_half_assigned, max);
	} else {
		ctx->max_assigned = MAX2(ctx->max_assigned, max);
	}
}

/* helper to determine which regs to assign in which pass: */
static bool
should_assign(struct ir3_ra_ctx *ctx, struct ir3_instruction *instr)
{
	if ((instr->opc == OPC_META_SPLIT) ||
			(instr->opc == OPC_META_COLLECT))
		return !ctx->scalar_pass;
	return ctx->scalar_pass;
}

static void
ra_block_alloc(struct ir3_ra_ctx *ctx, struct ir3_block *block)
{
	foreach_instr (instr, &block->instr_list) {
		struct ir3_register *reg;

		if (writes_gpr(instr)) {
			account_assignment(ctx, instr);
			if (should_assign(ctx, instr)) {
				reg_assign(ctx, instr->regs[0], instr);
				if (instr->regs[0]->flags & IR3_REG_HALF)
					fixup_half_instr_dst(instr);
			}
		}

		foreach_src_n(reg, n, instr) {
			struct ir3_instruction *src = reg->instr;

			if (src && !should_assign(ctx, src) && !should_assign(ctx, instr))
				continue;

			if (src && should_assign(ctx, instr))
				reg_assign(ctx, src->regs[0], src);

			/* Note: reg->instr could be null for IR3_REG_ARRAY */
			if (src || (reg->flags & IR3_REG_ARRAY))
				reg_assign(ctx, instr->regs[n+1], src);

			if (instr->regs[n+1]->flags & IR3_REG_HALF)
				fixup_half_instr_src(instr);
		}
	}

	/* We need to pre-color outputs for the scalar pass in
	 * ra_precolor_assigned(), so we need to actually assign
	 * them in the first pass:
	 */
	if (!ctx->scalar_pass) {
		struct ir3_instruction *in, *out;

		foreach_input (in, ctx->ir) {
			reg_assign(ctx, in->regs[0], in);
		}
		foreach_output (out, ctx->ir) {
			reg_assign(ctx, out->regs[0], out);
		}
	}
}

/* handle pre-colored registers.  This includes "arrays" (which could be of
 * length 1, used for phi webs lowered to registers in nir), as well as
 * special shader input values that need to be pinned to certain registers.
 */
static void
ra_precolor(struct ir3_ra_ctx *ctx, struct ir3_instruction **precolor, unsigned nprecolor)
{
	unsigned num_precolor = 0;
	for (unsigned i = 0; i < nprecolor; i++) {
		if (precolor[i] && !(precolor[i]->flags & IR3_INSTR_UNUSED)) {
			struct ir3_instruction *instr = precolor[i];

			if (instr->regs[0]->num == INVALID_REG)
				continue;

			struct ir3_ra_instr_data *id = &ctx->instrd[instr->ip];

			debug_assert(!(instr->regs[0]->flags & (IR3_REG_HALF | IR3_REG_HIGH)));

			/* only consider the first component: */
			if (id->off > 0)
				continue;

			if (ctx->scalar_pass && !should_assign(ctx, instr))
				continue;

			/* 'base' is in scalar (class 0) but we need to map that
			 * the conflicting register of the appropriate class (ie.
			 * input could be vec2/vec3/etc)
			 *
			 * Note that the higher class (larger than scalar) regs
			 * are setup to conflict with others in the same class,
			 * so for example, R1 (scalar) is also the first component
			 * of D1 (vec2/double):
			 *
			 *    Single (base) |  Double
			 *    --------------+---------------
			 *       R0         |  D0
			 *       R1         |  D0 D1
			 *       R2         |     D1 D2
			 *       R3         |        D2
			 *           .. and so on..
			 */
			unsigned regid = instr->regs[0]->num;
			unsigned reg = ctx->set->gpr_to_ra_reg[id->cls][regid];
			unsigned name = ra_name(ctx, id);
			ra_set_node_reg(ctx->g, name, reg);
			num_precolor = MAX2(regid, num_precolor);
		}
	}

	/* pre-assign array elements:
	 *
	 * TODO this is going to need some work for half-precision.. possibly
	 * this is easier on a6xx, where we can just divide array size by two?
	 * But on a5xx and earlier it will need to track two bases.
	 */
	foreach_array (arr, &ctx->ir->array_list) {
		unsigned base = 0;

		if (arr->end_ip == 0)
			continue;

		/* figure out what else we conflict with which has already
		 * been assigned:
		 */
retry:
		foreach_array (arr2, &ctx->ir->array_list) {
			if (arr2 == arr)
				break;
			if (arr2->end_ip == 0)
				continue;
			/* if it intersects with liverange AND register range.. */
			if (intersects(arr->start_ip, arr->end_ip,
					arr2->start_ip, arr2->end_ip) &&
				intersects(base, base + reg_size_for_array(arr),
					arr2->reg, arr2->reg + reg_size_for_array(arr2))) {
				base = MAX2(base, arr2->reg + reg_size_for_array(arr2));
				goto retry;
			}
		}

		/* also need to not conflict with any pre-assigned inputs: */
		for (unsigned i = 0; i < nprecolor; i++) {
			struct ir3_instruction *instr = precolor[i];

			if (!instr || (instr->flags & IR3_INSTR_UNUSED))
				continue;

			struct ir3_ra_instr_data *id = &ctx->instrd[instr->ip];

			/* only consider the first component: */
			if (id->off > 0)
				continue;

			unsigned name = ra_name(ctx, id);
			unsigned regid = instr->regs[0]->num;

			/* Check if array intersects with liverange AND register
			 * range of the input:
			 */
			if (intersects(arr->start_ip, arr->end_ip,
							ctx->def[name], ctx->use[name]) &&
					intersects(base, base + reg_size_for_array(arr),
							regid, regid + class_sizes[id->cls])) {
				base = MAX2(base, regid + class_sizes[id->cls]);
				goto retry;
			}
		}

		arr->reg = base;

		for (unsigned i = 0; i < arr->length; i++) {
			unsigned name, reg;

			if (arr->half) {
				/* Doesn't need to do this on older generations than a6xx,
				 * since there's no conflict between full regs and half regs
				 * on them.
				 *
				 * TODO Presumably "base" could start from 0 respectively
				 * for half regs of arrays on older generations.
				 */
				unsigned base_half = base * 2 + i;
				reg = ctx->set->gpr_to_ra_reg[0+HALF_OFFSET][base_half];
				base = base_half / 2 + 1;
			} else {
				reg = ctx->set->gpr_to_ra_reg[0][base++];
			}

			name = arr->base + i;
			ra_set_node_reg(ctx->g, name, reg);
		}
	}

	if (ir3_shader_debug & IR3_DBG_OPTMSGS) {
		foreach_array (arr, &ctx->ir->array_list) {
			unsigned first = arr->reg;
			unsigned last  = arr->reg + arr->length - 1;
			debug_printf("arr[%d] at r%d.%c->r%d.%c\n", arr->id,
					(first >> 2), "xyzw"[first & 0x3],
					(last >> 2), "xyzw"[last & 0x3]);
		}
	}
}

static void
precolor(struct ir3_ra_ctx *ctx, struct ir3_instruction *instr)
{
	struct ir3_ra_instr_data *id = &ctx->instrd[instr->ip];
	unsigned n = dest_regs(instr);
	for (unsigned i = 0; i < n; i++) {
		/* tex instructions actually have a wrmask, and
		 * don't touch masked out components.  So we
		 * shouldn't precolor them::
		 */
		if (is_tex_or_prefetch(instr) &&
				!(instr->regs[0]->wrmask & (1 << i)))
			continue;

		unsigned name = scalar_name(ctx, instr, i);
		unsigned regid = instr->regs[0]->num + i;

		if (instr->regs[0]->flags & IR3_REG_HIGH)
			regid -= FIRST_HIGH_REG;

		unsigned vreg = ctx->set->gpr_to_ra_reg[id->cls][regid];
		ra_set_node_reg(ctx->g, name, vreg);
	}
}

/* pre-color non-scalar registers based on the registers assigned in previous
 * pass.  Do this by looking actually at the fanout instructions.
 */
static void
ra_precolor_assigned(struct ir3_ra_ctx *ctx)
{
	debug_assert(ctx->scalar_pass);

	foreach_block (block, &ctx->ir->block_list) {
		foreach_instr (instr, &block->instr_list) {

			if ((instr->opc != OPC_META_SPLIT) &&
					(instr->opc != OPC_META_COLLECT))
				continue;

			precolor(ctx, instr);

			struct ir3_register *src;
			foreach_src (src, instr) {
				if (!src->instr)
					continue;
				precolor(ctx, src->instr);
			}
		}
	}
}

static int
ra_alloc(struct ir3_ra_ctx *ctx)
{
	if (!ra_allocate(ctx->g))
		return -1;

	foreach_block (block, &ctx->ir->block_list) {
		ra_block_alloc(ctx, block);
	}

	return 0;
}

/* if we end up with split/collect instructions with non-matching src
 * and dest regs, that means something has gone wrong.  Which makes it
 * a pretty good sanity check.
 */
static void
ra_sanity_check(struct ir3 *ir)
{
	foreach_block (block, &ir->block_list) {
		foreach_instr (instr, &block->instr_list) {
			if (instr->opc == OPC_META_SPLIT) {
				struct ir3_register *dst = instr->regs[0];
				struct ir3_register *src = instr->regs[1];
				debug_assert(dst->num == (src->num + instr->split.off));
			} else if (instr->opc == OPC_META_COLLECT) {
				struct ir3_register *dst = instr->regs[0];
				struct ir3_register *src;

				foreach_src_n (src, n, instr) {
					debug_assert(dst->num == (src->num - n));
				}
			}
		}
	}
}

/* Target is calculated in terms of half-regs (with a full reg
 * consisting of two half-regs).
 */
static void
ra_calc_merged_register_target(struct ir3_ra_ctx *ctx)
{
	const unsigned vec4 = 2 * 4;  // 8 half-regs
	unsigned t = MAX2(2 * ctx->max_assigned, ctx->max_half_assigned);

	/* second RA pass may have saved some regs, let's try to reclaim
	 * the benefit by adjusting the target downwards slightly:
	 */
	if (ir3_has_latency_to_hide(ctx->ir)) {
		if (t > 8 * vec4) {
			t -= 2 * vec4;
		} else if (t > 6 * vec4) {
			t -= vec4;
		}
	}

	ctx->max_target = t;
}

static int
ir3_ra_pass(struct ir3_shader_variant *v, struct ir3_instruction **precolor,
		unsigned nprecolor, bool scalar_pass, unsigned *target)
{
	struct ir3_ra_ctx ctx = {
			.v = v,
			.ir = v->ir,
			.set = v->ir->compiler->set,
			.scalar_pass = scalar_pass,
	};
	int ret;

	if (scalar_pass) {
		ctx.max_target = *target;
	}

	ra_init(&ctx);
	ra_add_interference(&ctx);
	ra_precolor(&ctx, precolor, nprecolor);
	if (scalar_pass)
		ra_precolor_assigned(&ctx);
	ret = ra_alloc(&ctx);
	ra_destroy(&ctx);

	/* In the first pass, calculate the target register usage used in the
	 * second (scalar) pass:
	 */
	if (!scalar_pass) {
		/* TODO: round-robin support for pre-a6xx: */
		if (ctx.ir->compiler->gpu_id >= 600) {
			ra_calc_merged_register_target(&ctx);
		}
		*target = ctx.max_target;
	}

	return ret;
}

int
ir3_ra(struct ir3_shader_variant *v, struct ir3_instruction **precolor,
		unsigned nprecolor)
{
	unsigned target = 0;
	int ret;

	/* First pass, assign the vecN (non-scalar) registers: */
	ret = ir3_ra_pass(v, precolor, nprecolor, false, &target);
	if (ret)
		return ret;

	if (ir3_shader_debug & IR3_DBG_OPTMSGS) {
		printf("AFTER RA (1st pass):\n");
		ir3_print(v->ir);
	}

	/* Second pass, assign the scalar registers: */
	ret = ir3_ra_pass(v, precolor, nprecolor, true, &target);
	if (ret)
		return ret;

	if (ir3_shader_debug & IR3_DBG_OPTMSGS) {
		printf("AFTER RA (2nd pass):\n");
		ir3_print(v->ir);
	}

#ifdef DEBUG
#  define SANITY_CHECK DEBUG
#else
#  define SANITY_CHECK 0
#endif
	if (SANITY_CHECK)
		ra_sanity_check(v->ir);

	return ret;
}