aboutsummaryrefslogtreecommitdiffstats
path: root/src/panfrost/bifrost/bi_pack.c
blob: 211c9e0fa1acbaa6321dc9d52e9c0035869c0f77 (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
/*
 * Copyright (C) 2020 Collabora, Ltd.
 *
 * 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.
 */

#include "compiler.h"

#define RETURN_PACKED(str) { \
        uint64_t temp = 0; \
        memcpy(&temp, &str, sizeof(str)); \
        return temp; \
}

/* This file contains the final passes of the compiler. Running after
 * scheduling and RA, the IR is now finalized, so we need to emit it to actual
 * bits on the wire (as well as fixup branches) */

static uint64_t
bi_pack_header(bi_clause *clause, bi_clause *next, bool is_fragment)
{
        struct bifrost_header header = {
                .back_to_back = clause->back_to_back,
                .no_end_of_shader = (next != NULL),
                .elide_writes = is_fragment,
                .branch_cond = clause->branch_conditional,
                .datareg_writebarrier = clause->data_register_write_barrier,
                .datareg = clause->data_register,
                .scoreboard_deps = next ? next->dependencies : 0,
                .scoreboard_index = clause->scoreboard_id,
                .clause_type = clause->clause_type,
                .next_clause_type = next ? next->clause_type : 0,
        };

        header.branch_cond |= header.back_to_back;

        uint64_t u = 0;
        memcpy(&u, &header, sizeof(header));
        return u;
}

/* Represents the assignment of ports for a given bundle */

struct bi_registers {
        /* Register to assign to each port */
        unsigned port[4];

        /* Read ports can be disabled */
        bool enabled[2];

        /* Should we write FMA? what about ADD? If only a single port is
         * enabled it is in port 2, else ADD/FMA is 2/3 respectively */
        bool write_fma, write_add;

        /* Should we read with port 3? */
        bool read_port3;

        /* Packed uniform/constant */
        uint8_t uniform_constant;

        /* Whether writes are actually for the last instruction */
        bool first_instruction;
};

static inline void
bi_print_ports(struct bi_registers *regs)
{
        for (unsigned i = 0; i < 2; ++i) {
                if (regs->enabled[i])
                        printf("port %u: %u\n", i, regs->port[i]);
        }

        if (regs->write_fma || regs->write_add) {
                printf("port 2 (%s): %u\n",
                                regs->write_add ? "ADD" : "FMA",
                                regs->port[2]);
        }

        if ((regs->write_fma && regs->write_add) || regs->read_port3) {
                printf("port 3 (%s): %u\n",
                                regs->read_port3 ? "read" : "FMA",
                                regs->port[3]);
        }
}

/* The uniform/constant slot allows loading a contiguous 64-bit immediate or
 * pushed uniform per bundle. Figure out which one we need in the bundle (the
 * scheduler needs to ensure we only have one type per bundle), validate
 * everything, and rewrite away the register/uniform indices to use 3-bit
 * sources directly. */

static unsigned
bi_lookup_constant(bi_clause *clause, uint64_t cons, bool *hi, bool b64)
{
        uint64_t want = (cons >> 4);

        for (unsigned i = 0; i < clause->constant_count; ++i) {
                /* Only check top 60-bits since that's what's actually embedded
                 * in the clause, the bottom 4-bits are bundle-inline */

                uint64_t candidates[2] = {
                        clause->constants[i] >> 4,
                        clause->constants[i] >> 36
                };

                /* For <64-bit mode, we treat lo/hi separately */

                if (!b64)
                        candidates[0] &= (0xFFFFFFFF >> 4);

                if (candidates[0] == want)
                        return i;

                if (candidates[1] == want && !b64) {
                        *hi = true;
                        return i;
                }
        }

        unreachable("Invalid constant accessed");
}

static unsigned
bi_constant_field(unsigned idx)
{
        assert(idx <= 5);

        const unsigned values[] = {
                4, 5, 6, 7, 2, 3
        };

        return values[idx] << 4;
}

static bool
bi_assign_uniform_constant_single(
                struct bi_registers *regs,
                bi_clause *clause,
                bi_instruction *ins, bool assigned, bool fast_zero)
{
        if (!ins)
                return assigned;

        if (ins->type == BI_BLEND) {
                assert(!assigned);
                regs->uniform_constant = 0x8;
                return true;
        }

        bi_foreach_src(ins, s) {
                if (s == 0 && (ins->type == BI_LOAD_VAR_ADDRESS || ins->type == BI_LOAD_ATTR)) continue;

                if (ins->src[s] & BIR_INDEX_CONSTANT) {
                        bool hi = false;
                        bool b64 = nir_alu_type_get_type_size(ins->src_types[s]) > 32;
                        uint64_t cons = bi_get_immediate(ins, s);
                        unsigned idx = bi_lookup_constant(clause, cons, &hi, b64);
                        unsigned lo = clause->constants[idx] & 0xF;
                        unsigned f = bi_constant_field(idx) | lo;

                        if (assigned && regs->uniform_constant != f)
                                unreachable("Mismatched uniform/const field: imm");

                        regs->uniform_constant = f;
                        ins->src[s] = BIR_INDEX_PASS | (hi ? BIFROST_SRC_CONST_HI : BIFROST_SRC_CONST_LO);
                        assigned = true;
                } else if (ins->src[s] & BIR_INDEX_ZERO && (ins->type == BI_LOAD_UNIFORM || ins->type == BI_LOAD_VAR)) {
                        /* XXX: HACK UNTIL WE HAVE HI MATCHING DUE TO OVERFLOW XXX */
                        ins->src[s] = BIR_INDEX_PASS | BIFROST_SRC_CONST_HI;
                } else if (ins->src[s] & BIR_INDEX_ZERO && !fast_zero) {
                        /* FMAs have a fast zero port, ADD needs to use the
                         * uniform/const port's special 0 mode handled here */
                        unsigned f = 0;

                        if (assigned && regs->uniform_constant != f)
                                unreachable("Mismatched uniform/const field: 0");

                        regs->uniform_constant = f;
                        ins->src[s] = BIR_INDEX_PASS | BIFROST_SRC_CONST_LO;
                        assigned = true;
                } else if (s & BIR_INDEX_UNIFORM) {
                        unreachable("Push uniforms not implemented yet");
                }
        }

        return assigned;
}

static void
bi_assign_uniform_constant(
                bi_clause *clause,
                struct bi_registers *regs,
                bi_bundle bundle)
{
        bool assigned =
                bi_assign_uniform_constant_single(regs, clause, bundle.fma, false, true);

        bi_assign_uniform_constant_single(regs, clause, bundle.add, assigned, false);
}

/* Assigns a port for reading, before anything is written */

static void
bi_assign_port_read(struct bi_registers *regs, unsigned src)
{
        /* We only assign for registers */
        if (!(src & BIR_INDEX_REGISTER))
                return;

        unsigned reg = src & ~BIR_INDEX_REGISTER;

        /* Check if we already assigned the port */
        for (unsigned i = 0; i <= 1; ++i) {
                if (regs->port[i] == reg && regs->enabled[i])
                        return;
        }

        if (regs->port[3] == reg && regs->read_port3)
                return;

        /* Assign it now */

        for (unsigned i = 0; i <= 1; ++i) {
                if (!regs->enabled[i]) {
                        regs->port[i] = reg;
                        regs->enabled[i] = true;
                        return;
                }
        }

        if (!regs->read_port3) {
                regs->port[3] = reg;
                regs->read_port3 = true;
                return;
        }

        bi_print_ports(regs);
        unreachable("Failed to find a free port for src");
}

static struct bi_registers
bi_assign_ports(bi_bundle now, bi_bundle prev)
{
        struct bi_registers regs = { 0 };

        /* We assign ports for the main register mechanism. Special ops
         * use the data registers, which has its own mechanism entirely
         * and thus gets skipped over here. */

        unsigned read_dreg = now.add &&
                bi_class_props[now.add->type] & BI_DATA_REG_SRC;

        unsigned write_dreg = prev.add &&
                bi_class_props[prev.add->type] & BI_DATA_REG_DEST;

        /* First, assign reads */

        if (now.fma)
                bi_foreach_src(now.fma, src)
                        bi_assign_port_read(&regs, now.fma->src[src]);

        if (now.add) {
                bi_foreach_src(now.add, src) {
                        if (!(src == 0 && read_dreg))
                                bi_assign_port_read(&regs, now.add->src[src]);
                }
        }

        /* Next, assign writes */

        if (prev.add && prev.add->dest & BIR_INDEX_REGISTER && !write_dreg) {
                regs.port[2] = prev.add->dest & ~BIR_INDEX_REGISTER;
                regs.write_add = true;
        }

        if (prev.fma && prev.fma->dest & BIR_INDEX_REGISTER) {
                unsigned r = prev.fma->dest & ~BIR_INDEX_REGISTER;

                if (regs.write_add) {
                        /* Scheduler constraint: cannot read 3 and write 2 */
                        assert(!regs.read_port3);
                        regs.port[3] = r;
                } else {
                        regs.port[2] = r;
                }

                regs.write_fma = true;
        }

        /* Finally, ensure port 1 > port 0 for the 63-x trick to function */

        if (regs.enabled[0] && regs.enabled[1] && regs.port[1] < regs.port[0]) {
                unsigned temp = regs.port[0];
                regs.port[0] = regs.port[1];
                regs.port[1] = temp;
        }

        return regs;
}

/* Determines the register control field, ignoring the first? flag */

static enum bifrost_reg_control
bi_pack_register_ctrl_lo(struct bi_registers r)
{
        if (r.write_fma) {
                if (r.write_add) {
                        assert(!r.read_port3);
                        return BIFROST_WRITE_ADD_P2_FMA_P3;
                } else {
                        if (r.read_port3)
                                return BIFROST_WRITE_FMA_P2_READ_P3;
                        else
                                return BIFROST_WRITE_FMA_P2;
                }
        } else if (r.write_add) {
                if (r.read_port3)
                        return BIFROST_WRITE_ADD_P2_READ_P3;
                else
                        return BIFROST_WRITE_ADD_P2;
        } else if (r.read_port3)
                return BIFROST_READ_P3;
        else
                return BIFROST_REG_NONE;
}

/* Ditto but account for the first? flag this time */

static enum bifrost_reg_control
bi_pack_register_ctrl(struct bi_registers r)
{
        enum bifrost_reg_control ctrl = bi_pack_register_ctrl_lo(r);

        if (r.first_instruction) {
                if (ctrl == BIFROST_REG_NONE)
                        ctrl = BIFROST_FIRST_NONE;
                else if (ctrl == BIFROST_WRITE_FMA_P2_READ_P3)
                        ctrl = BIFROST_FIRST_WRITE_FMA_P2_READ_P3;
                else
                        ctrl |= BIFROST_FIRST_NONE;
        }

        return ctrl;
}

static uint64_t
bi_pack_registers(struct bi_registers regs)
{
        enum bifrost_reg_control ctrl = bi_pack_register_ctrl(regs);
        struct bifrost_regs s = { 0 };
        uint64_t packed = 0;

        if (regs.enabled[1]) {
                /* Gotta save that bit!~ Required by the 63-x trick */
                assert(regs.port[1] > regs.port[0]);
                assert(regs.enabled[0]);

                /* Do the 63-x trick, see docs/disasm */
                if (regs.port[0] > 31) {
                        regs.port[0] = 63 - regs.port[0];
                        regs.port[1] = 63 - regs.port[1];
                }

                assert(regs.port[0] <= 31);
                assert(regs.port[1] <= 63);

                s.ctrl = ctrl;
                s.reg1 = regs.port[1];
                s.reg0 = regs.port[0];
        } else {
                /* Port 1 disabled, so set to zero and use port 1 for ctrl */
                s.ctrl = 0;
                s.reg1 = ctrl << 2;

                if (regs.enabled[0]) {
                        /* Bit 0 upper bit of port 0 */
                        s.reg1 |= (regs.port[0] >> 5);

                        /* Rest of port 0 in usual spot */
                        s.reg0 = (regs.port[0] & 0b11111);
                } else {
                        /* Bit 1 set if port 0 also disabled */
                        s.reg1 |= (1 << 1);
                }
        }

        /* When port 3 isn't used, we have to set it to port 2, and vice versa,
         * or INSTR_INVALID_ENC is raised. The reason is unknown. */

        bool has_port2 = regs.write_fma || regs.write_add;
        bool has_port3 = regs.read_port3 || (regs.write_fma && regs.write_add);

        if (!has_port3)
                regs.port[3] = regs.port[2];

        if (!has_port2)
                regs.port[2] = regs.port[3];

        s.reg3 = regs.port[3];
        s.reg2 = regs.port[2];
        s.uniform_const = regs.uniform_constant;

        memcpy(&packed, &s, sizeof(s));
        return packed;
}

static void
bi_set_data_register(bi_clause *clause, unsigned idx)
{
        assert(idx & BIR_INDEX_REGISTER);
        unsigned reg = idx & ~BIR_INDEX_REGISTER;
        assert(reg <= 63);
        clause->data_register = reg;
}

static void
bi_read_data_register(bi_clause *clause, bi_instruction *ins)
{
        bi_set_data_register(clause, ins->src[0]);
}

static void
bi_write_data_register(bi_clause *clause, bi_instruction *ins)
{
        bi_set_data_register(clause, ins->dest);
}

static enum bifrost_packed_src
bi_get_src_reg_port(struct bi_registers *regs, unsigned src)
{
        unsigned reg = src & ~BIR_INDEX_REGISTER;

        if (regs->port[0] == reg && regs->enabled[0])
                return BIFROST_SRC_PORT0;
        else if (regs->port[1] == reg && regs->enabled[1])
                return BIFROST_SRC_PORT1;
        else if (regs->port[3] == reg && regs->read_port3)
                return BIFROST_SRC_PORT3;
        else
                unreachable("Tried to access register with no port");
}

static enum bifrost_packed_src
bi_get_src(bi_instruction *ins, struct bi_registers *regs, unsigned s, bool is_fma)
{
        unsigned src = ins->src[s];

        if (src & BIR_INDEX_REGISTER)
                return bi_get_src_reg_port(regs, src);
        else if (src & BIR_INDEX_ZERO && is_fma)
                return BIFROST_SRC_STAGE;
        else if (src & BIR_INDEX_PASS)
                return src & ~BIR_INDEX_PASS;
        else
                unreachable("Unknown src");
}

/* Constructs a packed 2-bit swizzle for a 16-bit vec2 source. Source must be
 * 16-bit and written components must correspond to valid swizzles (component x
 * or y). */

static unsigned
bi_swiz16(bi_instruction *ins, unsigned src)
{
        assert(nir_alu_type_get_type_size(ins->src_types[src]) == 16);
        unsigned swizzle = 0;

        for (unsigned c = 0; c < 2; ++c) {
                if (!bi_writes_component(ins, src)) continue;

                unsigned k = ins->swizzle[src][c];
                assert(k <= 1);
                swizzle |= (k << c);
        }

        return swizzle;
}

static unsigned
bi_pack_fma_fma(bi_instruction *ins, struct bi_registers *regs)
{
        /* (-a)(-b) = ab, so we only need one negate bit */
        bool negate_mul = ins->src_neg[0] ^ ins->src_neg[1];

        if (ins->op.mscale) {
                assert(!(ins->src_abs[0] && ins->src_abs[1]));
                assert(!ins->src_abs[2] || !ins->src_neg[3] || !ins->src_abs[3]);

                /* We can have exactly one abs, and can flip the multiplication
                 * to make it fit if we have to */
                bool flip_ab = ins->src_abs[1];

                struct bifrost_fma_mscale pack = {
                        .src0 = bi_get_src(ins, regs, flip_ab ? 1 : 0, true),
                        .src1 = bi_get_src(ins, regs, flip_ab ? 0 : 1, true),
                        .src2 = bi_get_src(ins, regs, 2, true),
                        .src3 = bi_get_src(ins, regs, 3, true),
                        .mscale_mode = 0,
                        .mode = ins->outmod,
                        .src0_abs = ins->src_abs[0] || ins->src_abs[1],
                        .src1_neg = negate_mul,
                        .src2_neg = ins->src_neg[2],
                        .op = BIFROST_FMA_OP_MSCALE,
                };

                RETURN_PACKED(pack);
        } else if (ins->dest_type == nir_type_float32) {
                struct bifrost_fma_fma pack = {
                        .src0 = bi_get_src(ins, regs, 0, true),
                        .src1 = bi_get_src(ins, regs, 1, true),
                        .src2 = bi_get_src(ins, regs, 2, true),
                        .src0_abs = ins->src_abs[0],
                        .src1_abs = ins->src_abs[1],
                        .src2_abs = ins->src_abs[2],
                        .src0_neg = negate_mul,
                        .src2_neg = ins->src_neg[2],
                        .outmod = ins->outmod,
                        .roundmode = ins->roundmode,
                        .op = BIFROST_FMA_OP_FMA
                };

                RETURN_PACKED(pack);
        } else if (ins->dest_type == nir_type_float16) {
                struct bifrost_fma_fma16 pack = {
                        .src0 = bi_get_src(ins, regs, 0, true),
                        .src1 = bi_get_src(ins, regs, 1, true),
                        .src2 = bi_get_src(ins, regs, 2, true),
                        .swizzle_0 = bi_swiz16(ins, 0),
                        .swizzle_1 = bi_swiz16(ins, 1),
                        .swizzle_2 = bi_swiz16(ins, 2),
                        .src0_neg = negate_mul,
                        .src2_neg = ins->src_neg[2],
                        .outmod = ins->outmod,
                        .roundmode = ins->roundmode,
                        .op = BIFROST_FMA_OP_FMA16
                };

                RETURN_PACKED(pack);
        } else {
                unreachable("Invalid fma dest type");
        }
}

static unsigned
bi_pack_fma_addmin_f32(bi_instruction *ins, struct bi_registers *regs)
{
        unsigned op =
                (ins->type == BI_ADD) ? BIFROST_FMA_OP_FADD32 :
                (ins->op.minmax == BI_MINMAX_MIN) ? BIFROST_FMA_OP_FMIN32 :
                BIFROST_FMA_OP_FMAX32;

        struct bifrost_fma_add pack = {
                .src0 = bi_get_src(ins, regs, 0, true),
                .src1 = bi_get_src(ins, regs, 1, true),
                .src0_abs = ins->src_abs[0],
                .src1_abs = ins->src_abs[1],
                .src0_neg = ins->src_neg[0],
                .src1_neg = ins->src_neg[1],
                .unk = 0x0,
                .outmod = ins->outmod,
                .roundmode = (ins->type == BI_ADD) ? ins->roundmode : ins->minmax,
                .op = op
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_fmadd_min_f16(bi_instruction *ins, struct bi_registers *regs, bool FMA)
{
        unsigned op =
                (!FMA) ? ((ins->op.minmax == BI_MINMAX_MIN) ?
                        BIFROST_ADD_OP_FMIN16 : BIFROST_ADD_OP_FMAX16) :
                (ins->type == BI_ADD) ? BIFROST_FMA_OP_FADD16 :
                (ins->op.minmax == BI_MINMAX_MIN) ? BIFROST_FMA_OP_FMIN16 :
                BIFROST_FMA_OP_FMAX16;

        /* Absolute values are packed in a quirky way. Let k = src1 < src0. Let
         * l be an auxiliary bit we encode. Then the hardware determines:
         *
         *      abs0 = l || k
         *      abs1 = l && k
         *
         * Since add/min/max are commutative, this saves a bit by using the
         * order of the operands as a bit (k). To pack this, first note:
         *
         *      (l && k) implies (l || k).
         *
         * That is, if the second argument is abs'd, then the first argument
         * also has abs. So there are three cases:
         *
         * Case 0: Neither src has absolute value. Then we have l = k = 0.
         *
         * Case 1: Exactly one src has absolute value. Assign that source to
         * src0 and the other source to src1. Compute k = src1 < src0 based on
         * that assignment. Then l = ~k.
         *
         * Case 2: Both sources have absolute value. Then we have l = k = 1.
         * Note to force k = 1 requires that (src1 < src0) OR (src0 < src1).
         * That is, this encoding is only valid if src1 and src0 are distinct.
         * This is a scheduling restriction (XXX); if an op of this type
         * requires both identical sources to have abs value, then we must
         * schedule to ADD (which does not use this ordering trick).
         */

        unsigned abs_0 = ins->src_abs[0], abs_1 = ins->src_abs[1];
        unsigned src_0 = bi_get_src(ins, regs, 0, true);
        unsigned src_1 = bi_get_src(ins, regs, 1, true);
        bool l = false;
        bool flip = false;

        assert(!(abs_0 && abs_1));

        if (!abs_0 && !abs_1) {
                /* Force k = 0 <===> NOT(src1 < src0) */
                flip = (src_1 < src_0);
        } else if (abs_0 && !abs_1) {
                l = src_1 >= src_0;
        } else if (abs_1 && !abs_0) {
                flip = true;
                l = src_0 >= src_1;
        } else {
                flip = (src_0 >= src_1);
                l = true;
        }

        if (FMA) {
                struct bifrost_fma_add_minmax16 pack = {
                        .src0 = flip ? src_1 : src_0,
                        .src1 = flip ? src_0 : src_1,
                        .src0_neg = ins->src_neg[flip ? 1 : 0],
                        .src1_neg = ins->src_neg[flip ? 0 : 1],
                        .abs1 = l,
                        .outmod = ins->outmod,
                        .mode = (ins->type == BI_ADD) ? ins->roundmode : ins->minmax,
                        .op = op
                };

                RETURN_PACKED(pack);
        } else {
                /* Can't have modes for fp16 */
                assert(ins->outmod == 0);

                struct bifrost_add_fmin16 pack = {
                        .src0 = flip ? src_1 : src_0,
                        .src1 = flip ? src_0 : src_1,
                        .src0_neg = ins->src_neg[flip ? 1 : 0],
                        .src1_neg = ins->src_neg[flip ? 0 : 1],
                        .abs1 = l,
                        .src0_swizzle = bi_swiz16(ins, 0),
                        .src1_swizzle = bi_swiz16(ins, 1), 
                        .mode = ins->minmax,
                        .op = op
                };

                RETURN_PACKED(pack);
        }
}

static unsigned
bi_pack_fma_addmin(bi_instruction *ins, struct bi_registers *regs)
{
        if (ins->dest_type == nir_type_float32)
                return bi_pack_fma_addmin_f32(ins, regs);
        else if(ins->dest_type == nir_type_float16)
                return bi_pack_fmadd_min_f16(ins, regs, true);
        else
                unreachable("Unknown FMA/ADD type");
}

static unsigned
bi_pack_fma_1src(bi_instruction *ins, struct bi_registers *regs, unsigned op)
{
        struct bifrost_fma_inst pack = {
                .src0 = bi_get_src(ins, regs, 0, true),
                .op = op
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_fma_2src(bi_instruction *ins, struct bi_registers *regs, unsigned op)
{
        struct bifrost_fma_2src pack = {
                .src0 = bi_get_src(ins, regs, 0, true),
                .src1 = bi_get_src(ins, regs, 1, true),
                .op = op
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_1src(bi_instruction *ins, struct bi_registers *regs, unsigned op)
{
        struct bifrost_add_inst pack = {
                .src0 = bi_get_src(ins, regs, 0, true),
                .op = op
        };

        RETURN_PACKED(pack);
}

static enum bifrost_csel_cond
bi_cond_to_csel(enum bi_cond cond, bool *flip, bool *invert, nir_alu_type T)
{
        nir_alu_type B = nir_alu_type_get_base_type(T);
        unsigned idx = (B == nir_type_float) ? 0 :
                ((B == nir_type_int) ? 1 : 2);

        switch (cond){
        case BI_COND_LT:
                *flip = true;
        case BI_COND_GT: {
                const enum bifrost_csel_cond ops[] = {
                        BIFROST_FGT_F,
                        BIFROST_IGT_I,
                        BIFROST_UGT_I
                };

                return ops[idx];
        }
        case BI_COND_LE:
                *flip = true;
        case BI_COND_GE: {
                const enum bifrost_csel_cond ops[] = {
                        BIFROST_FGE_F,
                        BIFROST_IGE_I,
                        BIFROST_UGE_I
                };

                return ops[idx];
        }
        case BI_COND_NE:
                *invert = true;
        case BI_COND_EQ: {
                const enum bifrost_csel_cond ops[] = {
                        BIFROST_FEQ_F,
                        BIFROST_IEQ_F,
                        BIFROST_IEQ_F /* sign is irrelevant */
                };

                return ops[idx];
        }
        default:
                unreachable("Invalid op for csel");
        }
}

static unsigned
bi_pack_fma_csel(bi_instruction *ins, struct bi_registers *regs)
{
        /* TODO: Use csel3 as well */
        bool flip = false, invert = false;

        enum bifrost_csel_cond cond =
                bi_cond_to_csel(ins->csel_cond, &flip, &invert, ins->src_types[0]);

        unsigned size = nir_alu_type_get_type_size(ins->dest_type);

        unsigned cmp_0 = (flip ? 1 : 0);
        unsigned cmp_1 = (flip ? 0 : 1);
        unsigned res_0 = (invert ? 3 : 2);
        unsigned res_1 = (invert ? 2 : 3);
        
        struct bifrost_csel4 pack = {
                .src0 = bi_get_src(ins, regs, cmp_0, true),
                .src1 = bi_get_src(ins, regs, cmp_1, true),
                .src2 = bi_get_src(ins, regs, res_0, true),
                .src3 = bi_get_src(ins, regs, res_1, true),
                .cond = cond,
                .op = (size == 16) ? BIFROST_FMA_OP_CSEL4_V16 :
                        BIFROST_FMA_OP_CSEL4
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_fma_frexp(bi_instruction *ins, struct bi_registers *regs)
{
        unsigned op = BIFROST_FMA_OP_FREXPE_LOG;
        return bi_pack_fma_1src(ins, regs, op);
}

static unsigned
bi_pack_fma_reduce(bi_instruction *ins, struct bi_registers *regs)
{
        if (ins->op.reduce == BI_REDUCE_ADD_FREXPM) {
                return bi_pack_fma_2src(ins, regs, BIFROST_FMA_OP_ADD_FREXPM);
        } else {
                unreachable("Invalid reduce op");
        }
}

/* We have a single convert opcode in the IR but a number of opcodes that could
 * come out. In particular we have native opcodes for:
 *
 * [ui]16 --> [fui]32           -- int16_to_32
 * f16     --> f32              -- float16_to_32
 * f32     --> f16              -- float32_to_16
 * f32     --> [ui]32           -- float32_to_int
 * [ui]32  --> f32              -- int_to_float32
 * [fui]16 --> [fui]16          -- f2i_i2f16
 */

static unsigned
bi_pack_convert(bi_instruction *ins, struct bi_registers *regs, bool FMA)
{
        nir_alu_type from_base = nir_alu_type_get_base_type(ins->src_types[0]);
        unsigned from_size = nir_alu_type_get_type_size(ins->src_types[0]);
        bool from_unsigned = from_base == nir_type_uint;

        nir_alu_type to_base = nir_alu_type_get_base_type(ins->dest_type);
        unsigned to_size = nir_alu_type_get_type_size(ins->dest_type);
        bool to_unsigned = to_base == nir_type_uint;
        bool to_float = to_base == nir_type_float;

        /* Sanity check */
        assert((from_base != to_base) || (from_size != to_size));
        assert((MAX2(from_size, to_size) / MIN2(from_size, to_size)) <= 2);

        /* f32 to f16 is special */
        if (from_size == 32 && to_size == 16 && from_base == nir_type_float && to_base == from_base) {
                /* TODO: second vectorized source? */
                struct bifrost_fma_2src pfma = {
                        .src0 = bi_get_src(ins, regs, 0, true),
                        .src1 = BIFROST_SRC_STAGE, /* 0 */
                        .op = BIFROST_FMA_FLOAT32_TO_16
                };

                struct bifrost_add_2src padd = {
                        .src0 = bi_get_src(ins, regs, 0, true),
                        .src1 = BIFROST_SRC_STAGE, /* 0 */
                        .op = BIFROST_ADD_FLOAT32_TO_16
                };

                if (FMA) {
                        RETURN_PACKED(pfma);
                } else {
                        RETURN_PACKED(padd);
                }
        }

        /* Otherwise, figure out the mode */
        unsigned op = 0;

        if (from_size == 16 && to_size == 32) {
                unsigned component = ins->swizzle[0][0];
                assert(component <= 1);

                if (from_base == nir_type_float)
                        op = BIFROST_CONVERT_5(component);
                else
                        op = BIFROST_CONVERT_4(from_unsigned, component, to_float);
        } else {
                unsigned mode = 0;
                unsigned swizzle = (from_size == 16) ? bi_swiz16(ins, 0) : 0;
                bool is_unsigned = from_unsigned;

                if (from_base == nir_type_float) {
                        assert(to_base != nir_type_float);
                        is_unsigned = to_unsigned;

                        if (from_size == 32 && to_size == 32)
                                mode = BIFROST_CONV_F32_TO_I32;
                        else if (from_size == 16 && to_size == 16)
                                mode = BIFROST_CONV_F16_TO_I16;
                        else
                                unreachable("Invalid float conversion");
                } else {
                        assert(to_base == nir_type_float);
                        assert(from_size == to_size);

                        if (to_size == 32)
                                mode = BIFROST_CONV_I32_TO_F32;
                        else if (to_size == 16)
                                mode = BIFROST_CONV_I16_TO_F16;
                        else
                                unreachable("Invalid int conversion");
                }

                /* Fixup swizzle for 32-bit only modes */

                if (mode == BIFROST_CONV_I32_TO_F32)
                        swizzle = 0b11;
                else if (mode == BIFROST_CONV_F32_TO_I32)
                        swizzle = 0b10;

                op = BIFROST_CONVERT(is_unsigned, ins->roundmode, swizzle, mode);

                /* Unclear what the top bit is for... maybe 16-bit related */
                bool mode2 = mode == BIFROST_CONV_F16_TO_I16;
                bool mode6 = mode == BIFROST_CONV_I16_TO_F16;

                if (!(mode2 || mode6))
                        op |= 0x100;
        }

        if (FMA)
                return bi_pack_fma_1src(ins, regs, BIFROST_FMA_CONVERT | op);
        else
                return bi_pack_add_1src(ins, regs, BIFROST_ADD_CONVERT | op);
}

static unsigned
bi_pack_fma_select(bi_instruction *ins, struct bi_registers *regs)
{
        unsigned size = nir_alu_type_get_type_size(ins->src_types[0]);

        if (size == 16) {
                unsigned swiz = (ins->swizzle[0][0] | (ins->swizzle[1][0] << 1));
                unsigned op = BIFROST_FMA_SEL_16(swiz);
                return bi_pack_fma_2src(ins, regs, op);
        } else {
                unreachable("Unimplemented");
        }
}

static unsigned
bi_pack_fma(bi_clause *clause, bi_bundle bundle, struct bi_registers *regs)
{
        if (!bundle.fma)
                return BIFROST_FMA_NOP;

        switch (bundle.fma->type) {
        case BI_ADD:
                return bi_pack_fma_addmin(bundle.fma, regs);
        case BI_CMP:
        case BI_BITWISE:
		return BIFROST_FMA_NOP;
        case BI_CONVERT:
		return bi_pack_convert(bundle.fma, regs, true);
        case BI_CSEL:
		return bi_pack_fma_csel(bundle.fma, regs);
        case BI_FMA:
                return bi_pack_fma_fma(bundle.fma, regs);
        case BI_FREXP:
                return bi_pack_fma_frexp(bundle.fma, regs);
        case BI_ISUB:
                return BIFROST_FMA_NOP;
        case BI_MINMAX:
                return bi_pack_fma_addmin(bundle.fma, regs);
        case BI_MOV:
                return bi_pack_fma_1src(bundle.fma, regs, BIFROST_FMA_OP_MOV);
        case BI_SHIFT:
		return BIFROST_FMA_NOP;
        case BI_SELECT:
                return bi_pack_fma_select(bundle.fma, regs);
        case BI_ROUND:
		return BIFROST_FMA_NOP;
        case BI_REDUCE_FMA:
                return bi_pack_fma_reduce(bundle.fma, regs);
        default:
                unreachable("Cannot encode class as FMA");
        }
}

static unsigned
bi_pack_add_ld_vary(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        unsigned size = nir_alu_type_get_type_size(ins->dest_type);
        assert(size == 32 || size == 16);

        unsigned op = (size == 32) ?
                BIFROST_ADD_OP_LD_VAR_32 :
                BIFROST_ADD_OP_LD_VAR_16;

        unsigned packed_addr = 0;

        if (ins->src[0] & BIR_INDEX_CONSTANT) {
                /* Direct uses address field directly */
                packed_addr = bi_get_immediate(ins, 0);
                assert(packed_addr < 0b1000);
        } else {
                /* Indirect gets an extra source */
                packed_addr = bi_get_src(ins, regs, 0, false) | 0b11000;
        }

        /* The destination is thrown in the data register */
        assert(ins->dest & BIR_INDEX_REGISTER);
        clause->data_register = ins->dest & ~BIR_INDEX_REGISTER;

        unsigned channels = ins->vector_channels;
        assert(channels >= 1 && channels <= 4);

        struct bifrost_ld_var pack = {
                .src0 = bi_get_src(ins, regs, 1, false),
                .addr = packed_addr,
                .channels = MALI_POSITIVE(channels),
                .interp_mode = ins->load_vary.interp_mode,
                .reuse = ins->load_vary.reuse,
                .flat = ins->load_vary.flat,
                .op = op
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_2src(bi_instruction *ins, struct bi_registers *regs, unsigned op)
{
        struct bifrost_add_2src pack = {
                .src0 = bi_get_src(ins, regs, 0, true),
                .src1 = bi_get_src(ins, regs, 1, true),
                .op = op
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_addmin_f32(bi_instruction *ins, struct bi_registers *regs)
{
        unsigned op =
                (ins->type == BI_ADD) ? BIFROST_ADD_OP_FADD32 :
                (ins->op.minmax == BI_MINMAX_MIN) ? BIFROST_ADD_OP_FMIN32 :
                BIFROST_ADD_OP_FMAX32;
 
        struct bifrost_add_faddmin pack = {
                .src0 = bi_get_src(ins, regs, 0, true),
                .src1 = bi_get_src(ins, regs, 1, true),
                .src0_abs = ins->src_abs[0],
                .src1_abs = ins->src_abs[1],
                .src0_neg = ins->src_neg[0],
                .src1_neg = ins->src_neg[1],
                .outmod = ins->outmod,
                .mode = (ins->type == BI_ADD) ? ins->roundmode : ins->minmax,
                .op = op
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_add_f16(bi_instruction *ins, struct bi_registers *regs)
{
        /* ADD.v2f16 can't have outmod */
        assert(ins->outmod == BIFROST_NONE);

        struct bifrost_add_faddmin pack = {
                .src0 = bi_get_src(ins, regs, 0, true),
                .src1 = bi_get_src(ins, regs, 1, true),
                .src0_abs = ins->src_abs[0],
                .src1_abs = ins->src_abs[1],
                .src0_neg = ins->src_neg[0],
                .src1_neg = ins->src_neg[1],
                .select = bi_swiz16(ins, 0), /* swizzle_0 */
                .outmod = bi_swiz16(ins, 1), /* swizzle_1 */
                .mode = ins->roundmode,
                .op = BIFROST_ADD_OP_FADD16
        };

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_addmin(bi_instruction *ins, struct bi_registers *regs)
{
        if (ins->dest_type == nir_type_float32)
                return bi_pack_add_addmin_f32(ins, regs);
        else if (ins->dest_type == nir_type_float16) {
                if (ins->type == BI_ADD)
                        return bi_pack_add_add_f16(ins, regs);
                else
                        return bi_pack_fmadd_min_f16(ins, regs, false);
        } else
                unreachable("Unknown FMA/ADD type");
}

static unsigned
bi_pack_add_ld_ubo(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        assert(ins->vector_channels >= 1 && ins->vector_channels <= 4);

        const unsigned ops[4] = {
                BIFROST_ADD_OP_LD_UBO_1,
                BIFROST_ADD_OP_LD_UBO_2,
                BIFROST_ADD_OP_LD_UBO_3,
                BIFROST_ADD_OP_LD_UBO_4
        };

        bi_write_data_register(clause, ins);
        return bi_pack_add_2src(ins, regs, ops[ins->vector_channels - 1]);
}

static enum bifrost_ldst_type
bi_pack_ldst_type(nir_alu_type T)
{
        switch (T) {
        case nir_type_float16: return BIFROST_LDST_F16;
        case nir_type_float32: return BIFROST_LDST_F32;
        case nir_type_int32:   return BIFROST_LDST_I32;
        case nir_type_uint32:  return BIFROST_LDST_U32;
        default: unreachable("Invalid type loaded");
        }
}

static unsigned
bi_pack_add_ld_var_addr(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        struct bifrost_ld_var_addr pack = {
                .src0 = bi_get_src(ins, regs, 1, false),
                .src1 = bi_get_src(ins, regs, 2, false),
                .location = bi_get_immediate(ins, 0),
                .type = bi_pack_ldst_type(ins->src_types[3]),
                .op = BIFROST_ADD_OP_LD_VAR_ADDR
        };

        bi_write_data_register(clause, ins);
        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_ld_attr(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        assert(ins->vector_channels >= 0 && ins->vector_channels <= 4);

        struct bifrost_ld_attr pack = {
                .src0 = bi_get_src(ins, regs, 1, false),
                .src1 = bi_get_src(ins, regs, 2, false),
                .location = bi_get_immediate(ins, 0),
                .channels = MALI_POSITIVE(ins->vector_channels),
                .type = bi_pack_ldst_type(ins->dest_type),
                .op = BIFROST_ADD_OP_LD_ATTR
        };

        bi_write_data_register(clause, ins);
        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_st_vary(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        assert(ins->vector_channels >= 1 && ins->vector_channels <= 4);

        struct bifrost_st_vary pack = {
                .src0 = bi_get_src(ins, regs, 1, false),
                .src1 = bi_get_src(ins, regs, 2, false),
                .src2 = bi_get_src(ins, regs, 3, false),
                .channels = MALI_POSITIVE(ins->vector_channels),
                .op = BIFROST_ADD_OP_ST_VAR
        };

        bi_read_data_register(clause, ins);
        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_atest(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        bool fp16 = (ins->src_types[1] == nir_type_float16);

        struct bifrost_add_atest pack = {
                .src0 = bi_get_src(ins, regs, 0, false),
                .src1 = bi_get_src(ins, regs, 1, false),
                .half = fp16,
                .component = fp16 ? ins->swizzle[1][0] : 1, /* Set for fp32 */
                .op = BIFROST_ADD_OP_ATEST,
        };

        /* Despite *also* writing with the usual mechanism... quirky and
         * perhaps unnecessary, but let's match the blob */
        clause->data_register = ins->dest & ~BIR_INDEX_REGISTER;

        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_blend(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        struct bifrost_add_inst pack = {
                .src0 = bi_get_src(ins, regs, 1, false),
                .op = BIFROST_ADD_OP_BLEND
        };

        /* TODO: Pack location in uniform_const */
        assert(ins->blend_location == 0);

        bi_read_data_register(clause, ins);
        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add_special(bi_instruction *ins, struct bi_registers *regs)
{
        unsigned op = 0;
        bool fp16 = ins->dest_type == nir_type_float16;
        bool Y = ins->swizzle[0][0];

        if (ins->op.special == BI_SPECIAL_FRCP) {
                op = fp16 ?
                        (Y ? BIFROST_ADD_OP_FRCP_FAST_F16_Y :
                        BIFROST_ADD_OP_FRCP_FAST_F16_X) :
                        BIFROST_ADD_OP_FRCP_FAST_F32;
        } else if (ins->op.special == BI_SPECIAL_FRSQ) {
                op = fp16 ?
                        (Y ? BIFROST_ADD_OP_FRSQ_FAST_F16_Y :
                        BIFROST_ADD_OP_FRSQ_FAST_F16_X) :
                        BIFROST_ADD_OP_FRSQ_FAST_F32;

        } else if (ins->op.special == BI_SPECIAL_EXP2_LOW) {
                assert(!fp16);
                op = BIFROST_ADD_OP_FEXP2_FAST;
        } else {
                unreachable("Unknown special op");
        }

        return bi_pack_add_1src(ins, regs, op);
}

static unsigned
bi_pack_add_table(bi_instruction *ins, struct bi_registers *regs)
{
        unsigned op = 0;
        assert(ins->dest_type == nir_type_float32);

        op = BIFROST_ADD_OP_LOG2_HELP;
        return bi_pack_add_1src(ins, regs, op);
}
static unsigned
bi_pack_add_tex_compact(bi_clause *clause, bi_instruction *ins, struct bi_registers *regs)
{
        bool f16 = ins->dest_type == nir_type_float16;

        struct bifrost_tex_compact pack = {
                .src0 = bi_get_src(ins, regs, 0, false),
                .src1 = bi_get_src(ins, regs, 1, false),
                .op = f16 ? BIFROST_ADD_OP_TEX_COMPACT_F16 :
                        BIFROST_ADD_OP_TEX_COMPACT_F32,
                .unknown = 1,
                .tex_index = 0,
                .sampler_index = 0
        };

        bi_write_data_register(clause, ins);
        RETURN_PACKED(pack);
}

static unsigned
bi_pack_add(bi_clause *clause, bi_bundle bundle, struct bi_registers *regs)
{
        if (!bundle.add)
                return BIFROST_ADD_NOP;

        switch (bundle.add->type) {
        case BI_ADD:
                return bi_pack_add_addmin(bundle.add, regs);
        case BI_ATEST:
                return bi_pack_add_atest(clause, bundle.add, regs);
        case BI_BRANCH:
        case BI_CMP:
                return BIFROST_ADD_NOP;
        case BI_BLEND:
                return bi_pack_add_blend(clause, bundle.add, regs);
        case BI_BITWISE:
                return BIFROST_ADD_NOP;
        case BI_CONVERT:
		return bi_pack_convert(bundle.add, regs, false);
        case BI_DISCARD:
        case BI_FREXP:
        case BI_ISUB:
        case BI_LOAD:
                return BIFROST_ADD_NOP;
        case BI_LOAD_ATTR:
                return bi_pack_add_ld_attr(clause, bundle.add, regs);
        case BI_LOAD_UNIFORM:
                return bi_pack_add_ld_ubo(clause, bundle.add, regs);
        case BI_LOAD_VAR:
                return bi_pack_add_ld_vary(clause, bundle.add, regs);
        case BI_LOAD_VAR_ADDRESS:
                return bi_pack_add_ld_var_addr(clause, bundle.add, regs);
        case BI_MINMAX:
                return bi_pack_add_addmin(bundle.add, regs);
        case BI_MOV:
        case BI_SHIFT:
        case BI_STORE:
                return BIFROST_ADD_NOP;
        case BI_STORE_VAR:
                return bi_pack_add_st_vary(clause, bundle.add, regs);
        case BI_SPECIAL:
                return bi_pack_add_special(bundle.add, regs);
        case BI_TABLE:
                return bi_pack_add_table(bundle.add, regs);
        case BI_SELECT:
                return BIFROST_ADD_NOP;
        case BI_TEX:
                if (bundle.add->op.texture == BI_TEX_COMPACT)
                        return bi_pack_add_tex_compact(clause, bundle.add, regs);
                else
                        unreachable("Unknown tex type");
        case BI_ROUND:
                return BIFROST_ADD_NOP;
        default:
                unreachable("Cannot encode class as ADD");
        }
}

struct bi_packed_bundle {
        uint64_t lo;
        uint64_t hi;
};

static struct bi_packed_bundle
bi_pack_bundle(bi_clause *clause, bi_bundle bundle, bi_bundle prev, bool first_bundle)
{
        struct bi_registers regs = bi_assign_ports(bundle, prev);
        bi_assign_uniform_constant(clause, &regs, bundle);
        regs.first_instruction = first_bundle;

        uint64_t reg = bi_pack_registers(regs);
        uint64_t fma = bi_pack_fma(clause, bundle, &regs);
        uint64_t add = bi_pack_add(clause, bundle, &regs);

        struct bi_packed_bundle packed = {
                .lo = reg | (fma << 35) | ((add & 0b111111) << 58),
                .hi = add >> 6
        };

        return packed;
}

/* Packs the next two constants as a dedicated constant quadword at the end of
 * the clause, returning the number packed. */

static unsigned
bi_pack_constants(bi_context *ctx, bi_clause *clause,
                unsigned index,
                struct util_dynarray *emission)
{
        /* After these two, are we done? Determines tag */
        bool done = clause->constant_count <= (index + 2);
        bool only = clause->constant_count <= (index + 1);

        /* TODO: Pos */
        assert(index == 0 && clause->bundle_count == 1);
        assert(only);

        uint64_t hi = clause->constants[index + 0] >> 60ull;

        struct bifrost_fmt_constant quad = {
                .pos = 0, /* TODO */
                .tag = done ? BIFROST_FMTC_FINAL : BIFROST_FMTC_CONSTANTS,
                .imm_1 = clause->constants[index + 0] >> 4,
                .imm_2 = ((hi < 8) ? (hi << 60ull) : 0) >> 4,
        };

        /* XXX: On G71, Connor observed that the difference of the top 4 bits
         * of the second constant with the first must be less than 8, otherwise
         * we have to swap them. On G52, I'm able to reproduce a similar issue
         * but with a different workaround (modeled above with a single
         * constant, unclear how to workaround for multiple constants.) Further
         * investigation needed. Possibly an errata. XXX */

        util_dynarray_append(emission, struct bifrost_fmt_constant, quad);

        return 2;
}

static void
bi_pack_clause(bi_context *ctx, bi_clause *clause, bi_clause *next,
                struct util_dynarray *emission)
{
        struct bi_packed_bundle ins_1 = bi_pack_bundle(clause, clause->bundles[0], clause->bundles[0], true);
        assert(clause->bundle_count == 1);

        /* Used to decide if we elide writes */
        bool is_fragment = ctx->stage == MESA_SHADER_FRAGMENT;

        /* State for packing constants throughout */
        unsigned constant_index = 0;

        struct bifrost_fmt1 quad_1 = {
                .tag = clause->constant_count ? BIFROST_FMT1_CONSTANTS : BIFROST_FMT1_FINAL,
                .header = bi_pack_header(clause, next, is_fragment),
                .ins_1 = ins_1.lo,
                .ins_2 = ins_1.hi & ((1 << 11) - 1),
                .ins_0 = (ins_1.hi >> 11) & 0b111,
        };

        util_dynarray_append(emission, struct bifrost_fmt1, quad_1);

        /* Pack the remaining constants */

        while (constant_index < clause->constant_count) {
                constant_index += bi_pack_constants(ctx, clause,
                                constant_index, emission);
        }
}

static bi_clause *
bi_next_clause(bi_context *ctx, pan_block *block, bi_clause *clause)
{
        /* Try the next clause in this block */
        if (clause->link.next != &((bi_block *) block)->clauses)
                return list_first_entry(&(clause->link), bi_clause, link);

        /* Try the next block, or the one after that if it's empty, etc .*/
        pan_block *next_block = pan_next_block(block);

        bi_foreach_block_from(ctx, next_block, block) {
                bi_block *blk = (bi_block *) block;

                if (!list_is_empty(&blk->clauses))
                        return list_first_entry(&(blk->clauses), bi_clause, link);
        }

        return NULL;
}

void
bi_pack(bi_context *ctx, struct util_dynarray *emission)
{
        util_dynarray_init(emission, NULL);

        bi_foreach_block(ctx, _block) {
                bi_block *block = (bi_block *) _block;

                bi_foreach_clause_in_block(block, clause) {
                        bi_clause *next = bi_next_clause(ctx, _block, clause);
                        bi_pack_clause(ctx, clause, next, emission);
                }
        }
}