summaryrefslogtreecommitdiffstats
path: root/src/intel/compiler/brw_eu_emit.c
blob: 8c952e7da265c3bf2963871e0d56ac1a534ea163 (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
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
/*
 Copyright (C) Intel Corp.  2006.  All Rights Reserved.
 Intel funded Tungsten Graphics to
 develop this 3D driver.

 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 COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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:
  *   Keith Whitwell <keithw@vmware.com>
  */


#include "brw_eu_defines.h"
#include "brw_eu.h"

#include "util/ralloc.h"

/**
 * Prior to Sandybridge, the SEND instruction accepted non-MRF source
 * registers, implicitly moving the operand to a message register.
 *
 * On Sandybridge, this is no longer the case.  This function performs the
 * explicit move; it should be called before emitting a SEND instruction.
 */
void
gen6_resolve_implied_move(struct brw_codegen *p,
			  struct brw_reg *src,
			  unsigned msg_reg_nr)
{
   const struct gen_device_info *devinfo = p->devinfo;
   if (devinfo->gen < 6)
      return;

   if (src->file == BRW_MESSAGE_REGISTER_FILE)
      return;

   if (src->file != BRW_ARCHITECTURE_REGISTER_FILE || src->nr != BRW_ARF_NULL) {
      brw_push_insn_state(p);
      brw_set_default_exec_size(p, BRW_EXECUTE_8);
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);
      brw_set_default_compression_control(p, BRW_COMPRESSION_NONE);
      brw_MOV(p, retype(brw_message_reg(msg_reg_nr), BRW_REGISTER_TYPE_UD),
	      retype(*src, BRW_REGISTER_TYPE_UD));
      brw_pop_insn_state(p);
   }
   *src = brw_message_reg(msg_reg_nr);
}

static void
gen7_convert_mrf_to_grf(struct brw_codegen *p, struct brw_reg *reg)
{
   /* From the Ivybridge PRM, Volume 4 Part 3, page 218 ("send"):
    * "The send with EOT should use register space R112-R127 for <src>. This is
    *  to enable loading of a new thread into the same slot while the message
    *  with EOT for current thread is pending dispatch."
    *
    * Since we're pretending to have 16 MRFs anyway, we may as well use the
    * registers required for messages with EOT.
    */
   const struct gen_device_info *devinfo = p->devinfo;
   if (devinfo->gen >= 7 && reg->file == BRW_MESSAGE_REGISTER_FILE) {
      reg->file = BRW_GENERAL_REGISTER_FILE;
      reg->nr += GEN7_MRF_HACK_START;
   }
}

void
brw_set_dest(struct brw_codegen *p, brw_inst *inst, struct brw_reg dest)
{
   const struct gen_device_info *devinfo = p->devinfo;

   if (dest.file == BRW_MESSAGE_REGISTER_FILE)
      assert((dest.nr & ~BRW_MRF_COMPR4) < BRW_MAX_MRF(devinfo->gen));
   else if (dest.file != BRW_ARCHITECTURE_REGISTER_FILE)
      assert(dest.nr < 128);

   gen7_convert_mrf_to_grf(p, &dest);

   brw_inst_set_dst_file_type(devinfo, inst, dest.file, dest.type);
   brw_inst_set_dst_address_mode(devinfo, inst, dest.address_mode);

   if (dest.address_mode == BRW_ADDRESS_DIRECT) {
      brw_inst_set_dst_da_reg_nr(devinfo, inst, dest.nr);

      if (brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_1) {
         brw_inst_set_dst_da1_subreg_nr(devinfo, inst, dest.subnr);
	 if (dest.hstride == BRW_HORIZONTAL_STRIDE_0)
	    dest.hstride = BRW_HORIZONTAL_STRIDE_1;
         brw_inst_set_dst_hstride(devinfo, inst, dest.hstride);
      } else {
         brw_inst_set_dst_da16_subreg_nr(devinfo, inst, dest.subnr / 16);
         brw_inst_set_da16_writemask(devinfo, inst, dest.writemask);
         if (dest.file == BRW_GENERAL_REGISTER_FILE ||
             dest.file == BRW_MESSAGE_REGISTER_FILE) {
            assert(dest.writemask != 0);
         }
	 /* From the Ivybridge PRM, Vol 4, Part 3, Section 5.2.4.1:
	  *    Although Dst.HorzStride is a don't care for Align16, HW needs
	  *    this to be programmed as "01".
	  */
         brw_inst_set_dst_hstride(devinfo, inst, 1);
      }
   } else {
      brw_inst_set_dst_ia_subreg_nr(devinfo, inst, dest.subnr);

      /* These are different sizes in align1 vs align16:
       */
      if (brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_1) {
         brw_inst_set_dst_ia1_addr_imm(devinfo, inst,
                                       dest.indirect_offset);
	 if (dest.hstride == BRW_HORIZONTAL_STRIDE_0)
	    dest.hstride = BRW_HORIZONTAL_STRIDE_1;
         brw_inst_set_dst_hstride(devinfo, inst, dest.hstride);
      } else {
         brw_inst_set_dst_ia16_addr_imm(devinfo, inst,
                                        dest.indirect_offset);
	 /* even ignored in da16, still need to set as '01' */
         brw_inst_set_dst_hstride(devinfo, inst, 1);
      }
   }

   /* Generators should set a default exec_size of either 8 (SIMD4x2 or SIMD8)
    * or 16 (SIMD16), as that's normally correct.  However, when dealing with
    * small registers, we automatically reduce it to match the register size.
    *
    * In platforms that support fp64 we can emit instructions with a width of
    * 4 that need two SIMD8 registers and an exec_size of 8 or 16. In these
    * cases we need to make sure that these instructions have their exec sizes
    * set properly when they are emitted and we can't rely on this code to fix
    * it.
    */
   bool fix_exec_size;
   if (devinfo->gen >= 6)
      fix_exec_size = dest.width < BRW_EXECUTE_4;
   else
      fix_exec_size = dest.width < BRW_EXECUTE_8;

   if (fix_exec_size)
      brw_inst_set_exec_size(devinfo, inst, dest.width);
}

static void
validate_reg(const struct gen_device_info *devinfo,
             brw_inst *inst, struct brw_reg reg)
{
   const int hstride_for_reg[] = {0, 1, 2, 4};
   const int vstride_for_reg[] = {0, 1, 2, 4, 8, 16, 32};
   const int width_for_reg[] = {1, 2, 4, 8, 16};
   const int execsize_for_reg[] = {1, 2, 4, 8, 16, 32};
   int width, hstride, vstride, execsize;

   if (reg.file == BRW_IMMEDIATE_VALUE)
      return;

   if (reg.file == BRW_ARCHITECTURE_REGISTER_FILE &&
       reg.file == BRW_ARF_NULL)
      return;

   /* From the IVB PRM Vol. 4, Pt. 3, Section 3.3.3.5:
    *
    *    "Swizzling is not allowed when an accumulator is used as an implicit
    *    source or an explicit source in an instruction."
    */
   if (reg.file == BRW_ARCHITECTURE_REGISTER_FILE &&
       reg.nr == BRW_ARF_ACCUMULATOR)
      assert(reg.swizzle == BRW_SWIZZLE_XYZW);

   assert(reg.hstride < ARRAY_SIZE(hstride_for_reg));
   hstride = hstride_for_reg[reg.hstride];

   if (reg.vstride == 0xf) {
      vstride = -1;
   } else {
      assert(reg.vstride >= 0 && reg.vstride < ARRAY_SIZE(vstride_for_reg));
      vstride = vstride_for_reg[reg.vstride];
   }

   assert(reg.width >= 0 && reg.width < ARRAY_SIZE(width_for_reg));
   width = width_for_reg[reg.width];

   assert(brw_inst_exec_size(devinfo, inst) >= 0 &&
          brw_inst_exec_size(devinfo, inst) < ARRAY_SIZE(execsize_for_reg));
   execsize = execsize_for_reg[brw_inst_exec_size(devinfo, inst)];

   /* Restrictions from 3.3.10: Register Region Restrictions. */
   /* 3. */
   assert(execsize >= width);

   /* 4. */
   if (execsize == width && hstride != 0) {
      assert(vstride == -1 || vstride == width * hstride);
   }

   /* 5. */
   if (execsize == width && hstride == 0) {
      /* no restriction on vstride. */
   }

   /* 6. */
   if (width == 1) {
      assert(hstride == 0);
   }

   /* 7. */
   if (execsize == 1 && width == 1) {
      assert(hstride == 0);
      assert(vstride == 0);
   }

   /* 8. */
   if (vstride == 0 && hstride == 0) {
      assert(width == 1);
   }

   /* 10. Check destination issues. */
}

void
brw_set_src0(struct brw_codegen *p, brw_inst *inst, struct brw_reg reg)
{
   const struct gen_device_info *devinfo = p->devinfo;

   if (reg.file == BRW_MESSAGE_REGISTER_FILE)
      assert((reg.nr & ~BRW_MRF_COMPR4) < BRW_MAX_MRF(devinfo->gen));
   else if (reg.file != BRW_ARCHITECTURE_REGISTER_FILE)
      assert(reg.nr < 128);

   gen7_convert_mrf_to_grf(p, &reg);

   if (devinfo->gen >= 6 && (brw_inst_opcode(devinfo, inst) == BRW_OPCODE_SEND ||
                             brw_inst_opcode(devinfo, inst) == BRW_OPCODE_SENDC)) {
      /* Any source modifiers or regions will be ignored, since this just
       * identifies the MRF/GRF to start reading the message contents from.
       * Check for some likely failures.
       */
      assert(!reg.negate);
      assert(!reg.abs);
      assert(reg.address_mode == BRW_ADDRESS_DIRECT);
   }

   validate_reg(devinfo, inst, reg);

   brw_inst_set_src0_file_type(devinfo, inst, reg.file, reg.type);
   brw_inst_set_src0_abs(devinfo, inst, reg.abs);
   brw_inst_set_src0_negate(devinfo, inst, reg.negate);
   brw_inst_set_src0_address_mode(devinfo, inst, reg.address_mode);

   if (reg.file == BRW_IMMEDIATE_VALUE) {
      if (reg.type == BRW_REGISTER_TYPE_DF ||
          brw_inst_opcode(devinfo, inst) == BRW_OPCODE_DIM)
         brw_inst_set_imm_df(devinfo, inst, reg.df);
      else if (reg.type == BRW_REGISTER_TYPE_UQ ||
               reg.type == BRW_REGISTER_TYPE_Q)
         brw_inst_set_imm_uq(devinfo, inst, reg.u64);
      else
         brw_inst_set_imm_ud(devinfo, inst, reg.ud);

      if (type_sz(reg.type) < 8) {
         brw_inst_set_src1_reg_file(devinfo, inst,
                                    BRW_ARCHITECTURE_REGISTER_FILE);
         brw_inst_set_src1_reg_hw_type(devinfo, inst,
                                       brw_inst_src0_reg_hw_type(devinfo, inst));
      }
   } else {
      if (reg.address_mode == BRW_ADDRESS_DIRECT) {
         brw_inst_set_src0_da_reg_nr(devinfo, inst, reg.nr);
         if (brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_1) {
             brw_inst_set_src0_da1_subreg_nr(devinfo, inst, reg.subnr);
	 } else {
            brw_inst_set_src0_da16_subreg_nr(devinfo, inst, reg.subnr / 16);
	 }
      } else {
         brw_inst_set_src0_ia_subreg_nr(devinfo, inst, reg.subnr);

         if (brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_1) {
            brw_inst_set_src0_ia1_addr_imm(devinfo, inst, reg.indirect_offset);
	 } else {
            brw_inst_set_src0_ia16_addr_imm(devinfo, inst, reg.indirect_offset);
	 }
      }

      if (brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_1) {
	 if (reg.width == BRW_WIDTH_1 &&
             brw_inst_exec_size(devinfo, inst) == BRW_EXECUTE_1) {
            brw_inst_set_src0_hstride(devinfo, inst, BRW_HORIZONTAL_STRIDE_0);
            brw_inst_set_src0_width(devinfo, inst, BRW_WIDTH_1);
            brw_inst_set_src0_vstride(devinfo, inst, BRW_VERTICAL_STRIDE_0);
	 } else {
            brw_inst_set_src0_hstride(devinfo, inst, reg.hstride);
            brw_inst_set_src0_width(devinfo, inst, reg.width);
            brw_inst_set_src0_vstride(devinfo, inst, reg.vstride);
	 }
      } else {
         brw_inst_set_src0_da16_swiz_x(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_X));
         brw_inst_set_src0_da16_swiz_y(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_Y));
         brw_inst_set_src0_da16_swiz_z(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_Z));
         brw_inst_set_src0_da16_swiz_w(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_W));

         if (reg.vstride == BRW_VERTICAL_STRIDE_8) {
            /* This is an oddity of the fact we're using the same
             * descriptions for registers in align_16 as align_1:
             */
            brw_inst_set_src0_vstride(devinfo, inst, BRW_VERTICAL_STRIDE_4);
         } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
                    reg.type == BRW_REGISTER_TYPE_DF &&
                    reg.vstride == BRW_VERTICAL_STRIDE_2) {
            /* From SNB PRM:
             *
             * "For Align16 access mode, only encodings of 0000 and 0011
             *  are allowed. Other codes are reserved."
             *
             * Presumably the DevSNB behavior applies to IVB as well.
             */
            brw_inst_set_src0_vstride(devinfo, inst, BRW_VERTICAL_STRIDE_4);
         } else {
            brw_inst_set_src0_vstride(devinfo, inst, reg.vstride);
         }
      }
   }
}


void
brw_set_src1(struct brw_codegen *p, brw_inst *inst, struct brw_reg reg)
{
   const struct gen_device_info *devinfo = p->devinfo;

   if (reg.file != BRW_ARCHITECTURE_REGISTER_FILE)
      assert(reg.nr < 128);

   /* From the IVB PRM Vol. 4, Pt. 3, Section 3.3.3.5:
    *
    *    "Accumulator registers may be accessed explicitly as src0
    *    operands only."
    */
   assert(reg.file != BRW_ARCHITECTURE_REGISTER_FILE ||
          reg.nr != BRW_ARF_ACCUMULATOR);

   gen7_convert_mrf_to_grf(p, &reg);
   assert(reg.file != BRW_MESSAGE_REGISTER_FILE);

   validate_reg(devinfo, inst, reg);

   brw_inst_set_src1_file_type(devinfo, inst, reg.file, reg.type);
   brw_inst_set_src1_abs(devinfo, inst, reg.abs);
   brw_inst_set_src1_negate(devinfo, inst, reg.negate);

   /* Only src1 can be immediate in two-argument instructions.
    */
   assert(brw_inst_src0_reg_file(devinfo, inst) != BRW_IMMEDIATE_VALUE);

   if (reg.file == BRW_IMMEDIATE_VALUE) {
      /* two-argument instructions can only use 32-bit immediates */
      assert(type_sz(reg.type) < 8);
      brw_inst_set_imm_ud(devinfo, inst, reg.ud);
   } else {
      /* This is a hardware restriction, which may or may not be lifted
       * in the future:
       */
      assert (reg.address_mode == BRW_ADDRESS_DIRECT);
      /* assert (reg.file == BRW_GENERAL_REGISTER_FILE); */

      brw_inst_set_src1_da_reg_nr(devinfo, inst, reg.nr);
      if (brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_1) {
         brw_inst_set_src1_da1_subreg_nr(devinfo, inst, reg.subnr);
      } else {
         brw_inst_set_src1_da16_subreg_nr(devinfo, inst, reg.subnr / 16);
      }

      if (brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_1) {
	 if (reg.width == BRW_WIDTH_1 &&
             brw_inst_exec_size(devinfo, inst) == BRW_EXECUTE_1) {
            brw_inst_set_src1_hstride(devinfo, inst, BRW_HORIZONTAL_STRIDE_0);
            brw_inst_set_src1_width(devinfo, inst, BRW_WIDTH_1);
            brw_inst_set_src1_vstride(devinfo, inst, BRW_VERTICAL_STRIDE_0);
	 } else {
            brw_inst_set_src1_hstride(devinfo, inst, reg.hstride);
            brw_inst_set_src1_width(devinfo, inst, reg.width);
            brw_inst_set_src1_vstride(devinfo, inst, reg.vstride);
	 }
      } else {
         brw_inst_set_src1_da16_swiz_x(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_X));
         brw_inst_set_src1_da16_swiz_y(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_Y));
         brw_inst_set_src1_da16_swiz_z(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_Z));
         brw_inst_set_src1_da16_swiz_w(devinfo, inst,
            BRW_GET_SWZ(reg.swizzle, BRW_CHANNEL_W));

         if (reg.vstride == BRW_VERTICAL_STRIDE_8) {
            /* This is an oddity of the fact we're using the same
             * descriptions for registers in align_16 as align_1:
             */
            brw_inst_set_src1_vstride(devinfo, inst, BRW_VERTICAL_STRIDE_4);
         } else if (devinfo->gen == 7 && !devinfo->is_haswell &&
                    reg.type == BRW_REGISTER_TYPE_DF &&
                    reg.vstride == BRW_VERTICAL_STRIDE_2) {
            /* From SNB PRM:
             *
             * "For Align16 access mode, only encodings of 0000 and 0011
             *  are allowed. Other codes are reserved."
             *
             * Presumably the DevSNB behavior applies to IVB as well.
             */
            brw_inst_set_src1_vstride(devinfo, inst, BRW_VERTICAL_STRIDE_4);
         } else {
            brw_inst_set_src1_vstride(devinfo, inst, reg.vstride);
         }
      }
   }
}

/**
 * Set the Message Descriptor and Extended Message Descriptor fields
 * for SEND messages.
 *
 * \note This zeroes out the Function Control bits, so it must be called
 *       \b before filling out any message-specific data.  Callers can
 *       choose not to fill in irrelevant bits; they will be zero.
 */
void
brw_set_message_descriptor(struct brw_codegen *p,
			   brw_inst *inst,
			   enum brw_message_target sfid,
			   unsigned msg_length,
			   unsigned response_length,
			   bool header_present,
			   bool end_of_thread)
{
   const struct gen_device_info *devinfo = p->devinfo;

   brw_set_src1(p, inst, brw_imm_d(0));

   /* For indirect sends, `inst` will not be the SEND/SENDC instruction
    * itself; instead, it will be a MOV/OR into the address register.
    *
    * In this case, we avoid setting the extended message descriptor bits,
    * since they go on the later SEND/SENDC instead and if set here would
    * instead clobber the conditionalmod bits.
    */
   unsigned opcode = brw_inst_opcode(devinfo, inst);
   if (opcode == BRW_OPCODE_SEND || opcode == BRW_OPCODE_SENDC) {
      brw_inst_set_sfid(devinfo, inst, sfid);
   }

   brw_inst_set_mlen(devinfo, inst, msg_length);
   brw_inst_set_rlen(devinfo, inst, response_length);
   brw_inst_set_eot(devinfo, inst, end_of_thread);

   if (devinfo->gen >= 5) {
      brw_inst_set_header_present(devinfo, inst, header_present);
   }
}

static void brw_set_math_message( struct brw_codegen *p,
				  brw_inst *inst,
				  unsigned function,
				  unsigned integer_type,
				  bool low_precision,
				  unsigned dataType )
{
   const struct gen_device_info *devinfo = p->devinfo;
   unsigned msg_length;
   unsigned response_length;

   /* Infer message length from the function */
   switch (function) {
   case BRW_MATH_FUNCTION_POW:
   case BRW_MATH_FUNCTION_INT_DIV_QUOTIENT:
   case BRW_MATH_FUNCTION_INT_DIV_REMAINDER:
   case BRW_MATH_FUNCTION_INT_DIV_QUOTIENT_AND_REMAINDER:
      msg_length = 2;
      break;
   default:
      msg_length = 1;
      break;
   }

   /* Infer response length from the function */
   switch (function) {
   case BRW_MATH_FUNCTION_SINCOS:
   case BRW_MATH_FUNCTION_INT_DIV_QUOTIENT_AND_REMAINDER:
      response_length = 2;
      break;
   default:
      response_length = 1;
      break;
   }


   brw_set_message_descriptor(p, inst, BRW_SFID_MATH,
			      msg_length, response_length, false, false);
   brw_inst_set_math_msg_function(devinfo, inst, function);
   brw_inst_set_math_msg_signed_int(devinfo, inst, integer_type);
   brw_inst_set_math_msg_precision(devinfo, inst, low_precision);
   brw_inst_set_math_msg_saturate(devinfo, inst, brw_inst_saturate(devinfo, inst));
   brw_inst_set_math_msg_data_type(devinfo, inst, dataType);
   brw_inst_set_saturate(devinfo, inst, 0);
}


static void brw_set_ff_sync_message(struct brw_codegen *p,
				    brw_inst *insn,
				    bool allocate,
				    unsigned response_length,
				    bool end_of_thread)
{
   const struct gen_device_info *devinfo = p->devinfo;

   brw_set_message_descriptor(p, insn, BRW_SFID_URB,
			      1, response_length, true, end_of_thread);
   brw_inst_set_urb_opcode(devinfo, insn, 1); /* FF_SYNC */
   brw_inst_set_urb_allocate(devinfo, insn, allocate);
   /* The following fields are not used by FF_SYNC: */
   brw_inst_set_urb_global_offset(devinfo, insn, 0);
   brw_inst_set_urb_swizzle_control(devinfo, insn, 0);
   brw_inst_set_urb_used(devinfo, insn, 0);
   brw_inst_set_urb_complete(devinfo, insn, 0);
}

static void brw_set_urb_message( struct brw_codegen *p,
				 brw_inst *insn,
                                 enum brw_urb_write_flags flags,
				 unsigned msg_length,
				 unsigned response_length,
				 unsigned offset,
				 unsigned swizzle_control )
{
   const struct gen_device_info *devinfo = p->devinfo;

   assert(devinfo->gen < 7 || swizzle_control != BRW_URB_SWIZZLE_TRANSPOSE);
   assert(devinfo->gen < 7 || !(flags & BRW_URB_WRITE_ALLOCATE));
   assert(devinfo->gen >= 7 || !(flags & BRW_URB_WRITE_PER_SLOT_OFFSET));

   brw_set_message_descriptor(p, insn, BRW_SFID_URB,
			      msg_length, response_length, true,
                              flags & BRW_URB_WRITE_EOT);

   if (flags & BRW_URB_WRITE_OWORD) {
      assert(msg_length == 2); /* header + one OWORD of data */
      brw_inst_set_urb_opcode(devinfo, insn, BRW_URB_OPCODE_WRITE_OWORD);
   } else {
      brw_inst_set_urb_opcode(devinfo, insn, BRW_URB_OPCODE_WRITE_HWORD);
   }

   brw_inst_set_urb_global_offset(devinfo, insn, offset);
   brw_inst_set_urb_swizzle_control(devinfo, insn, swizzle_control);

   if (devinfo->gen < 8) {
      brw_inst_set_urb_complete(devinfo, insn, !!(flags & BRW_URB_WRITE_COMPLETE));
   }

   if (devinfo->gen < 7) {
      brw_inst_set_urb_allocate(devinfo, insn, !!(flags & BRW_URB_WRITE_ALLOCATE));
      brw_inst_set_urb_used(devinfo, insn, !(flags & BRW_URB_WRITE_UNUSED));
   } else {
      brw_inst_set_urb_per_slot_offset(devinfo, insn,
         !!(flags & BRW_URB_WRITE_PER_SLOT_OFFSET));
   }
}

void
brw_set_dp_write_message(struct brw_codegen *p,
			 brw_inst *insn,
			 unsigned binding_table_index,
			 unsigned msg_control,
			 unsigned msg_type,
                         unsigned target_cache,
			 unsigned msg_length,
			 bool header_present,
			 unsigned last_render_target,
			 unsigned response_length,
			 unsigned end_of_thread,
			 unsigned send_commit_msg)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 6 ? target_cache :
                          BRW_SFID_DATAPORT_WRITE);

   brw_set_message_descriptor(p, insn, sfid, msg_length, response_length,
			      header_present, end_of_thread);

   brw_inst_set_binding_table_index(devinfo, insn, binding_table_index);
   brw_inst_set_dp_write_msg_type(devinfo, insn, msg_type);
   brw_inst_set_dp_write_msg_control(devinfo, insn, msg_control);
   brw_inst_set_rt_last(devinfo, insn, last_render_target);
   if (devinfo->gen < 7) {
      brw_inst_set_dp_write_commit(devinfo, insn, send_commit_msg);
   }
}

void
brw_set_dp_read_message(struct brw_codegen *p,
			brw_inst *insn,
			unsigned binding_table_index,
			unsigned msg_control,
			unsigned msg_type,
			unsigned target_cache,
			unsigned msg_length,
                        bool header_present,
			unsigned response_length)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 6 ? target_cache :
                          BRW_SFID_DATAPORT_READ);

   brw_set_message_descriptor(p, insn, sfid, msg_length, response_length,
			      header_present, false);

   brw_inst_set_binding_table_index(devinfo, insn, binding_table_index);
   brw_inst_set_dp_read_msg_type(devinfo, insn, msg_type);
   brw_inst_set_dp_read_msg_control(devinfo, insn, msg_control);
   if (devinfo->gen < 6)
      brw_inst_set_dp_read_target_cache(devinfo, insn, target_cache);
}

void
brw_set_sampler_message(struct brw_codegen *p,
                        brw_inst *inst,
                        unsigned binding_table_index,
                        unsigned sampler,
                        unsigned msg_type,
                        unsigned response_length,
                        unsigned msg_length,
                        unsigned header_present,
                        unsigned simd_mode,
                        unsigned return_format)
{
   const struct gen_device_info *devinfo = p->devinfo;

   brw_set_message_descriptor(p, inst, BRW_SFID_SAMPLER, msg_length,
			      response_length, header_present, false);

   brw_inst_set_binding_table_index(devinfo, inst, binding_table_index);
   brw_inst_set_sampler(devinfo, inst, sampler);
   brw_inst_set_sampler_msg_type(devinfo, inst, msg_type);
   if (devinfo->gen >= 5) {
      brw_inst_set_sampler_simd_mode(devinfo, inst, simd_mode);
   } else if (devinfo->gen == 4 && !devinfo->is_g4x) {
      brw_inst_set_sampler_return_format(devinfo, inst, return_format);
   }
}

static void
gen7_set_dp_scratch_message(struct brw_codegen *p,
                            brw_inst *inst,
                            bool write,
                            bool dword,
                            bool invalidate_after_read,
                            unsigned num_regs,
                            unsigned addr_offset,
                            unsigned mlen,
                            unsigned rlen,
                            bool header_present)
{
   const struct gen_device_info *devinfo = p->devinfo;
   assert(num_regs == 1 || num_regs == 2 || num_regs == 4 ||
          (devinfo->gen >= 8 && num_regs == 8));
   const unsigned block_size = (devinfo->gen >= 8 ? _mesa_logbase2(num_regs) :
                                num_regs - 1);

   brw_set_message_descriptor(p, inst, GEN7_SFID_DATAPORT_DATA_CACHE,
                              mlen, rlen, header_present, false);
   brw_inst_set_dp_category(devinfo, inst, 1); /* Scratch Block Read/Write msgs */
   brw_inst_set_scratch_read_write(devinfo, inst, write);
   brw_inst_set_scratch_type(devinfo, inst, dword);
   brw_inst_set_scratch_invalidate_after_read(devinfo, inst, invalidate_after_read);
   brw_inst_set_scratch_block_size(devinfo, inst, block_size);
   brw_inst_set_scratch_addr_offset(devinfo, inst, addr_offset);
}

#define next_insn brw_next_insn
brw_inst *
brw_next_insn(struct brw_codegen *p, unsigned opcode)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   if (p->nr_insn + 1 > p->store_size) {
      p->store_size <<= 1;
      p->store = reralloc(p->mem_ctx, p->store, brw_inst, p->store_size);
   }

   p->next_insn_offset += 16;
   insn = &p->store[p->nr_insn++];
   memcpy(insn, p->current, sizeof(*insn));

   brw_inst_set_opcode(devinfo, insn, opcode);
   return insn;
}

static brw_inst *
brw_alu1(struct brw_codegen *p, unsigned opcode,
         struct brw_reg dest, struct brw_reg src)
{
   brw_inst *insn = next_insn(p, opcode);
   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src);
   return insn;
}

static brw_inst *
brw_alu2(struct brw_codegen *p, unsigned opcode,
         struct brw_reg dest, struct brw_reg src0, struct brw_reg src1)
{
   /* 64-bit immediates are only supported on 1-src instructions */
   assert(src0.file != BRW_IMMEDIATE_VALUE || type_sz(src0.type) <= 4);
   assert(src1.file != BRW_IMMEDIATE_VALUE || type_sz(src1.type) <= 4);

   brw_inst *insn = next_insn(p, opcode);
   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_src1(p, insn, src1);
   return insn;
}

static int
get_3src_subreg_nr(struct brw_reg reg)
{
   /* Normally, SubRegNum is in bytes (0..31).  However, 3-src instructions
    * use 32-bit units (components 0..7).  Since they only support F/D/UD
    * types, this doesn't lose any flexibility, but uses fewer bits.
    */
   return reg.subnr / 4;
}

static brw_inst *
brw_alu3(struct brw_codegen *p, unsigned opcode, struct brw_reg dest,
         struct brw_reg src0, struct brw_reg src1, struct brw_reg src2)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *inst = next_insn(p, opcode);

   gen7_convert_mrf_to_grf(p, &dest);

   assert(brw_inst_access_mode(devinfo, inst) == BRW_ALIGN_16);

   assert(dest.file == BRW_GENERAL_REGISTER_FILE ||
	  dest.file == BRW_MESSAGE_REGISTER_FILE);
   assert(dest.nr < 128);
   assert(dest.address_mode == BRW_ADDRESS_DIRECT);
   assert(dest.type == BRW_REGISTER_TYPE_F  ||
          dest.type == BRW_REGISTER_TYPE_DF ||
          dest.type == BRW_REGISTER_TYPE_D  ||
          dest.type == BRW_REGISTER_TYPE_UD);
   if (devinfo->gen == 6) {
      brw_inst_set_3src_dst_reg_file(devinfo, inst,
                                     dest.file == BRW_MESSAGE_REGISTER_FILE);
   }
   brw_inst_set_3src_dst_reg_nr(devinfo, inst, dest.nr);
   brw_inst_set_3src_dst_subreg_nr(devinfo, inst, dest.subnr / 16);
   brw_inst_set_3src_dst_writemask(devinfo, inst, dest.writemask);

   assert(src0.file == BRW_GENERAL_REGISTER_FILE);
   assert(src0.address_mode == BRW_ADDRESS_DIRECT);
   assert(src0.nr < 128);
   brw_inst_set_3src_src0_swizzle(devinfo, inst, src0.swizzle);
   brw_inst_set_3src_src0_subreg_nr(devinfo, inst, get_3src_subreg_nr(src0));
   brw_inst_set_3src_src0_reg_nr(devinfo, inst, src0.nr);
   brw_inst_set_3src_src0_abs(devinfo, inst, src0.abs);
   brw_inst_set_3src_src0_negate(devinfo, inst, src0.negate);
   brw_inst_set_3src_src0_rep_ctrl(devinfo, inst,
                                   src0.vstride == BRW_VERTICAL_STRIDE_0);

   assert(src1.file == BRW_GENERAL_REGISTER_FILE);
   assert(src1.address_mode == BRW_ADDRESS_DIRECT);
   assert(src1.nr < 128);
   brw_inst_set_3src_src1_swizzle(devinfo, inst, src1.swizzle);
   brw_inst_set_3src_src1_subreg_nr(devinfo, inst, get_3src_subreg_nr(src1));
   brw_inst_set_3src_src1_reg_nr(devinfo, inst, src1.nr);
   brw_inst_set_3src_src1_abs(devinfo, inst, src1.abs);
   brw_inst_set_3src_src1_negate(devinfo, inst, src1.negate);
   brw_inst_set_3src_src1_rep_ctrl(devinfo, inst,
                                   src1.vstride == BRW_VERTICAL_STRIDE_0);

   assert(src2.file == BRW_GENERAL_REGISTER_FILE);
   assert(src2.address_mode == BRW_ADDRESS_DIRECT);
   assert(src2.nr < 128);
   brw_inst_set_3src_src2_swizzle(devinfo, inst, src2.swizzle);
   brw_inst_set_3src_src2_subreg_nr(devinfo, inst, get_3src_subreg_nr(src2));
   brw_inst_set_3src_src2_reg_nr(devinfo, inst, src2.nr);
   brw_inst_set_3src_src2_abs(devinfo, inst, src2.abs);
   brw_inst_set_3src_src2_negate(devinfo, inst, src2.negate);
   brw_inst_set_3src_src2_rep_ctrl(devinfo, inst,
                                   src2.vstride == BRW_VERTICAL_STRIDE_0);

   if (devinfo->gen >= 7) {
      /* Set both the source and destination types based on dest.type,
       * ignoring the source register types.  The MAD and LRP emitters ensure
       * that all four types are float.  The BFE and BFI2 emitters, however,
       * may send us mixed D and UD types and want us to ignore that and use
       * the destination type.
       */
      switch (dest.type) {
      case BRW_REGISTER_TYPE_F:
         brw_inst_set_3src_src_type(devinfo, inst, BRW_3SRC_TYPE_F);
         brw_inst_set_3src_dst_type(devinfo, inst, BRW_3SRC_TYPE_F);
         break;
      case BRW_REGISTER_TYPE_DF:
         brw_inst_set_3src_src_type(devinfo, inst, BRW_3SRC_TYPE_DF);
         brw_inst_set_3src_dst_type(devinfo, inst, BRW_3SRC_TYPE_DF);
         break;
      case BRW_REGISTER_TYPE_D:
         brw_inst_set_3src_src_type(devinfo, inst, BRW_3SRC_TYPE_D);
         brw_inst_set_3src_dst_type(devinfo, inst, BRW_3SRC_TYPE_D);
         break;
      case BRW_REGISTER_TYPE_UD:
         brw_inst_set_3src_src_type(devinfo, inst, BRW_3SRC_TYPE_UD);
         brw_inst_set_3src_dst_type(devinfo, inst, BRW_3SRC_TYPE_UD);
         break;
      default:
         unreachable("not reached");
      }
   }

   return inst;
}


/***********************************************************************
 * Convenience routines.
 */
#define ALU1(OP)					\
brw_inst *brw_##OP(struct brw_codegen *p,		\
	      struct brw_reg dest,			\
	      struct brw_reg src0)   			\
{							\
   return brw_alu1(p, BRW_OPCODE_##OP, dest, src0);    	\
}

#define ALU2(OP)					\
brw_inst *brw_##OP(struct brw_codegen *p,		\
	      struct brw_reg dest,			\
	      struct brw_reg src0,			\
	      struct brw_reg src1)   			\
{							\
   return brw_alu2(p, BRW_OPCODE_##OP, dest, src0, src1);	\
}

#define ALU3(OP)					\
brw_inst *brw_##OP(struct brw_codegen *p,		\
	      struct brw_reg dest,			\
	      struct brw_reg src0,			\
	      struct brw_reg src1,			\
	      struct brw_reg src2)   			\
{							\
   return brw_alu3(p, BRW_OPCODE_##OP, dest, src0, src1, src2);	\
}

#define ALU3F(OP)                                               \
brw_inst *brw_##OP(struct brw_codegen *p,         \
                                 struct brw_reg dest,           \
                                 struct brw_reg src0,           \
                                 struct brw_reg src1,           \
                                 struct brw_reg src2)           \
{                                                               \
   assert(dest.type == BRW_REGISTER_TYPE_F ||                   \
          dest.type == BRW_REGISTER_TYPE_DF);                   \
   if (dest.type == BRW_REGISTER_TYPE_F) {                      \
      assert(src0.type == BRW_REGISTER_TYPE_F);                 \
      assert(src1.type == BRW_REGISTER_TYPE_F);                 \
      assert(src2.type == BRW_REGISTER_TYPE_F);                 \
   } else if (dest.type == BRW_REGISTER_TYPE_DF) {              \
      assert(src0.type == BRW_REGISTER_TYPE_DF);                \
      assert(src1.type == BRW_REGISTER_TYPE_DF);                \
      assert(src2.type == BRW_REGISTER_TYPE_DF);                \
   }                                                            \
   return brw_alu3(p, BRW_OPCODE_##OP, dest, src0, src1, src2); \
}

/* Rounding operations (other than RNDD) require two instructions - the first
 * stores a rounded value (possibly the wrong way) in the dest register, but
 * also sets a per-channel "increment bit" in the flag register.  A predicated
 * add of 1.0 fixes dest to contain the desired result.
 *
 * Sandybridge and later appear to round correctly without an ADD.
 */
#define ROUND(OP)							      \
void brw_##OP(struct brw_codegen *p,					      \
	      struct brw_reg dest,					      \
	      struct brw_reg src)					      \
{									      \
   const struct gen_device_info *devinfo = p->devinfo;					      \
   brw_inst *rnd, *add;							      \
   rnd = next_insn(p, BRW_OPCODE_##OP);					      \
   brw_set_dest(p, rnd, dest);						      \
   brw_set_src0(p, rnd, src);						      \
									      \
   if (devinfo->gen < 6) {							      \
      /* turn on round-increments */					      \
      brw_inst_set_cond_modifier(devinfo, rnd, BRW_CONDITIONAL_R);            \
      add = brw_ADD(p, dest, dest, brw_imm_f(1.0f));			      \
      brw_inst_set_pred_control(devinfo, add, BRW_PREDICATE_NORMAL);          \
   }									      \
}


ALU2(SEL)
ALU1(NOT)
ALU2(AND)
ALU2(OR)
ALU2(XOR)
ALU2(SHR)
ALU2(SHL)
ALU1(DIM)
ALU2(ASR)
ALU1(FRC)
ALU1(RNDD)
ALU2(MAC)
ALU2(MACH)
ALU1(LZD)
ALU2(DP4)
ALU2(DPH)
ALU2(DP3)
ALU2(DP2)
ALU3F(MAD)
ALU3F(LRP)
ALU1(BFREV)
ALU3(BFE)
ALU2(BFI1)
ALU3(BFI2)
ALU1(FBH)
ALU1(FBL)
ALU1(CBIT)
ALU2(ADDC)
ALU2(SUBB)

ROUND(RNDZ)
ROUND(RNDE)

brw_inst *
brw_MOV(struct brw_codegen *p, struct brw_reg dest, struct brw_reg src0)
{
   const struct gen_device_info *devinfo = p->devinfo;

   /* When converting F->DF on IVB/BYT, every odd source channel is ignored.
    * To avoid the problems that causes, we use a <1,2,0> source region to read
    * each element twice.
    */
   if (devinfo->gen == 7 && !devinfo->is_haswell &&
       brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1 &&
       dest.type == BRW_REGISTER_TYPE_DF &&
       (src0.type == BRW_REGISTER_TYPE_F ||
        src0.type == BRW_REGISTER_TYPE_D ||
        src0.type == BRW_REGISTER_TYPE_UD) &&
       !has_scalar_region(src0)) {
      assert(src0.vstride == BRW_VERTICAL_STRIDE_4 &&
             src0.width == BRW_WIDTH_4 &&
             src0.hstride == BRW_HORIZONTAL_STRIDE_1);

      src0.vstride = BRW_VERTICAL_STRIDE_1;
      src0.width = BRW_WIDTH_2;
      src0.hstride = BRW_HORIZONTAL_STRIDE_0;
   }

   return brw_alu1(p, BRW_OPCODE_MOV, dest, src0);
}

brw_inst *
brw_ADD(struct brw_codegen *p, struct brw_reg dest,
        struct brw_reg src0, struct brw_reg src1)
{
   /* 6.2.2: add */
   if (src0.type == BRW_REGISTER_TYPE_F ||
       (src0.file == BRW_IMMEDIATE_VALUE &&
	src0.type == BRW_REGISTER_TYPE_VF)) {
      assert(src1.type != BRW_REGISTER_TYPE_UD);
      assert(src1.type != BRW_REGISTER_TYPE_D);
   }

   if (src1.type == BRW_REGISTER_TYPE_F ||
       (src1.file == BRW_IMMEDIATE_VALUE &&
	src1.type == BRW_REGISTER_TYPE_VF)) {
      assert(src0.type != BRW_REGISTER_TYPE_UD);
      assert(src0.type != BRW_REGISTER_TYPE_D);
   }

   return brw_alu2(p, BRW_OPCODE_ADD, dest, src0, src1);
}

brw_inst *
brw_AVG(struct brw_codegen *p, struct brw_reg dest,
        struct brw_reg src0, struct brw_reg src1)
{
   assert(dest.type == src0.type);
   assert(src0.type == src1.type);
   switch (src0.type) {
   case BRW_REGISTER_TYPE_B:
   case BRW_REGISTER_TYPE_UB:
   case BRW_REGISTER_TYPE_W:
   case BRW_REGISTER_TYPE_UW:
   case BRW_REGISTER_TYPE_D:
   case BRW_REGISTER_TYPE_UD:
      break;
   default:
      unreachable("Bad type for brw_AVG");
   }

   return brw_alu2(p, BRW_OPCODE_AVG, dest, src0, src1);
}

brw_inst *
brw_MUL(struct brw_codegen *p, struct brw_reg dest,
        struct brw_reg src0, struct brw_reg src1)
{
   /* 6.32.38: mul */
   if (src0.type == BRW_REGISTER_TYPE_D ||
       src0.type == BRW_REGISTER_TYPE_UD ||
       src1.type == BRW_REGISTER_TYPE_D ||
       src1.type == BRW_REGISTER_TYPE_UD) {
      assert(dest.type != BRW_REGISTER_TYPE_F);
   }

   if (src0.type == BRW_REGISTER_TYPE_F ||
       (src0.file == BRW_IMMEDIATE_VALUE &&
	src0.type == BRW_REGISTER_TYPE_VF)) {
      assert(src1.type != BRW_REGISTER_TYPE_UD);
      assert(src1.type != BRW_REGISTER_TYPE_D);
   }

   if (src1.type == BRW_REGISTER_TYPE_F ||
       (src1.file == BRW_IMMEDIATE_VALUE &&
	src1.type == BRW_REGISTER_TYPE_VF)) {
      assert(src0.type != BRW_REGISTER_TYPE_UD);
      assert(src0.type != BRW_REGISTER_TYPE_D);
   }

   assert(src0.file != BRW_ARCHITECTURE_REGISTER_FILE ||
	  src0.nr != BRW_ARF_ACCUMULATOR);
   assert(src1.file != BRW_ARCHITECTURE_REGISTER_FILE ||
	  src1.nr != BRW_ARF_ACCUMULATOR);

   return brw_alu2(p, BRW_OPCODE_MUL, dest, src0, src1);
}

brw_inst *
brw_LINE(struct brw_codegen *p, struct brw_reg dest,
         struct brw_reg src0, struct brw_reg src1)
{
   src0.vstride = BRW_VERTICAL_STRIDE_0;
   src0.width = BRW_WIDTH_1;
   src0.hstride = BRW_HORIZONTAL_STRIDE_0;
   return brw_alu2(p, BRW_OPCODE_LINE, dest, src0, src1);
}

brw_inst *
brw_PLN(struct brw_codegen *p, struct brw_reg dest,
        struct brw_reg src0, struct brw_reg src1)
{
   src0.vstride = BRW_VERTICAL_STRIDE_0;
   src0.width = BRW_WIDTH_1;
   src0.hstride = BRW_HORIZONTAL_STRIDE_0;
   src1.vstride = BRW_VERTICAL_STRIDE_8;
   src1.width = BRW_WIDTH_8;
   src1.hstride = BRW_HORIZONTAL_STRIDE_1;
   return brw_alu2(p, BRW_OPCODE_PLN, dest, src0, src1);
}

brw_inst *
brw_F32TO16(struct brw_codegen *p, struct brw_reg dst, struct brw_reg src)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const bool align16 = brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_16;
   /* The F32TO16 instruction doesn't support 32-bit destination types in
    * Align1 mode, and neither does the Gen8 implementation in terms of a
    * converting MOV.  Gen7 does zero out the high 16 bits in Align16 mode as
    * an undocumented feature.
    */
   const bool needs_zero_fill = (dst.type == BRW_REGISTER_TYPE_UD &&
                                 (!align16 || devinfo->gen >= 8));
   brw_inst *inst;

   if (align16) {
      assert(dst.type == BRW_REGISTER_TYPE_UD);
   } else {
      assert(dst.type == BRW_REGISTER_TYPE_UD ||
             dst.type == BRW_REGISTER_TYPE_W ||
             dst.type == BRW_REGISTER_TYPE_UW ||
             dst.type == BRW_REGISTER_TYPE_HF);
   }

   brw_push_insn_state(p);

   if (needs_zero_fill) {
      brw_set_default_access_mode(p, BRW_ALIGN_1);
      dst = spread(retype(dst, BRW_REGISTER_TYPE_W), 2);
   }

   if (devinfo->gen >= 8) {
      inst = brw_MOV(p, retype(dst, BRW_REGISTER_TYPE_HF), src);
   } else {
      assert(devinfo->gen == 7);
      inst = brw_alu1(p, BRW_OPCODE_F32TO16, dst, src);
   }

   if (needs_zero_fill) {
      brw_inst_set_no_dd_clear(devinfo, inst, true);
      inst = brw_MOV(p, suboffset(dst, 1), brw_imm_w(0));
      brw_inst_set_no_dd_check(devinfo, inst, true);
   }

   brw_pop_insn_state(p);
   return inst;
}

brw_inst *
brw_F16TO32(struct brw_codegen *p, struct brw_reg dst, struct brw_reg src)
{
   const struct gen_device_info *devinfo = p->devinfo;
   bool align16 = brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_16;

   if (align16) {
      assert(src.type == BRW_REGISTER_TYPE_UD);
   } else {
      /* From the Ivybridge PRM, Vol4, Part3, Section 6.26 f16to32:
       *
       *   Because this instruction does not have a 16-bit floating-point
       *   type, the source data type must be Word (W). The destination type
       *   must be F (Float).
       */
      if (src.type == BRW_REGISTER_TYPE_UD)
         src = spread(retype(src, BRW_REGISTER_TYPE_W), 2);

      assert(src.type == BRW_REGISTER_TYPE_W ||
             src.type == BRW_REGISTER_TYPE_UW ||
             src.type == BRW_REGISTER_TYPE_HF);
   }

   if (devinfo->gen >= 8) {
      return brw_MOV(p, dst, retype(src, BRW_REGISTER_TYPE_HF));
   } else {
      assert(devinfo->gen == 7);
      return brw_alu1(p, BRW_OPCODE_F16TO32, dst, src);
   }
}


void brw_NOP(struct brw_codegen *p)
{
   brw_inst *insn = next_insn(p, BRW_OPCODE_NOP);
   memset(insn, 0, sizeof(*insn));
   brw_inst_set_opcode(p->devinfo, insn, BRW_OPCODE_NOP);
}





/***********************************************************************
 * Comparisons, if/else/endif
 */

brw_inst *
brw_JMPI(struct brw_codegen *p, struct brw_reg index,
         unsigned predicate_control)
{
   const struct gen_device_info *devinfo = p->devinfo;
   struct brw_reg ip = brw_ip_reg();
   brw_inst *inst = brw_alu2(p, BRW_OPCODE_JMPI, ip, ip, index);

   brw_inst_set_exec_size(devinfo, inst, BRW_EXECUTE_2);
   brw_inst_set_qtr_control(devinfo, inst, BRW_COMPRESSION_NONE);
   brw_inst_set_mask_control(devinfo, inst, BRW_MASK_DISABLE);
   brw_inst_set_pred_control(devinfo, inst, predicate_control);

   return inst;
}

static void
push_if_stack(struct brw_codegen *p, brw_inst *inst)
{
   p->if_stack[p->if_stack_depth] = inst - p->store;

   p->if_stack_depth++;
   if (p->if_stack_array_size <= p->if_stack_depth) {
      p->if_stack_array_size *= 2;
      p->if_stack = reralloc(p->mem_ctx, p->if_stack, int,
			     p->if_stack_array_size);
   }
}

static brw_inst *
pop_if_stack(struct brw_codegen *p)
{
   p->if_stack_depth--;
   return &p->store[p->if_stack[p->if_stack_depth]];
}

static void
push_loop_stack(struct brw_codegen *p, brw_inst *inst)
{
   if (p->loop_stack_array_size <= (p->loop_stack_depth + 1)) {
      p->loop_stack_array_size *= 2;
      p->loop_stack = reralloc(p->mem_ctx, p->loop_stack, int,
			       p->loop_stack_array_size);
      p->if_depth_in_loop = reralloc(p->mem_ctx, p->if_depth_in_loop, int,
				     p->loop_stack_array_size);
   }

   p->loop_stack[p->loop_stack_depth] = inst - p->store;
   p->loop_stack_depth++;
   p->if_depth_in_loop[p->loop_stack_depth] = 0;
}

static brw_inst *
get_inner_do_insn(struct brw_codegen *p)
{
   return &p->store[p->loop_stack[p->loop_stack_depth - 1]];
}

/* EU takes the value from the flag register and pushes it onto some
 * sort of a stack (presumably merging with any flag value already on
 * the stack).  Within an if block, the flags at the top of the stack
 * control execution on each channel of the unit, eg. on each of the
 * 16 pixel values in our wm programs.
 *
 * When the matching 'else' instruction is reached (presumably by
 * countdown of the instruction count patched in by our ELSE/ENDIF
 * functions), the relevant flags are inverted.
 *
 * When the matching 'endif' instruction is reached, the flags are
 * popped off.  If the stack is now empty, normal execution resumes.
 */
brw_inst *
brw_IF(struct brw_codegen *p, unsigned execute_size)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   insn = next_insn(p, BRW_OPCODE_IF);

   /* Override the defaults for this instruction:
    */
   if (devinfo->gen < 6) {
      brw_set_dest(p, insn, brw_ip_reg());
      brw_set_src0(p, insn, brw_ip_reg());
      brw_set_src1(p, insn, brw_imm_d(0x0));
   } else if (devinfo->gen == 6) {
      brw_set_dest(p, insn, brw_imm_w(0));
      brw_inst_set_gen6_jump_count(devinfo, insn, 0);
      brw_set_src0(p, insn, vec1(retype(brw_null_reg(), BRW_REGISTER_TYPE_D)));
      brw_set_src1(p, insn, vec1(retype(brw_null_reg(), BRW_REGISTER_TYPE_D)));
   } else if (devinfo->gen == 7) {
      brw_set_dest(p, insn, vec1(retype(brw_null_reg(), BRW_REGISTER_TYPE_D)));
      brw_set_src0(p, insn, vec1(retype(brw_null_reg(), BRW_REGISTER_TYPE_D)));
      brw_set_src1(p, insn, brw_imm_w(0));
      brw_inst_set_jip(devinfo, insn, 0);
      brw_inst_set_uip(devinfo, insn, 0);
   } else {
      brw_set_dest(p, insn, vec1(retype(brw_null_reg(), BRW_REGISTER_TYPE_D)));
      brw_set_src0(p, insn, brw_imm_d(0));
      brw_inst_set_jip(devinfo, insn, 0);
      brw_inst_set_uip(devinfo, insn, 0);
   }

   brw_inst_set_exec_size(devinfo, insn, execute_size);
   brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);
   brw_inst_set_pred_control(devinfo, insn, BRW_PREDICATE_NORMAL);
   brw_inst_set_mask_control(devinfo, insn, BRW_MASK_ENABLE);
   if (!p->single_program_flow && devinfo->gen < 6)
      brw_inst_set_thread_control(devinfo, insn, BRW_THREAD_SWITCH);

   push_if_stack(p, insn);
   p->if_depth_in_loop[p->loop_stack_depth]++;
   return insn;
}

/* This function is only used for gen6-style IF instructions with an
 * embedded comparison (conditional modifier).  It is not used on gen7.
 */
brw_inst *
gen6_IF(struct brw_codegen *p, enum brw_conditional_mod conditional,
	struct brw_reg src0, struct brw_reg src1)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   insn = next_insn(p, BRW_OPCODE_IF);

   brw_set_dest(p, insn, brw_imm_w(0));
   brw_inst_set_exec_size(devinfo, insn,
                          brw_inst_exec_size(devinfo, p->current));
   brw_inst_set_gen6_jump_count(devinfo, insn, 0);
   brw_set_src0(p, insn, src0);
   brw_set_src1(p, insn, src1);

   assert(brw_inst_qtr_control(devinfo, insn) == BRW_COMPRESSION_NONE);
   assert(brw_inst_pred_control(devinfo, insn) == BRW_PREDICATE_NONE);
   brw_inst_set_cond_modifier(devinfo, insn, conditional);

   push_if_stack(p, insn);
   return insn;
}

/**
 * In single-program-flow (SPF) mode, convert IF and ELSE into ADDs.
 */
static void
convert_IF_ELSE_to_ADD(struct brw_codegen *p,
                       brw_inst *if_inst, brw_inst *else_inst)
{
   const struct gen_device_info *devinfo = p->devinfo;

   /* The next instruction (where the ENDIF would be, if it existed) */
   brw_inst *next_inst = &p->store[p->nr_insn];

   assert(p->single_program_flow);
   assert(if_inst != NULL && brw_inst_opcode(devinfo, if_inst) == BRW_OPCODE_IF);
   assert(else_inst == NULL || brw_inst_opcode(devinfo, else_inst) == BRW_OPCODE_ELSE);
   assert(brw_inst_exec_size(devinfo, if_inst) == BRW_EXECUTE_1);

   /* Convert IF to an ADD instruction that moves the instruction pointer
    * to the first instruction of the ELSE block.  If there is no ELSE
    * block, point to where ENDIF would be.  Reverse the predicate.
    *
    * There's no need to execute an ENDIF since we don't need to do any
    * stack operations, and if we're currently executing, we just want to
    * continue normally.
    */
   brw_inst_set_opcode(devinfo, if_inst, BRW_OPCODE_ADD);
   brw_inst_set_pred_inv(devinfo, if_inst, true);

   if (else_inst != NULL) {
      /* Convert ELSE to an ADD instruction that points where the ENDIF
       * would be.
       */
      brw_inst_set_opcode(devinfo, else_inst, BRW_OPCODE_ADD);

      brw_inst_set_imm_ud(devinfo, if_inst, (else_inst - if_inst + 1) * 16);
      brw_inst_set_imm_ud(devinfo, else_inst, (next_inst - else_inst) * 16);
   } else {
      brw_inst_set_imm_ud(devinfo, if_inst, (next_inst - if_inst) * 16);
   }
}

/**
 * Patch IF and ELSE instructions with appropriate jump targets.
 */
static void
patch_IF_ELSE(struct brw_codegen *p,
              brw_inst *if_inst, brw_inst *else_inst, brw_inst *endif_inst)
{
   const struct gen_device_info *devinfo = p->devinfo;

   /* We shouldn't be patching IF and ELSE instructions in single program flow
    * mode when gen < 6, because in single program flow mode on those
    * platforms, we convert flow control instructions to conditional ADDs that
    * operate on IP (see brw_ENDIF).
    *
    * However, on Gen6, writing to IP doesn't work in single program flow mode
    * (see the SandyBridge PRM, Volume 4 part 2, p79: "When SPF is ON, IP may
    * not be updated by non-flow control instructions.").  And on later
    * platforms, there is no significant benefit to converting control flow
    * instructions to conditional ADDs.  So we do patch IF and ELSE
    * instructions in single program flow mode on those platforms.
    */
   if (devinfo->gen < 6)
      assert(!p->single_program_flow);

   assert(if_inst != NULL && brw_inst_opcode(devinfo, if_inst) == BRW_OPCODE_IF);
   assert(endif_inst != NULL);
   assert(else_inst == NULL || brw_inst_opcode(devinfo, else_inst) == BRW_OPCODE_ELSE);

   unsigned br = brw_jump_scale(devinfo);

   assert(brw_inst_opcode(devinfo, endif_inst) == BRW_OPCODE_ENDIF);
   brw_inst_set_exec_size(devinfo, endif_inst, brw_inst_exec_size(devinfo, if_inst));

   if (else_inst == NULL) {
      /* Patch IF -> ENDIF */
      if (devinfo->gen < 6) {
	 /* Turn it into an IFF, which means no mask stack operations for
	  * all-false and jumping past the ENDIF.
	  */
         brw_inst_set_opcode(devinfo, if_inst, BRW_OPCODE_IFF);
         brw_inst_set_gen4_jump_count(devinfo, if_inst,
                                      br * (endif_inst - if_inst + 1));
         brw_inst_set_gen4_pop_count(devinfo, if_inst, 0);
      } else if (devinfo->gen == 6) {
	 /* As of gen6, there is no IFF and IF must point to the ENDIF. */
         brw_inst_set_gen6_jump_count(devinfo, if_inst, br*(endif_inst - if_inst));
      } else {
         brw_inst_set_uip(devinfo, if_inst, br * (endif_inst - if_inst));
         brw_inst_set_jip(devinfo, if_inst, br * (endif_inst - if_inst));
      }
   } else {
      brw_inst_set_exec_size(devinfo, else_inst, brw_inst_exec_size(devinfo, if_inst));

      /* Patch IF -> ELSE */
      if (devinfo->gen < 6) {
         brw_inst_set_gen4_jump_count(devinfo, if_inst,
                                      br * (else_inst - if_inst));
         brw_inst_set_gen4_pop_count(devinfo, if_inst, 0);
      } else if (devinfo->gen == 6) {
         brw_inst_set_gen6_jump_count(devinfo, if_inst,
                                      br * (else_inst - if_inst + 1));
      }

      /* Patch ELSE -> ENDIF */
      if (devinfo->gen < 6) {
	 /* BRW_OPCODE_ELSE pre-gen6 should point just past the
	  * matching ENDIF.
	  */
         brw_inst_set_gen4_jump_count(devinfo, else_inst,
                                      br * (endif_inst - else_inst + 1));
         brw_inst_set_gen4_pop_count(devinfo, else_inst, 1);
      } else if (devinfo->gen == 6) {
	 /* BRW_OPCODE_ELSE on gen6 should point to the matching ENDIF. */
         brw_inst_set_gen6_jump_count(devinfo, else_inst,
                                      br * (endif_inst - else_inst));
      } else {
	 /* The IF instruction's JIP should point just past the ELSE */
         brw_inst_set_jip(devinfo, if_inst, br * (else_inst - if_inst + 1));
	 /* The IF instruction's UIP and ELSE's JIP should point to ENDIF */
         brw_inst_set_uip(devinfo, if_inst, br * (endif_inst - if_inst));
         brw_inst_set_jip(devinfo, else_inst, br * (endif_inst - else_inst));
         if (devinfo->gen >= 8) {
            /* Since we don't set branch_ctrl, the ELSE's JIP and UIP both
             * should point to ENDIF.
             */
            brw_inst_set_uip(devinfo, else_inst, br * (endif_inst - else_inst));
         }
      }
   }
}

void
brw_ELSE(struct brw_codegen *p)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   insn = next_insn(p, BRW_OPCODE_ELSE);

   if (devinfo->gen < 6) {
      brw_set_dest(p, insn, brw_ip_reg());
      brw_set_src0(p, insn, brw_ip_reg());
      brw_set_src1(p, insn, brw_imm_d(0x0));
   } else if (devinfo->gen == 6) {
      brw_set_dest(p, insn, brw_imm_w(0));
      brw_inst_set_gen6_jump_count(devinfo, insn, 0);
      brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src1(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
   } else if (devinfo->gen == 7) {
      brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src1(p, insn, brw_imm_w(0));
      brw_inst_set_jip(devinfo, insn, 0);
      brw_inst_set_uip(devinfo, insn, 0);
   } else {
      brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src0(p, insn, brw_imm_d(0));
      brw_inst_set_jip(devinfo, insn, 0);
      brw_inst_set_uip(devinfo, insn, 0);
   }

   brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);
   brw_inst_set_mask_control(devinfo, insn, BRW_MASK_ENABLE);
   if (!p->single_program_flow && devinfo->gen < 6)
      brw_inst_set_thread_control(devinfo, insn, BRW_THREAD_SWITCH);

   push_if_stack(p, insn);
}

void
brw_ENDIF(struct brw_codegen *p)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn = NULL;
   brw_inst *else_inst = NULL;
   brw_inst *if_inst = NULL;
   brw_inst *tmp;
   bool emit_endif = true;

   /* In single program flow mode, we can express IF and ELSE instructions
    * equivalently as ADD instructions that operate on IP.  On platforms prior
    * to Gen6, flow control instructions cause an implied thread switch, so
    * this is a significant savings.
    *
    * However, on Gen6, writing to IP doesn't work in single program flow mode
    * (see the SandyBridge PRM, Volume 4 part 2, p79: "When SPF is ON, IP may
    * not be updated by non-flow control instructions.").  And on later
    * platforms, there is no significant benefit to converting control flow
    * instructions to conditional ADDs.  So we only do this trick on Gen4 and
    * Gen5.
    */
   if (devinfo->gen < 6 && p->single_program_flow)
      emit_endif = false;

   /*
    * A single next_insn() may change the base address of instruction store
    * memory(p->store), so call it first before referencing the instruction
    * store pointer from an index
    */
   if (emit_endif)
      insn = next_insn(p, BRW_OPCODE_ENDIF);

   /* Pop the IF and (optional) ELSE instructions from the stack */
   p->if_depth_in_loop[p->loop_stack_depth]--;
   tmp = pop_if_stack(p);
   if (brw_inst_opcode(devinfo, tmp) == BRW_OPCODE_ELSE) {
      else_inst = tmp;
      tmp = pop_if_stack(p);
   }
   if_inst = tmp;

   if (!emit_endif) {
      /* ENDIF is useless; don't bother emitting it. */
      convert_IF_ELSE_to_ADD(p, if_inst, else_inst);
      return;
   }

   if (devinfo->gen < 6) {
      brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src1(p, insn, brw_imm_d(0x0));
   } else if (devinfo->gen == 6) {
      brw_set_dest(p, insn, brw_imm_w(0));
      brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src1(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
   } else if (devinfo->gen == 7) {
      brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src1(p, insn, brw_imm_w(0));
   } else {
      brw_set_src0(p, insn, brw_imm_d(0));
   }

   brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);
   brw_inst_set_mask_control(devinfo, insn, BRW_MASK_ENABLE);
   if (devinfo->gen < 6)
      brw_inst_set_thread_control(devinfo, insn, BRW_THREAD_SWITCH);

   /* Also pop item off the stack in the endif instruction: */
   if (devinfo->gen < 6) {
      brw_inst_set_gen4_jump_count(devinfo, insn, 0);
      brw_inst_set_gen4_pop_count(devinfo, insn, 1);
   } else if (devinfo->gen == 6) {
      brw_inst_set_gen6_jump_count(devinfo, insn, 2);
   } else {
      brw_inst_set_jip(devinfo, insn, 2);
   }
   patch_IF_ELSE(p, if_inst, else_inst, insn);
}

brw_inst *
brw_BREAK(struct brw_codegen *p)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   insn = next_insn(p, BRW_OPCODE_BREAK);
   if (devinfo->gen >= 8) {
      brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src0(p, insn, brw_imm_d(0x0));
   } else if (devinfo->gen >= 6) {
      brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src1(p, insn, brw_imm_d(0x0));
   } else {
      brw_set_dest(p, insn, brw_ip_reg());
      brw_set_src0(p, insn, brw_ip_reg());
      brw_set_src1(p, insn, brw_imm_d(0x0));
      brw_inst_set_gen4_pop_count(devinfo, insn,
                                  p->if_depth_in_loop[p->loop_stack_depth]);
   }
   brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);
   brw_inst_set_exec_size(devinfo, insn,
                          brw_inst_exec_size(devinfo, p->current));

   return insn;
}

brw_inst *
brw_CONT(struct brw_codegen *p)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   insn = next_insn(p, BRW_OPCODE_CONTINUE);
   brw_set_dest(p, insn, brw_ip_reg());
   if (devinfo->gen >= 8) {
      brw_set_src0(p, insn, brw_imm_d(0x0));
   } else {
      brw_set_src0(p, insn, brw_ip_reg());
      brw_set_src1(p, insn, brw_imm_d(0x0));
   }

   if (devinfo->gen < 6) {
      brw_inst_set_gen4_pop_count(devinfo, insn,
                                  p->if_depth_in_loop[p->loop_stack_depth]);
   }
   brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);
   brw_inst_set_exec_size(devinfo, insn,
                          brw_inst_exec_size(devinfo, p->current));
   return insn;
}

brw_inst *
gen6_HALT(struct brw_codegen *p)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   insn = next_insn(p, BRW_OPCODE_HALT);
   brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
   if (devinfo->gen >= 8) {
      brw_set_src0(p, insn, brw_imm_d(0x0));
   } else {
      brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      brw_set_src1(p, insn, brw_imm_d(0x0)); /* UIP and JIP, updated later. */
   }

   brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);
   brw_inst_set_exec_size(devinfo, insn,
                          brw_inst_exec_size(devinfo, p->current));
   return insn;
}

/* DO/WHILE loop:
 *
 * The DO/WHILE is just an unterminated loop -- break or continue are
 * used for control within the loop.  We have a few ways they can be
 * done.
 *
 * For uniform control flow, the WHILE is just a jump, so ADD ip, ip,
 * jip and no DO instruction.
 *
 * For non-uniform control flow pre-gen6, there's a DO instruction to
 * push the mask, and a WHILE to jump back, and BREAK to get out and
 * pop the mask.
 *
 * For gen6, there's no more mask stack, so no need for DO.  WHILE
 * just points back to the first instruction of the loop.
 */
brw_inst *
brw_DO(struct brw_codegen *p, unsigned execute_size)
{
   const struct gen_device_info *devinfo = p->devinfo;

   if (devinfo->gen >= 6 || p->single_program_flow) {
      push_loop_stack(p, &p->store[p->nr_insn]);
      return &p->store[p->nr_insn];
   } else {
      brw_inst *insn = next_insn(p, BRW_OPCODE_DO);

      push_loop_stack(p, insn);

      /* Override the defaults for this instruction:
       */
      brw_set_dest(p, insn, brw_null_reg());
      brw_set_src0(p, insn, brw_null_reg());
      brw_set_src1(p, insn, brw_null_reg());

      brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);
      brw_inst_set_exec_size(devinfo, insn, execute_size);
      brw_inst_set_pred_control(devinfo, insn, BRW_PREDICATE_NONE);

      return insn;
   }
}

/**
 * For pre-gen6, we patch BREAK/CONT instructions to point at the WHILE
 * instruction here.
 *
 * For gen6+, see brw_set_uip_jip(), which doesn't care so much about the loop
 * nesting, since it can always just point to the end of the block/current loop.
 */
static void
brw_patch_break_cont(struct brw_codegen *p, brw_inst *while_inst)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *do_inst = get_inner_do_insn(p);
   brw_inst *inst;
   unsigned br = brw_jump_scale(devinfo);

   assert(devinfo->gen < 6);

   for (inst = while_inst - 1; inst != do_inst; inst--) {
      /* If the jump count is != 0, that means that this instruction has already
       * been patched because it's part of a loop inside of the one we're
       * patching.
       */
      if (brw_inst_opcode(devinfo, inst) == BRW_OPCODE_BREAK &&
          brw_inst_gen4_jump_count(devinfo, inst) == 0) {
         brw_inst_set_gen4_jump_count(devinfo, inst, br*((while_inst - inst) + 1));
      } else if (brw_inst_opcode(devinfo, inst) == BRW_OPCODE_CONTINUE &&
                 brw_inst_gen4_jump_count(devinfo, inst) == 0) {
         brw_inst_set_gen4_jump_count(devinfo, inst, br * (while_inst - inst));
      }
   }
}

brw_inst *
brw_WHILE(struct brw_codegen *p)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn, *do_insn;
   unsigned br = brw_jump_scale(devinfo);

   if (devinfo->gen >= 6) {
      insn = next_insn(p, BRW_OPCODE_WHILE);
      do_insn = get_inner_do_insn(p);

      if (devinfo->gen >= 8) {
         brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
         brw_set_src0(p, insn, brw_imm_d(0));
         brw_inst_set_jip(devinfo, insn, br * (do_insn - insn));
      } else if (devinfo->gen == 7) {
         brw_set_dest(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
         brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
         brw_set_src1(p, insn, brw_imm_w(0));
         brw_inst_set_jip(devinfo, insn, br * (do_insn - insn));
      } else {
         brw_set_dest(p, insn, brw_imm_w(0));
         brw_inst_set_gen6_jump_count(devinfo, insn, br * (do_insn - insn));
         brw_set_src0(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
         brw_set_src1(p, insn, retype(brw_null_reg(), BRW_REGISTER_TYPE_D));
      }

      brw_inst_set_exec_size(devinfo, insn,
                             brw_inst_exec_size(devinfo, p->current));

   } else {
      if (p->single_program_flow) {
	 insn = next_insn(p, BRW_OPCODE_ADD);
         do_insn = get_inner_do_insn(p);

	 brw_set_dest(p, insn, brw_ip_reg());
	 brw_set_src0(p, insn, brw_ip_reg());
	 brw_set_src1(p, insn, brw_imm_d((do_insn - insn) * 16));
         brw_inst_set_exec_size(devinfo, insn, BRW_EXECUTE_1);
      } else {
	 insn = next_insn(p, BRW_OPCODE_WHILE);
         do_insn = get_inner_do_insn(p);

         assert(brw_inst_opcode(devinfo, do_insn) == BRW_OPCODE_DO);

	 brw_set_dest(p, insn, brw_ip_reg());
	 brw_set_src0(p, insn, brw_ip_reg());
	 brw_set_src1(p, insn, brw_imm_d(0));

         brw_inst_set_exec_size(devinfo, insn, brw_inst_exec_size(devinfo, do_insn));
         brw_inst_set_gen4_jump_count(devinfo, insn, br * (do_insn - insn + 1));
         brw_inst_set_gen4_pop_count(devinfo, insn, 0);

	 brw_patch_break_cont(p, insn);
      }
   }
   brw_inst_set_qtr_control(devinfo, insn, BRW_COMPRESSION_NONE);

   p->loop_stack_depth--;

   return insn;
}

/* FORWARD JUMPS:
 */
void brw_land_fwd_jump(struct brw_codegen *p, int jmp_insn_idx)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *jmp_insn = &p->store[jmp_insn_idx];
   unsigned jmpi = 1;

   if (devinfo->gen >= 5)
      jmpi = 2;

   assert(brw_inst_opcode(devinfo, jmp_insn) == BRW_OPCODE_JMPI);
   assert(brw_inst_src1_reg_file(devinfo, jmp_insn) == BRW_IMMEDIATE_VALUE);

   brw_inst_set_gen4_jump_count(devinfo, jmp_insn,
                                jmpi * (p->nr_insn - jmp_insn_idx - 1));
}

/* To integrate with the above, it makes sense that the comparison
 * instruction should populate the flag register.  It might be simpler
 * just to use the flag reg for most WM tasks?
 */
void brw_CMP(struct brw_codegen *p,
	     struct brw_reg dest,
	     unsigned conditional,
	     struct brw_reg src0,
	     struct brw_reg src1)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn = next_insn(p, BRW_OPCODE_CMP);

   brw_inst_set_cond_modifier(devinfo, insn, conditional);
   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_src1(p, insn, src1);

   /* Item WaCMPInstNullDstForcesThreadSwitch in the Haswell Bspec workarounds
    * page says:
    *    "Any CMP instruction with a null destination must use a {switch}."
    *
    * It also applies to other Gen7 platforms (IVB, BYT) even though it isn't
    * mentioned on their work-arounds pages.
    */
   if (devinfo->gen == 7) {
      if (dest.file == BRW_ARCHITECTURE_REGISTER_FILE &&
          dest.nr == BRW_ARF_NULL) {
         brw_inst_set_thread_control(devinfo, insn, BRW_THREAD_SWITCH);
      }
   }
}

/***********************************************************************
 * Helpers for the various SEND message types:
 */

/** Extended math function, float[8].
 */
void gen4_math(struct brw_codegen *p,
	       struct brw_reg dest,
	       unsigned function,
	       unsigned msg_reg_nr,
	       struct brw_reg src,
	       unsigned precision )
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn = next_insn(p, BRW_OPCODE_SEND);
   unsigned data_type;
   if (has_scalar_region(src)) {
      data_type = BRW_MATH_DATA_SCALAR;
   } else {
      data_type = BRW_MATH_DATA_VECTOR;
   }

   assert(devinfo->gen < 6);

   /* Example code doesn't set predicate_control for send
    * instructions.
    */
   brw_inst_set_pred_control(devinfo, insn, 0);
   brw_inst_set_base_mrf(devinfo, insn, msg_reg_nr);

   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src);
   brw_set_math_message(p,
                        insn,
                        function,
                        src.type == BRW_REGISTER_TYPE_D,
                        precision,
                        data_type);
}

void gen6_math(struct brw_codegen *p,
	       struct brw_reg dest,
	       unsigned function,
	       struct brw_reg src0,
	       struct brw_reg src1)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn = next_insn(p, BRW_OPCODE_MATH);

   assert(devinfo->gen >= 6);

   assert(dest.file == BRW_GENERAL_REGISTER_FILE ||
          (devinfo->gen >= 7 && dest.file == BRW_MESSAGE_REGISTER_FILE));

   assert(dest.hstride == BRW_HORIZONTAL_STRIDE_1);
   if (devinfo->gen == 6) {
      assert(src0.hstride == BRW_HORIZONTAL_STRIDE_1);
      assert(src1.hstride == BRW_HORIZONTAL_STRIDE_1);
   }

   if (function == BRW_MATH_FUNCTION_INT_DIV_QUOTIENT ||
       function == BRW_MATH_FUNCTION_INT_DIV_REMAINDER ||
       function == BRW_MATH_FUNCTION_INT_DIV_QUOTIENT_AND_REMAINDER) {
      assert(src0.type != BRW_REGISTER_TYPE_F);
      assert(src1.type != BRW_REGISTER_TYPE_F);
      assert(src1.file == BRW_GENERAL_REGISTER_FILE ||
             (devinfo->gen >= 8 && src1.file == BRW_IMMEDIATE_VALUE));
   } else {
      assert(src0.type == BRW_REGISTER_TYPE_F);
      assert(src1.type == BRW_REGISTER_TYPE_F);
   }

   /* Source modifiers are ignored for extended math instructions on Gen6. */
   if (devinfo->gen == 6) {
      assert(!src0.negate);
      assert(!src0.abs);
      assert(!src1.negate);
      assert(!src1.abs);
   }

   brw_inst_set_math_function(devinfo, insn, function);

   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_src1(p, insn, src1);
}

/**
 * Return the right surface index to access the thread scratch space using
 * stateless dataport messages.
 */
unsigned
brw_scratch_surface_idx(const struct brw_codegen *p)
{
   /* The scratch space is thread-local so IA coherency is unnecessary. */
   if (p->devinfo->gen >= 8)
      return GEN8_BTI_STATELESS_NON_COHERENT;
   else
      return BRW_BTI_STATELESS;
}

/**
 * Write a block of OWORDs (half a GRF each) from the scratch buffer,
 * using a constant offset per channel.
 *
 * The offset must be aligned to oword size (16 bytes).  Used for
 * register spilling.
 */
void brw_oword_block_write_scratch(struct brw_codegen *p,
				   struct brw_reg mrf,
				   int num_regs,
				   unsigned offset)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned target_cache =
      (devinfo->gen >= 7 ? GEN7_SFID_DATAPORT_DATA_CACHE :
       devinfo->gen >= 6 ? GEN6_SFID_DATAPORT_RENDER_CACHE :
       BRW_DATAPORT_READ_TARGET_RENDER_CACHE);
   uint32_t msg_type;

   if (devinfo->gen >= 6)
      offset /= 16;

   mrf = retype(mrf, BRW_REGISTER_TYPE_UD);

   const unsigned mlen = 1 + num_regs;

   /* Set up the message header.  This is g0, with g0.2 filled with
    * the offset.  We don't want to leave our offset around in g0 or
    * it'll screw up texture samples, so set it up inside the message
    * reg.
    */
   {
      brw_push_insn_state(p);
      brw_set_default_exec_size(p, BRW_EXECUTE_8);
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);
      brw_set_default_compression_control(p, BRW_COMPRESSION_NONE);

      brw_MOV(p, mrf, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));

      /* set message header global offset field (reg 0, element 2) */
      brw_MOV(p,
	      retype(brw_vec1_reg(BRW_MESSAGE_REGISTER_FILE,
				  mrf.nr,
				  2), BRW_REGISTER_TYPE_UD),
	      brw_imm_ud(offset));

      brw_pop_insn_state(p);
   }

   {
      struct brw_reg dest;
      brw_inst *insn = next_insn(p, BRW_OPCODE_SEND);
      int send_commit_msg;
      struct brw_reg src_header = retype(brw_vec8_grf(0, 0),
					 BRW_REGISTER_TYPE_UW);

      brw_inst_set_compression(devinfo, insn, false);

      if (brw_inst_exec_size(devinfo, insn) >= 16)
	 src_header = vec16(src_header);

      assert(brw_inst_pred_control(devinfo, insn) == BRW_PREDICATE_NONE);
      if (devinfo->gen < 6)
         brw_inst_set_base_mrf(devinfo, insn, mrf.nr);

      /* Until gen6, writes followed by reads from the same location
       * are not guaranteed to be ordered unless write_commit is set.
       * If set, then a no-op write is issued to the destination
       * register to set a dependency, and a read from the destination
       * can be used to ensure the ordering.
       *
       * For gen6, only writes between different threads need ordering
       * protection.  Our use of DP writes is all about register
       * spilling within a thread.
       */
      if (devinfo->gen >= 6) {
	 dest = retype(vec16(brw_null_reg()), BRW_REGISTER_TYPE_UW);
	 send_commit_msg = 0;
      } else {
	 dest = src_header;
	 send_commit_msg = 1;
      }

      brw_set_dest(p, insn, dest);
      if (devinfo->gen >= 6) {
	 brw_set_src0(p, insn, mrf);
      } else {
	 brw_set_src0(p, insn, brw_null_reg());
      }

      if (devinfo->gen >= 6)
	 msg_type = GEN6_DATAPORT_WRITE_MESSAGE_OWORD_BLOCK_WRITE;
      else
	 msg_type = BRW_DATAPORT_WRITE_MESSAGE_OWORD_BLOCK_WRITE;

      brw_set_dp_write_message(p,
			       insn,
                               brw_scratch_surface_idx(p),
			       BRW_DATAPORT_OWORD_BLOCK_DWORDS(num_regs * 8),
			       msg_type,
                               target_cache,
			       mlen,
			       true, /* header_present */
			       0, /* not a render target */
			       send_commit_msg, /* response_length */
			       0, /* eot */
			       send_commit_msg);
   }
}


/**
 * Read a block of owords (half a GRF each) from the scratch buffer
 * using a constant index per channel.
 *
 * Offset must be aligned to oword size (16 bytes).  Used for register
 * spilling.
 */
void
brw_oword_block_read_scratch(struct brw_codegen *p,
			     struct brw_reg dest,
			     struct brw_reg mrf,
			     int num_regs,
			     unsigned offset)
{
   const struct gen_device_info *devinfo = p->devinfo;

   if (devinfo->gen >= 6)
      offset /= 16;

   if (p->devinfo->gen >= 7) {
      /* On gen 7 and above, we no longer have message registers and we can
       * send from any register we want.  By using the destination register
       * for the message, we guarantee that the implied message write won't
       * accidentally overwrite anything.  This has been a problem because
       * the MRF registers and source for the final FB write are both fixed
       * and may overlap.
       */
      mrf = retype(dest, BRW_REGISTER_TYPE_UD);
   } else {
      mrf = retype(mrf, BRW_REGISTER_TYPE_UD);
   }
   dest = retype(dest, BRW_REGISTER_TYPE_UW);

   const unsigned rlen = num_regs;
   const unsigned target_cache =
      (devinfo->gen >= 7 ? GEN7_SFID_DATAPORT_DATA_CACHE :
       devinfo->gen >= 6 ? GEN6_SFID_DATAPORT_RENDER_CACHE :
       BRW_DATAPORT_READ_TARGET_RENDER_CACHE);

   {
      brw_push_insn_state(p);
      brw_set_default_exec_size(p, BRW_EXECUTE_8);
      brw_set_default_compression_control(p, BRW_COMPRESSION_NONE);
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);

      brw_MOV(p, mrf, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));

      /* set message header global offset field (reg 0, element 2) */
      brw_MOV(p, get_element_ud(mrf, 2), brw_imm_ud(offset));

      brw_pop_insn_state(p);
   }

   {
      brw_inst *insn = next_insn(p, BRW_OPCODE_SEND);

      assert(brw_inst_pred_control(devinfo, insn) == 0);
      brw_inst_set_compression(devinfo, insn, false);

      brw_set_dest(p, insn, dest);	/* UW? */
      if (devinfo->gen >= 6) {
	 brw_set_src0(p, insn, mrf);
      } else {
	 brw_set_src0(p, insn, brw_null_reg());
         brw_inst_set_base_mrf(devinfo, insn, mrf.nr);
      }

      brw_set_dp_read_message(p,
			      insn,
                              brw_scratch_surface_idx(p),
			      BRW_DATAPORT_OWORD_BLOCK_DWORDS(num_regs * 8),
			      BRW_DATAPORT_READ_MESSAGE_OWORD_BLOCK_READ, /* msg_type */
			      target_cache,
			      1, /* msg_length */
                              true, /* header_present */
			      rlen);
   }
}

void
gen7_block_read_scratch(struct brw_codegen *p,
                        struct brw_reg dest,
                        int num_regs,
                        unsigned offset)
{
   brw_inst *insn = next_insn(p, BRW_OPCODE_SEND);
   assert(brw_inst_pred_control(p->devinfo, insn) == BRW_PREDICATE_NONE);

   brw_set_dest(p, insn, retype(dest, BRW_REGISTER_TYPE_UW));

   /* The HW requires that the header is present; this is to get the g0.5
    * scratch offset.
    */
   brw_set_src0(p, insn, brw_vec8_grf(0, 0));

   /* According to the docs, offset is "A 12-bit HWord offset into the memory
    * Immediate Memory buffer as specified by binding table 0xFF."  An HWORD
    * is 32 bytes, which happens to be the size of a register.
    */
   offset /= REG_SIZE;
   assert(offset < (1 << 12));

   gen7_set_dp_scratch_message(p, insn,
                               false, /* scratch read */
                               false, /* OWords */
                               false, /* invalidate after read */
                               num_regs,
                               offset,
                               1,        /* mlen: just g0 */
                               num_regs, /* rlen */
                               true);    /* header present */
}

/**
 * Read float[4] vectors from the data port constant cache.
 * Location (in buffer) should be a multiple of 16.
 * Used for fetching shader constants.
 */
void brw_oword_block_read(struct brw_codegen *p,
			  struct brw_reg dest,
			  struct brw_reg mrf,
			  uint32_t offset,
			  uint32_t bind_table_index)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned target_cache =
      (devinfo->gen >= 6 ? GEN6_SFID_DATAPORT_CONSTANT_CACHE :
       BRW_DATAPORT_READ_TARGET_DATA_CACHE);
   const unsigned exec_size = 1 << brw_inst_exec_size(devinfo, p->current);

   /* On newer hardware, offset is in units of owords. */
   if (devinfo->gen >= 6)
      offset /= 16;

   mrf = retype(mrf, BRW_REGISTER_TYPE_UD);

   brw_push_insn_state(p);
   brw_set_default_predicate_control(p, BRW_PREDICATE_NONE);
   brw_set_default_compression_control(p, BRW_COMPRESSION_NONE);
   brw_set_default_mask_control(p, BRW_MASK_DISABLE);

   brw_push_insn_state(p);
   brw_set_default_exec_size(p, BRW_EXECUTE_8);
   brw_MOV(p, mrf, retype(brw_vec8_grf(0, 0), BRW_REGISTER_TYPE_UD));

   /* set message header global offset field (reg 0, element 2) */
   brw_MOV(p,
	   retype(brw_vec1_reg(BRW_MESSAGE_REGISTER_FILE,
			       mrf.nr,
			       2), BRW_REGISTER_TYPE_UD),
	   brw_imm_ud(offset));
   brw_pop_insn_state(p);

   brw_inst *insn = next_insn(p, BRW_OPCODE_SEND);

   /* cast dest to a uword[8] vector */
   dest = retype(vec8(dest), BRW_REGISTER_TYPE_UW);

   brw_set_dest(p, insn, dest);
   if (devinfo->gen >= 6) {
      brw_set_src0(p, insn, mrf);
   } else {
      brw_set_src0(p, insn, brw_null_reg());
      brw_inst_set_base_mrf(devinfo, insn, mrf.nr);
   }

   brw_set_dp_read_message(p, insn, bind_table_index,
                           BRW_DATAPORT_OWORD_BLOCK_DWORDS(exec_size),
			   BRW_DATAPORT_READ_MESSAGE_OWORD_BLOCK_READ,
			   target_cache,
			   1, /* msg_length */
                           true, /* header_present */
			   DIV_ROUND_UP(exec_size, 8)); /* response_length */

   brw_pop_insn_state(p);
}


void brw_fb_WRITE(struct brw_codegen *p,
                  struct brw_reg payload,
                  struct brw_reg implied_header,
                  unsigned msg_control,
                  unsigned binding_table_index,
                  unsigned msg_length,
                  unsigned response_length,
                  bool eot,
                  bool last_render_target,
                  bool header_present)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned target_cache =
      (devinfo->gen >= 6 ? GEN6_SFID_DATAPORT_RENDER_CACHE :
       BRW_DATAPORT_READ_TARGET_RENDER_CACHE);
   brw_inst *insn;
   unsigned msg_type;
   struct brw_reg dest, src0;

   if (brw_inst_exec_size(devinfo, p->current) >= BRW_EXECUTE_16)
      dest = retype(vec16(brw_null_reg()), BRW_REGISTER_TYPE_UW);
   else
      dest = retype(vec8(brw_null_reg()), BRW_REGISTER_TYPE_UW);

   if (devinfo->gen >= 6) {
      insn = next_insn(p, BRW_OPCODE_SENDC);
   } else {
      insn = next_insn(p, BRW_OPCODE_SEND);
   }
   brw_inst_set_compression(devinfo, insn, false);

   if (devinfo->gen >= 6) {
      /* headerless version, just submit color payload */
      src0 = payload;

      msg_type = GEN6_DATAPORT_WRITE_MESSAGE_RENDER_TARGET_WRITE;
   } else {
      assert(payload.file == BRW_MESSAGE_REGISTER_FILE);
      brw_inst_set_base_mrf(devinfo, insn, payload.nr);
      src0 = implied_header;

      msg_type = BRW_DATAPORT_WRITE_MESSAGE_RENDER_TARGET_WRITE;
   }

   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_dp_write_message(p,
			    insn,
			    binding_table_index,
			    msg_control,
			    msg_type,
                            target_cache,
			    msg_length,
			    header_present,
			    last_render_target,
			    response_length,
			    eot,
			    0 /* send_commit_msg */);
}

brw_inst *
gen9_fb_READ(struct brw_codegen *p,
             struct brw_reg dst,
             struct brw_reg payload,
             unsigned binding_table_index,
             unsigned msg_length,
             unsigned response_length,
             bool per_sample)
{
   const struct gen_device_info *devinfo = p->devinfo;
   assert(devinfo->gen >= 9);
   const unsigned msg_subtype =
      brw_inst_exec_size(devinfo, p->current) == BRW_EXECUTE_16 ? 0 : 1;
   brw_inst *insn = next_insn(p, BRW_OPCODE_SENDC);

   brw_set_dest(p, insn, dst);
   brw_set_src0(p, insn, payload);
   brw_set_dp_read_message(p, insn, binding_table_index,
                           per_sample << 5 | msg_subtype,
                           GEN9_DATAPORT_RC_RENDER_TARGET_READ,
                           GEN6_SFID_DATAPORT_RENDER_CACHE,
                           msg_length, true /* header_present */,
                           response_length);
   brw_inst_set_rt_slot_group(devinfo, insn,
                              brw_inst_qtr_control(devinfo, p->current) / 2);

   return insn;
}

/**
 * Texture sample instruction.
 * Note: the msg_type plus msg_length values determine exactly what kind
 * of sampling operation is performed.  See volume 4, page 161 of docs.
 */
void brw_SAMPLE(struct brw_codegen *p,
		struct brw_reg dest,
		unsigned msg_reg_nr,
		struct brw_reg src0,
		unsigned binding_table_index,
		unsigned sampler,
		unsigned msg_type,
		unsigned response_length,
		unsigned msg_length,
		unsigned header_present,
		unsigned simd_mode,
		unsigned return_format)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   if (msg_reg_nr != -1)
      gen6_resolve_implied_move(p, &src0, msg_reg_nr);

   insn = next_insn(p, BRW_OPCODE_SEND);
   brw_inst_set_pred_control(devinfo, insn, BRW_PREDICATE_NONE); /* XXX */

   /* From the 965 PRM (volume 4, part 1, section 14.2.41):
    *
    *    "Instruction compression is not allowed for this instruction (that
    *     is, send). The hardware behavior is undefined if this instruction is
    *     set as compressed. However, compress control can be set to "SecHalf"
    *     to affect the EMask generation."
    *
    * No similar wording is found in later PRMs, but there are examples
    * utilizing send with SecHalf.  More importantly, SIMD8 sampler messages
    * are allowed in SIMD16 mode and they could not work without SecHalf.  For
    * these reasons, we allow BRW_COMPRESSION_2NDHALF here.
    */
   brw_inst_set_compression(devinfo, insn, false);

   if (devinfo->gen < 6)
      brw_inst_set_base_mrf(devinfo, insn, msg_reg_nr);

   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_sampler_message(p, insn,
                           binding_table_index,
                           sampler,
                           msg_type,
                           response_length,
                           msg_length,
                           header_present,
                           simd_mode,
                           return_format);
}

/* Adjust the message header's sampler state pointer to
 * select the correct group of 16 samplers.
 */
void brw_adjust_sampler_state_pointer(struct brw_codegen *p,
                                      struct brw_reg header,
                                      struct brw_reg sampler_index)
{
   /* The "Sampler Index" field can only store values between 0 and 15.
    * However, we can add an offset to the "Sampler State Pointer"
    * field, effectively selecting a different set of 16 samplers.
    *
    * The "Sampler State Pointer" needs to be aligned to a 32-byte
    * offset, and each sampler state is only 16-bytes, so we can't
    * exclusively use the offset - we have to use both.
    */

   const struct gen_device_info *devinfo = p->devinfo;

   if (sampler_index.file == BRW_IMMEDIATE_VALUE) {
      const int sampler_state_size = 16; /* 16 bytes */
      uint32_t sampler = sampler_index.ud;

      if (sampler >= 16) {
         assert(devinfo->is_haswell || devinfo->gen >= 8);
         brw_ADD(p,
                 get_element_ud(header, 3),
                 get_element_ud(brw_vec8_grf(0, 0), 3),
                 brw_imm_ud(16 * (sampler / 16) * sampler_state_size));
      }
   } else {
      /* Non-const sampler array indexing case */
      if (devinfo->gen < 8 && !devinfo->is_haswell) {
         return;
      }

      struct brw_reg temp = get_element_ud(header, 3);

      brw_AND(p, temp, get_element_ud(sampler_index, 0), brw_imm_ud(0x0f0));
      brw_SHL(p, temp, temp, brw_imm_ud(4));
      brw_ADD(p,
              get_element_ud(header, 3),
              get_element_ud(brw_vec8_grf(0, 0), 3),
              temp);
   }
}

/* All these variables are pretty confusing - we might be better off
 * using bitmasks and macros for this, in the old style.  Or perhaps
 * just having the caller instantiate the fields in dword3 itself.
 */
void brw_urb_WRITE(struct brw_codegen *p,
		   struct brw_reg dest,
		   unsigned msg_reg_nr,
		   struct brw_reg src0,
                   enum brw_urb_write_flags flags,
		   unsigned msg_length,
		   unsigned response_length,
		   unsigned offset,
		   unsigned swizzle)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   gen6_resolve_implied_move(p, &src0, msg_reg_nr);

   if (devinfo->gen >= 7 && !(flags & BRW_URB_WRITE_USE_CHANNEL_MASKS)) {
      /* Enable Channel Masks in the URB_WRITE_HWORD message header */
      brw_push_insn_state(p);
      brw_set_default_access_mode(p, BRW_ALIGN_1);
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);
      brw_OR(p, retype(brw_vec1_reg(BRW_MESSAGE_REGISTER_FILE, msg_reg_nr, 5),
		       BRW_REGISTER_TYPE_UD),
	        retype(brw_vec1_grf(0, 5), BRW_REGISTER_TYPE_UD),
		brw_imm_ud(0xff00));
      brw_pop_insn_state(p);
   }

   insn = next_insn(p, BRW_OPCODE_SEND);

   assert(msg_length < BRW_MAX_MRF(devinfo->gen));

   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_src1(p, insn, brw_imm_d(0));

   if (devinfo->gen < 6)
      brw_inst_set_base_mrf(devinfo, insn, msg_reg_nr);

   brw_set_urb_message(p,
		       insn,
		       flags,
		       msg_length,
		       response_length,
		       offset,
		       swizzle);
}

struct brw_inst *
brw_send_indirect_message(struct brw_codegen *p,
                          unsigned sfid,
                          struct brw_reg dst,
                          struct brw_reg payload,
                          struct brw_reg desc)
{
   const struct gen_device_info *devinfo = p->devinfo;
   struct brw_inst *send;
   int setup;

   dst = retype(dst, BRW_REGISTER_TYPE_UW);

   assert(desc.type == BRW_REGISTER_TYPE_UD);

   /* We hold on to the setup instruction (the SEND in the direct case, the OR
    * in the indirect case) by its index in the instruction store.  The
    * pointer returned by next_insn() may become invalid if emitting the SEND
    * in the indirect case reallocs the store.
    */

   if (desc.file == BRW_IMMEDIATE_VALUE) {
      setup = p->nr_insn;
      send = next_insn(p, BRW_OPCODE_SEND);
      brw_set_src1(p, send, desc);

   } else {
      struct brw_reg addr = retype(brw_address_reg(0), BRW_REGISTER_TYPE_UD);

      brw_push_insn_state(p);
      brw_set_default_access_mode(p, BRW_ALIGN_1);
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);
      brw_set_default_predicate_control(p, BRW_PREDICATE_NONE);

      /* Load the indirect descriptor to an address register using OR so the
       * caller can specify additional descriptor bits with the usual
       * brw_set_*_message() helper functions.
       */
      setup = p->nr_insn;
      brw_OR(p, addr, desc, brw_imm_ud(0));

      brw_pop_insn_state(p);

      send = next_insn(p, BRW_OPCODE_SEND);
      brw_set_src1(p, send, addr);
   }

   if (dst.width < BRW_EXECUTE_8)
      brw_inst_set_exec_size(devinfo, send, dst.width);

   brw_set_dest(p, send, dst);
   brw_set_src0(p, send, retype(payload, BRW_REGISTER_TYPE_UD));
   brw_inst_set_sfid(devinfo, send, sfid);

   return &p->store[setup];
}

static struct brw_inst *
brw_send_indirect_surface_message(struct brw_codegen *p,
                                  unsigned sfid,
                                  struct brw_reg dst,
                                  struct brw_reg payload,
                                  struct brw_reg surface,
                                  unsigned message_len,
                                  unsigned response_len,
                                  bool header_present)
{
   const struct gen_device_info *devinfo = p->devinfo;
   struct brw_inst *insn;

   if (surface.file != BRW_IMMEDIATE_VALUE) {
      struct brw_reg addr = retype(brw_address_reg(0), BRW_REGISTER_TYPE_UD);

      brw_push_insn_state(p);
      brw_set_default_access_mode(p, BRW_ALIGN_1);
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);
      brw_set_default_predicate_control(p, BRW_PREDICATE_NONE);

      /* Mask out invalid bits from the surface index to avoid hangs e.g. when
       * some surface array is accessed out of bounds.
       */
      insn = brw_AND(p, addr,
                     suboffset(vec1(retype(surface, BRW_REGISTER_TYPE_UD)),
                               BRW_GET_SWZ(surface.swizzle, 0)),
                     brw_imm_ud(0xff));

      brw_pop_insn_state(p);

      surface = addr;
   }

   insn = brw_send_indirect_message(p, sfid, dst, payload, surface);
   brw_inst_set_mlen(devinfo, insn, message_len);
   brw_inst_set_rlen(devinfo, insn, response_len);
   brw_inst_set_header_present(devinfo, insn, header_present);

   return insn;
}

static bool
while_jumps_before_offset(const struct gen_device_info *devinfo,
                          brw_inst *insn, int while_offset, int start_offset)
{
   int scale = 16 / brw_jump_scale(devinfo);
   int jip = devinfo->gen == 6 ? brw_inst_gen6_jump_count(devinfo, insn)
                               : brw_inst_jip(devinfo, insn);
   assert(jip < 0);
   return while_offset + jip * scale <= start_offset;
}


static int
brw_find_next_block_end(struct brw_codegen *p, int start_offset)
{
   int offset;
   void *store = p->store;
   const struct gen_device_info *devinfo = p->devinfo;

   int depth = 0;

   for (offset = next_offset(devinfo, store, start_offset);
        offset < p->next_insn_offset;
        offset = next_offset(devinfo, store, offset)) {
      brw_inst *insn = store + offset;

      switch (brw_inst_opcode(devinfo, insn)) {
      case BRW_OPCODE_IF:
         depth++;
         break;
      case BRW_OPCODE_ENDIF:
         if (depth == 0)
            return offset;
         depth--;
         break;
      case BRW_OPCODE_WHILE:
         /* If the while doesn't jump before our instruction, it's the end
          * of a sibling do...while loop.  Ignore it.
          */
         if (!while_jumps_before_offset(devinfo, insn, offset, start_offset))
            continue;
         /* fallthrough */
      case BRW_OPCODE_ELSE:
      case BRW_OPCODE_HALT:
         if (depth == 0)
            return offset;
      }
   }

   return 0;
}

/* There is no DO instruction on gen6, so to find the end of the loop
 * we have to see if the loop is jumping back before our start
 * instruction.
 */
static int
brw_find_loop_end(struct brw_codegen *p, int start_offset)
{
   const struct gen_device_info *devinfo = p->devinfo;
   int offset;
   void *store = p->store;

   assert(devinfo->gen >= 6);

   /* Always start after the instruction (such as a WHILE) we're trying to fix
    * up.
    */
   for (offset = next_offset(devinfo, store, start_offset);
        offset < p->next_insn_offset;
        offset = next_offset(devinfo, store, offset)) {
      brw_inst *insn = store + offset;

      if (brw_inst_opcode(devinfo, insn) == BRW_OPCODE_WHILE) {
	 if (while_jumps_before_offset(devinfo, insn, offset, start_offset))
	    return offset;
      }
   }
   assert(!"not reached");
   return start_offset;
}

/* After program generation, go back and update the UIP and JIP of
 * BREAK, CONT, and HALT instructions to their correct locations.
 */
void
brw_set_uip_jip(struct brw_codegen *p, int start_offset)
{
   const struct gen_device_info *devinfo = p->devinfo;
   int offset;
   int br = brw_jump_scale(devinfo);
   int scale = 16 / br;
   void *store = p->store;

   if (devinfo->gen < 6)
      return;

   for (offset = start_offset; offset < p->next_insn_offset; offset += 16) {
      brw_inst *insn = store + offset;
      assert(brw_inst_cmpt_control(devinfo, insn) == 0);

      int block_end_offset = brw_find_next_block_end(p, offset);
      switch (brw_inst_opcode(devinfo, insn)) {
      case BRW_OPCODE_BREAK:
         assert(block_end_offset != 0);
         brw_inst_set_jip(devinfo, insn, (block_end_offset - offset) / scale);
	 /* Gen7 UIP points to WHILE; Gen6 points just after it */
         brw_inst_set_uip(devinfo, insn,
	    (brw_find_loop_end(p, offset) - offset +
             (devinfo->gen == 6 ? 16 : 0)) / scale);
	 break;
      case BRW_OPCODE_CONTINUE:
         assert(block_end_offset != 0);
         brw_inst_set_jip(devinfo, insn, (block_end_offset - offset) / scale);
         brw_inst_set_uip(devinfo, insn,
            (brw_find_loop_end(p, offset) - offset) / scale);

         assert(brw_inst_uip(devinfo, insn) != 0);
         assert(brw_inst_jip(devinfo, insn) != 0);
	 break;

      case BRW_OPCODE_ENDIF: {
         int32_t jump = (block_end_offset == 0) ?
                        1 * br : (block_end_offset - offset) / scale;
         if (devinfo->gen >= 7)
            brw_inst_set_jip(devinfo, insn, jump);
         else
            brw_inst_set_gen6_jump_count(devinfo, insn, jump);
	 break;
      }

      case BRW_OPCODE_HALT:
	 /* From the Sandy Bridge PRM (volume 4, part 2, section 8.3.19):
	  *
	  *    "In case of the halt instruction not inside any conditional
	  *     code block, the value of <JIP> and <UIP> should be the
	  *     same. In case of the halt instruction inside conditional code
	  *     block, the <UIP> should be the end of the program, and the
	  *     <JIP> should be end of the most inner conditional code block."
	  *
	  * The uip will have already been set by whoever set up the
	  * instruction.
	  */
	 if (block_end_offset == 0) {
            brw_inst_set_jip(devinfo, insn, brw_inst_uip(devinfo, insn));
	 } else {
            brw_inst_set_jip(devinfo, insn, (block_end_offset - offset) / scale);
	 }
         assert(brw_inst_uip(devinfo, insn) != 0);
         assert(brw_inst_jip(devinfo, insn) != 0);
	 break;
      }
   }
}

void brw_ff_sync(struct brw_codegen *p,
		   struct brw_reg dest,
		   unsigned msg_reg_nr,
		   struct brw_reg src0,
		   bool allocate,
		   unsigned response_length,
		   bool eot)
{
   const struct gen_device_info *devinfo = p->devinfo;
   brw_inst *insn;

   gen6_resolve_implied_move(p, &src0, msg_reg_nr);

   insn = next_insn(p, BRW_OPCODE_SEND);
   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_src1(p, insn, brw_imm_d(0));

   if (devinfo->gen < 6)
      brw_inst_set_base_mrf(devinfo, insn, msg_reg_nr);

   brw_set_ff_sync_message(p,
			   insn,
			   allocate,
			   response_length,
			   eot);
}

/**
 * Emit the SEND instruction necessary to generate stream output data on Gen6
 * (for transform feedback).
 *
 * If send_commit_msg is true, this is the last piece of stream output data
 * from this thread, so send the data as a committed write.  According to the
 * Sandy Bridge PRM (volume 2 part 1, section 4.5.1):
 *
 *   "Prior to End of Thread with a URB_WRITE, the kernel must ensure all
 *   writes are complete by sending the final write as a committed write."
 */
void
brw_svb_write(struct brw_codegen *p,
              struct brw_reg dest,
              unsigned msg_reg_nr,
              struct brw_reg src0,
              unsigned binding_table_index,
              bool   send_commit_msg)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned target_cache =
      (devinfo->gen >= 7 ? GEN7_SFID_DATAPORT_DATA_CACHE :
       devinfo->gen >= 6 ? GEN6_SFID_DATAPORT_RENDER_CACHE :
       BRW_DATAPORT_READ_TARGET_RENDER_CACHE);
   brw_inst *insn;

   gen6_resolve_implied_move(p, &src0, msg_reg_nr);

   insn = next_insn(p, BRW_OPCODE_SEND);
   brw_set_dest(p, insn, dest);
   brw_set_src0(p, insn, src0);
   brw_set_src1(p, insn, brw_imm_d(0));
   brw_set_dp_write_message(p, insn,
                            binding_table_index,
                            0, /* msg_control: ignored */
                            GEN6_DATAPORT_WRITE_MESSAGE_STREAMED_VB_WRITE,
                            target_cache,
                            1, /* msg_length */
                            true, /* header_present */
                            0, /* last_render_target: ignored */
                            send_commit_msg, /* response_length */
                            0, /* end_of_thread */
                            send_commit_msg); /* send_commit_msg */
}

static unsigned
brw_surface_payload_size(struct brw_codegen *p,
                         unsigned num_channels,
                         bool has_simd4x2,
                         bool has_simd16)
{
   if (has_simd4x2 &&
       brw_inst_access_mode(p->devinfo, p->current) == BRW_ALIGN_16)
      return 1;
   else if (has_simd16 &&
            brw_inst_exec_size(p->devinfo, p->current) == BRW_EXECUTE_16)
      return 2 * num_channels;
   else
      return num_channels;
}

static void
brw_set_dp_untyped_atomic_message(struct brw_codegen *p,
                                  brw_inst *insn,
                                  unsigned atomic_op,
                                  bool response_expected)
{
   const struct gen_device_info *devinfo = p->devinfo;
   unsigned msg_control =
      atomic_op | /* Atomic Operation Type: BRW_AOP_* */
      (response_expected ? 1 << 5 : 0); /* Return data expected */

   if (devinfo->gen >= 8 || devinfo->is_haswell) {
      if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
         if (brw_inst_exec_size(devinfo, p->current) != BRW_EXECUTE_16)
            msg_control |= 1 << 4; /* SIMD8 mode */

         brw_inst_set_dp_msg_type(devinfo, insn,
                                  HSW_DATAPORT_DC_PORT1_UNTYPED_ATOMIC_OP);
      } else {
         brw_inst_set_dp_msg_type(devinfo, insn,
            HSW_DATAPORT_DC_PORT1_UNTYPED_ATOMIC_OP_SIMD4X2);
      }
   } else {
      brw_inst_set_dp_msg_type(devinfo, insn,
                               GEN7_DATAPORT_DC_UNTYPED_ATOMIC_OP);

      if (brw_inst_exec_size(devinfo, p->current) != BRW_EXECUTE_16)
         msg_control |= 1 << 4; /* SIMD8 mode */
   }

   brw_inst_set_dp_msg_control(devinfo, insn, msg_control);
}

void
brw_untyped_atomic(struct brw_codegen *p,
                   struct brw_reg dst,
                   struct brw_reg payload,
                   struct brw_reg surface,
                   unsigned atomic_op,
                   unsigned msg_length,
                   bool response_expected)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
                          HSW_SFID_DATAPORT_DATA_CACHE_1 :
                          GEN7_SFID_DATAPORT_DATA_CACHE);
   const bool align1 = brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1;
   /* Mask out unused components -- This is especially important in Align16
    * mode on generations that don't have native support for SIMD4x2 atomics,
    * because unused but enabled components will cause the dataport to perform
    * additional atomic operations on the addresses that happen to be in the
    * uninitialized Y, Z and W coordinates of the payload.
    */
   const unsigned mask = align1 ? WRITEMASK_XYZW : WRITEMASK_X;
   struct brw_inst *insn = brw_send_indirect_surface_message(
      p, sfid, brw_writemask(dst, mask), payload, surface, msg_length,
      brw_surface_payload_size(p, response_expected,
                               devinfo->gen >= 8 || devinfo->is_haswell, true),
      align1);

   brw_set_dp_untyped_atomic_message(
      p, insn, atomic_op, response_expected);
}

static void
brw_set_dp_untyped_surface_read_message(struct brw_codegen *p,
                                        struct brw_inst *insn,
                                        unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   /* Set mask of 32-bit channels to drop. */
   unsigned msg_control = 0xf & (0xf << num_channels);

   if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
      if (brw_inst_exec_size(devinfo, p->current) == BRW_EXECUTE_16)
         msg_control |= 1 << 4; /* SIMD16 mode */
      else
         msg_control |= 2 << 4; /* SIMD8 mode */
   }

   brw_inst_set_dp_msg_type(devinfo, insn,
                            (devinfo->gen >= 8 || devinfo->is_haswell ?
                             HSW_DATAPORT_DC_PORT1_UNTYPED_SURFACE_READ :
                             GEN7_DATAPORT_DC_UNTYPED_SURFACE_READ));
   brw_inst_set_dp_msg_control(devinfo, insn, msg_control);
}

void
brw_untyped_surface_read(struct brw_codegen *p,
                         struct brw_reg dst,
                         struct brw_reg payload,
                         struct brw_reg surface,
                         unsigned msg_length,
                         unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
                          HSW_SFID_DATAPORT_DATA_CACHE_1 :
                          GEN7_SFID_DATAPORT_DATA_CACHE);
   struct brw_inst *insn = brw_send_indirect_surface_message(
      p, sfid, dst, payload, surface, msg_length,
      brw_surface_payload_size(p, num_channels, true, true),
      false);

   brw_set_dp_untyped_surface_read_message(
      p, insn, num_channels);
}

static void
brw_set_dp_untyped_surface_write_message(struct brw_codegen *p,
                                         struct brw_inst *insn,
                                         unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   /* Set mask of 32-bit channels to drop. */
   unsigned msg_control = 0xf & (0xf << num_channels);

   if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
      if (brw_inst_exec_size(devinfo, p->current) == BRW_EXECUTE_16)
         msg_control |= 1 << 4; /* SIMD16 mode */
      else
         msg_control |= 2 << 4; /* SIMD8 mode */
   } else {
      if (devinfo->gen >= 8 || devinfo->is_haswell)
         msg_control |= 0 << 4; /* SIMD4x2 mode */
      else
         msg_control |= 2 << 4; /* SIMD8 mode */
   }

   brw_inst_set_dp_msg_type(devinfo, insn,
                            devinfo->gen >= 8 || devinfo->is_haswell ?
                             HSW_DATAPORT_DC_PORT1_UNTYPED_SURFACE_WRITE :
                             GEN7_DATAPORT_DC_UNTYPED_SURFACE_WRITE);
   brw_inst_set_dp_msg_control(devinfo, insn, msg_control);
}

void
brw_untyped_surface_write(struct brw_codegen *p,
                          struct brw_reg payload,
                          struct brw_reg surface,
                          unsigned msg_length,
                          unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
                          HSW_SFID_DATAPORT_DATA_CACHE_1 :
                          GEN7_SFID_DATAPORT_DATA_CACHE);
   const bool align1 = brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1;
   /* Mask out unused components -- See comment in brw_untyped_atomic(). */
   const unsigned mask = devinfo->gen == 7 && !devinfo->is_haswell && !align1 ?
                          WRITEMASK_X : WRITEMASK_XYZW;
   struct brw_inst *insn = brw_send_indirect_surface_message(
      p, sfid, brw_writemask(brw_null_reg(), mask),
      payload, surface, msg_length, 0, align1);

   brw_set_dp_untyped_surface_write_message(
      p, insn, num_channels);
}

static void
brw_set_dp_typed_atomic_message(struct brw_codegen *p,
                                struct brw_inst *insn,
                                unsigned atomic_op,
                                bool response_expected)
{
   const struct gen_device_info *devinfo = p->devinfo;
   unsigned msg_control =
      atomic_op | /* Atomic Operation Type: BRW_AOP_* */
      (response_expected ? 1 << 5 : 0); /* Return data expected */

   if (devinfo->gen >= 8 || devinfo->is_haswell) {
      if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
         if (brw_inst_qtr_control(devinfo, p->current) % 2 == 1)
            msg_control |= 1 << 4; /* Use high 8 slots of the sample mask */

         brw_inst_set_dp_msg_type(devinfo, insn,
                                  HSW_DATAPORT_DC_PORT1_TYPED_ATOMIC_OP);
      } else {
         brw_inst_set_dp_msg_type(devinfo, insn,
                                  HSW_DATAPORT_DC_PORT1_TYPED_ATOMIC_OP_SIMD4X2);
      }

   } else {
      brw_inst_set_dp_msg_type(devinfo, insn,
                               GEN7_DATAPORT_RC_TYPED_ATOMIC_OP);

      if (brw_inst_qtr_control(devinfo, p->current) % 2 == 1)
         msg_control |= 1 << 4; /* Use high 8 slots of the sample mask */
   }

   brw_inst_set_dp_msg_control(devinfo, insn, msg_control);
}

void
brw_typed_atomic(struct brw_codegen *p,
                 struct brw_reg dst,
                 struct brw_reg payload,
                 struct brw_reg surface,
                 unsigned atomic_op,
                 unsigned msg_length,
                 bool response_expected) {
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
                          HSW_SFID_DATAPORT_DATA_CACHE_1 :
                          GEN6_SFID_DATAPORT_RENDER_CACHE);
   const bool align1 = (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1);
   /* Mask out unused components -- See comment in brw_untyped_atomic(). */
   const unsigned mask = align1 ? WRITEMASK_XYZW : WRITEMASK_X;
   struct brw_inst *insn = brw_send_indirect_surface_message(
      p, sfid, brw_writemask(dst, mask), payload, surface, msg_length,
      brw_surface_payload_size(p, response_expected,
                               devinfo->gen >= 8 || devinfo->is_haswell, false),
      true);

   brw_set_dp_typed_atomic_message(
      p, insn, atomic_op, response_expected);
}

static void
brw_set_dp_typed_surface_read_message(struct brw_codegen *p,
                                      struct brw_inst *insn,
                                      unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   /* Set mask of unused channels. */
   unsigned msg_control = 0xf & (0xf << num_channels);

   if (devinfo->gen >= 8 || devinfo->is_haswell) {
      if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
         if (brw_inst_qtr_control(devinfo, p->current) % 2 == 1)
            msg_control |= 2 << 4; /* Use high 8 slots of the sample mask */
         else
            msg_control |= 1 << 4; /* Use low 8 slots of the sample mask */
      }

      brw_inst_set_dp_msg_type(devinfo, insn,
                               HSW_DATAPORT_DC_PORT1_TYPED_SURFACE_READ);
   } else {
      if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
         if (brw_inst_qtr_control(devinfo, p->current) % 2 == 1)
            msg_control |= 1 << 5; /* Use high 8 slots of the sample mask */
      }

      brw_inst_set_dp_msg_type(devinfo, insn,
                               GEN7_DATAPORT_RC_TYPED_SURFACE_READ);
   }

   brw_inst_set_dp_msg_control(devinfo, insn, msg_control);
}

void
brw_typed_surface_read(struct brw_codegen *p,
                       struct brw_reg dst,
                       struct brw_reg payload,
                       struct brw_reg surface,
                       unsigned msg_length,
                       unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
                          HSW_SFID_DATAPORT_DATA_CACHE_1 :
                          GEN6_SFID_DATAPORT_RENDER_CACHE);
   struct brw_inst *insn = brw_send_indirect_surface_message(
      p, sfid, dst, payload, surface, msg_length,
      brw_surface_payload_size(p, num_channels,
                               devinfo->gen >= 8 || devinfo->is_haswell, false),
      true);

   brw_set_dp_typed_surface_read_message(
      p, insn, num_channels);
}

static void
brw_set_dp_typed_surface_write_message(struct brw_codegen *p,
                                       struct brw_inst *insn,
                                       unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   /* Set mask of unused channels. */
   unsigned msg_control = 0xf & (0xf << num_channels);

   if (devinfo->gen >= 8 || devinfo->is_haswell) {
      if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
         if (brw_inst_qtr_control(devinfo, p->current) % 2 == 1)
            msg_control |= 2 << 4; /* Use high 8 slots of the sample mask */
         else
            msg_control |= 1 << 4; /* Use low 8 slots of the sample mask */
      }

      brw_inst_set_dp_msg_type(devinfo, insn,
                               HSW_DATAPORT_DC_PORT1_TYPED_SURFACE_WRITE);

   } else {
      if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
         if (brw_inst_qtr_control(devinfo, p->current) % 2 == 1)
            msg_control |= 1 << 5; /* Use high 8 slots of the sample mask */
      }

      brw_inst_set_dp_msg_type(devinfo, insn,
                               GEN7_DATAPORT_RC_TYPED_SURFACE_WRITE);
   }

   brw_inst_set_dp_msg_control(devinfo, insn, msg_control);
}

void
brw_typed_surface_write(struct brw_codegen *p,
                        struct brw_reg payload,
                        struct brw_reg surface,
                        unsigned msg_length,
                        unsigned num_channels)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned sfid = (devinfo->gen >= 8 || devinfo->is_haswell ?
                          HSW_SFID_DATAPORT_DATA_CACHE_1 :
                          GEN6_SFID_DATAPORT_RENDER_CACHE);
   const bool align1 = (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1);
   /* Mask out unused components -- See comment in brw_untyped_atomic(). */
   const unsigned mask = (devinfo->gen == 7 && !devinfo->is_haswell && !align1 ?
                          WRITEMASK_X : WRITEMASK_XYZW);
   struct brw_inst *insn = brw_send_indirect_surface_message(
      p, sfid, brw_writemask(brw_null_reg(), mask),
      payload, surface, msg_length, 0, true);

   brw_set_dp_typed_surface_write_message(
      p, insn, num_channels);
}

static void
brw_set_memory_fence_message(struct brw_codegen *p,
                             struct brw_inst *insn,
                             enum brw_message_target sfid,
                             bool commit_enable)
{
   const struct gen_device_info *devinfo = p->devinfo;

   brw_set_message_descriptor(p, insn, sfid,
                              1 /* message length */,
                              (commit_enable ? 1 : 0) /* response length */,
                              true /* header present */,
                              false);

   switch (sfid) {
   case GEN6_SFID_DATAPORT_RENDER_CACHE:
      brw_inst_set_dp_msg_type(devinfo, insn, GEN7_DATAPORT_RC_MEMORY_FENCE);
      break;
   case GEN7_SFID_DATAPORT_DATA_CACHE:
      brw_inst_set_dp_msg_type(devinfo, insn, GEN7_DATAPORT_DC_MEMORY_FENCE);
      break;
   default:
      unreachable("Not reached");
   }

   if (commit_enable)
      brw_inst_set_dp_msg_control(devinfo, insn, 1 << 5);
}

void
brw_memory_fence(struct brw_codegen *p,
                 struct brw_reg dst)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const bool commit_enable = devinfo->gen == 7 && !devinfo->is_haswell;
   struct brw_inst *insn;

   brw_push_insn_state(p);
   brw_set_default_mask_control(p, BRW_MASK_DISABLE);
   brw_set_default_exec_size(p, BRW_EXECUTE_1);
   dst = vec1(dst);

   /* Set dst as destination for dependency tracking, the MEMORY_FENCE
    * message doesn't write anything back.
    */
   insn = next_insn(p, BRW_OPCODE_SEND);
   dst = retype(dst, BRW_REGISTER_TYPE_UW);
   brw_set_dest(p, insn, dst);
   brw_set_src0(p, insn, dst);
   brw_set_memory_fence_message(p, insn, GEN7_SFID_DATAPORT_DATA_CACHE,
                                commit_enable);

   if (devinfo->gen == 7 && !devinfo->is_haswell) {
      /* IVB does typed surface access through the render cache, so we need to
       * flush it too.  Use a different register so both flushes can be
       * pipelined by the hardware.
       */
      insn = next_insn(p, BRW_OPCODE_SEND);
      brw_set_dest(p, insn, offset(dst, 1));
      brw_set_src0(p, insn, offset(dst, 1));
      brw_set_memory_fence_message(p, insn, GEN6_SFID_DATAPORT_RENDER_CACHE,
                                   commit_enable);

      /* Now write the response of the second message into the response of the
       * first to trigger a pipeline stall -- This way future render and data
       * cache messages will be properly ordered with respect to past data and
       * render cache messages.
       */
      brw_MOV(p, dst, offset(dst, 1));
   }

   brw_pop_insn_state(p);
}

void
brw_pixel_interpolator_query(struct brw_codegen *p,
                             struct brw_reg dest,
                             struct brw_reg mrf,
                             bool noperspective,
                             unsigned mode,
                             struct brw_reg data,
                             unsigned msg_length,
                             unsigned response_length)
{
   const struct gen_device_info *devinfo = p->devinfo;
   struct brw_inst *insn;
   const uint16_t exec_size = brw_inst_exec_size(devinfo, p->current);

   /* brw_send_indirect_message will automatically use a direct send message
    * if data is actually immediate.
    */
   insn = brw_send_indirect_message(p,
                                    GEN7_SFID_PIXEL_INTERPOLATOR,
                                    dest,
                                    mrf,
                                    vec1(data));
   brw_inst_set_mlen(devinfo, insn, msg_length);
   brw_inst_set_rlen(devinfo, insn, response_length);

   brw_inst_set_pi_simd_mode(devinfo, insn, exec_size == BRW_EXECUTE_16);
   brw_inst_set_pi_slot_group(devinfo, insn, 0); /* zero unless 32/64px dispatch */
   brw_inst_set_pi_nopersp(devinfo, insn, noperspective);
   brw_inst_set_pi_message_type(devinfo, insn, mode);
}

void
brw_find_live_channel(struct brw_codegen *p, struct brw_reg dst,
                      struct brw_reg mask)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const unsigned exec_size = 1 << brw_inst_exec_size(devinfo, p->current);
   const unsigned qtr_control = brw_inst_qtr_control(devinfo, p->current);
   brw_inst *inst;

   assert(devinfo->gen >= 7);
   assert(mask.type == BRW_REGISTER_TYPE_UD);

   brw_push_insn_state(p);

   if (brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1) {
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);

      if (devinfo->gen >= 8) {
         /* Getting the first active channel index is easy on Gen8: Just find
          * the first bit set in the execution mask.  The register exists on
          * HSW already but it reads back as all ones when the current
          * instruction has execution masking disabled, so it's kind of
          * useless.
          */
         struct brw_reg exec_mask =
            retype(brw_mask_reg(0), BRW_REGISTER_TYPE_UD);

         if (mask.file != BRW_IMMEDIATE_VALUE || mask.ud != 0xffffffff) {
            /* Unfortunately, ce0 does not take into account the thread
             * dispatch mask, which may be a problem in cases where it's not
             * tightly packed (i.e. it doesn't have the form '2^n - 1' for
             * some n).  Combine ce0 with the given dispatch (or vector) mask
             * to mask off those channels which were never dispatched by the
             * hardware.
             */
            brw_SHR(p, vec1(dst), mask, brw_imm_ud(qtr_control * 8));
            brw_AND(p, vec1(dst), exec_mask, vec1(dst));
            exec_mask = vec1(dst);
         }

         /* Quarter control has the effect of magically shifting the value of
          * ce0 so you'll get the first active channel relative to the
          * specified quarter control as result.
          */
         inst = brw_FBL(p, vec1(dst), exec_mask);
      } else {
         const struct brw_reg flag = brw_flag_reg(1, 0);

         brw_MOV(p, retype(flag, BRW_REGISTER_TYPE_UD), brw_imm_ud(0));

         /* Run enough instructions returning zero with execution masking and
          * a conditional modifier enabled in order to get the full execution
          * mask in f1.0.  We could use a single 32-wide move here if it
          * weren't because of the hardware bug that causes channel enables to
          * be applied incorrectly to the second half of 32-wide instructions
          * on Gen7.
          */
         const unsigned lower_size = MIN2(16, exec_size);
         for (unsigned i = 0; i < exec_size / lower_size; i++) {
            inst = brw_MOV(p, retype(brw_null_reg(), BRW_REGISTER_TYPE_UW),
                           brw_imm_uw(0));
            brw_inst_set_mask_control(devinfo, inst, BRW_MASK_ENABLE);
            brw_inst_set_group(devinfo, inst, lower_size * i + 8 * qtr_control);
            brw_inst_set_cond_modifier(devinfo, inst, BRW_CONDITIONAL_Z);
            brw_inst_set_flag_reg_nr(devinfo, inst, 1);
            brw_inst_set_exec_size(devinfo, inst, cvt(lower_size) - 1);
         }

         /* Find the first bit set in the exec_size-wide portion of the flag
          * register that was updated by the last sequence of MOV
          * instructions.
          */
         const enum brw_reg_type type = brw_int_type(exec_size / 8, false);
         brw_FBL(p, vec1(dst), byte_offset(retype(flag, type), qtr_control));
      }
   } else {
      brw_set_default_mask_control(p, BRW_MASK_DISABLE);

      if (devinfo->gen >= 8 &&
          mask.file == BRW_IMMEDIATE_VALUE && mask.ud == 0xffffffff) {
         /* In SIMD4x2 mode the first active channel index is just the
          * negation of the first bit of the mask register.  Note that ce0
          * doesn't take into account the dispatch mask, so the Gen7 path
          * should be used instead unless you have the guarantee that the
          * dispatch mask is tightly packed (i.e. it has the form '2^n - 1'
          * for some n).
          */
         inst = brw_AND(p, brw_writemask(dst, WRITEMASK_X),
                        negate(retype(brw_mask_reg(0), BRW_REGISTER_TYPE_UD)),
                        brw_imm_ud(1));

      } else {
         /* Overwrite the destination without and with execution masking to
          * find out which of the channels is active.
          */
         brw_push_insn_state(p);
         brw_set_default_exec_size(p, BRW_EXECUTE_4);
         brw_MOV(p, brw_writemask(vec4(dst), WRITEMASK_X),
                 brw_imm_ud(1));

         inst = brw_MOV(p, brw_writemask(vec4(dst), WRITEMASK_X),
                        brw_imm_ud(0));
         brw_pop_insn_state(p);
         brw_inst_set_mask_control(devinfo, inst, BRW_MASK_ENABLE);
      }
   }

   brw_pop_insn_state(p);
}

void
brw_broadcast(struct brw_codegen *p,
              struct brw_reg dst,
              struct brw_reg src,
              struct brw_reg idx)
{
   const struct gen_device_info *devinfo = p->devinfo;
   const bool align1 = brw_inst_access_mode(devinfo, p->current) == BRW_ALIGN_1;
   brw_inst *inst;

   brw_push_insn_state(p);
   brw_set_default_mask_control(p, BRW_MASK_DISABLE);
   brw_set_default_exec_size(p, align1 ? BRW_EXECUTE_1 : BRW_EXECUTE_4);

   assert(src.file == BRW_GENERAL_REGISTER_FILE &&
          src.address_mode == BRW_ADDRESS_DIRECT);

   if ((src.vstride == 0 && (src.hstride == 0 || !align1)) ||
       idx.file == BRW_IMMEDIATE_VALUE) {
      /* Trivial, the source is already uniform or the index is a constant.
       * We will typically not get here if the optimizer is doing its job, but
       * asserting would be mean.
       */
      const unsigned i = idx.file == BRW_IMMEDIATE_VALUE ? idx.ud : 0;
      brw_MOV(p, dst,
              (align1 ? stride(suboffset(src, i), 0, 1, 0) :
               stride(suboffset(src, 4 * i), 0, 4, 1)));
   } else {
      if (align1) {
         const struct brw_reg addr =
            retype(brw_address_reg(0), BRW_REGISTER_TYPE_UD);
         const unsigned offset = src.nr * REG_SIZE + src.subnr;
         /* Limit in bytes of the signed indirect addressing immediate. */
         const unsigned limit = 512;

         brw_push_insn_state(p);
         brw_set_default_mask_control(p, BRW_MASK_DISABLE);
         brw_set_default_predicate_control(p, BRW_PREDICATE_NONE);

         /* Take into account the component size and horizontal stride. */
         assert(src.vstride == src.hstride + src.width);
         brw_SHL(p, addr, vec1(idx),
                 brw_imm_ud(_mesa_logbase2(type_sz(src.type)) +
                            src.hstride - 1));

         /* We can only address up to limit bytes using the indirect
          * addressing immediate, account for the difference if the source
          * register is above this limit.
          */
         if (offset >= limit)
            brw_ADD(p, addr, addr, brw_imm_ud(offset - offset % limit));

         brw_pop_insn_state(p);

         /* Use indirect addressing to fetch the specified component. */
         brw_MOV(p, dst,
                 retype(brw_vec1_indirect(addr.subnr, offset % limit),
                        src.type));
      } else {
         /* In SIMD4x2 mode the index can be either zero or one, replicate it
          * to all bits of a flag register,
          */
         inst = brw_MOV(p,
                        brw_null_reg(),
                        stride(brw_swizzle(idx, BRW_SWIZZLE_XXXX), 4, 4, 1));
         brw_inst_set_pred_control(devinfo, inst, BRW_PREDICATE_NONE);
         brw_inst_set_cond_modifier(devinfo, inst, BRW_CONDITIONAL_NZ);
         brw_inst_set_flag_reg_nr(devinfo, inst, 1);

         /* and use predicated SEL to pick the right channel. */
         inst = brw_SEL(p, dst,
                        stride(suboffset(src, 4), 4, 4, 1),
                        stride(src, 4, 4, 1));
         brw_inst_set_pred_control(devinfo, inst, BRW_PREDICATE_NORMAL);
         brw_inst_set_flag_reg_nr(devinfo, inst, 1);
      }
   }

   brw_pop_insn_state(p);
}

/**
 * This instruction is generated as a single-channel align1 instruction by
 * both the VS and FS stages when using INTEL_DEBUG=shader_time.
 *
 * We can't use the typed atomic op in the FS because that has the execution
 * mask ANDed with the pixel mask, but we just want to write the one dword for
 * all the pixels.
 *
 * We don't use the SIMD4x2 atomic ops in the VS because want to just write
 * one u32.  So we use the same untyped atomic write message as the pixel
 * shader.
 *
 * The untyped atomic operation requires a BUFFER surface type with RAW
 * format, and is only accessible through the legacy DATA_CACHE dataport
 * messages.
 */
void brw_shader_time_add(struct brw_codegen *p,
                         struct brw_reg payload,
                         uint32_t surf_index)
{
   const unsigned sfid = (p->devinfo->gen >= 8 || p->devinfo->is_haswell ?
                          HSW_SFID_DATAPORT_DATA_CACHE_1 :
                          GEN7_SFID_DATAPORT_DATA_CACHE);
   assert(p->devinfo->gen >= 7);

   brw_push_insn_state(p);
   brw_set_default_access_mode(p, BRW_ALIGN_1);
   brw_set_default_mask_control(p, BRW_MASK_DISABLE);
   brw_set_default_compression_control(p, BRW_COMPRESSION_NONE);
   brw_inst *send = brw_next_insn(p, BRW_OPCODE_SEND);

   /* We use brw_vec1_reg and unmasked because we want to increment the given
    * offset only once.
    */
   brw_set_dest(p, send, brw_vec1_reg(BRW_ARCHITECTURE_REGISTER_FILE,
                                      BRW_ARF_NULL, 0));
   brw_set_src0(p, send, brw_vec1_reg(payload.file,
                                      payload.nr, 0));
   brw_set_src1(p, send, brw_imm_ud(0));
   brw_set_message_descriptor(p, send, sfid, 2, 0, false, false);
   brw_inst_set_binding_table_index(p->devinfo, send, surf_index);
   brw_set_dp_untyped_atomic_message(p, send, BRW_AOP_ADD, false);

   brw_pop_insn_state(p);
}


/**
 * Emit the SEND message for a barrier
 */
void
brw_barrier(struct brw_codegen *p, struct brw_reg src)
{
   const struct gen_device_info *devinfo = p->devinfo;
   struct brw_inst *inst;

   assert(devinfo->gen >= 7);

   brw_push_insn_state(p);
   brw_set_default_access_mode(p, BRW_ALIGN_1);
   inst = next_insn(p, BRW_OPCODE_SEND);
   brw_set_dest(p, inst, retype(brw_null_reg(), BRW_REGISTER_TYPE_UW));
   brw_set_src0(p, inst, src);
   brw_set_src1(p, inst, brw_null_reg());

   brw_set_message_descriptor(p, inst, BRW_SFID_MESSAGE_GATEWAY,
                              1 /* msg_length */,
                              0 /* response_length */,
                              false /* header_present */,
                              false /* end_of_thread */);

   brw_inst_set_gateway_notify(devinfo, inst, 1);
   brw_inst_set_gateway_subfuncid(devinfo, inst,
                                  BRW_MESSAGE_GATEWAY_SFID_BARRIER_MSG);

   brw_inst_set_mask_control(devinfo, inst, BRW_MASK_DISABLE);
   brw_pop_insn_state(p);
}


/**
 * Emit the wait instruction for a barrier
 */
void
brw_WAIT(struct brw_codegen *p)
{
   const struct gen_device_info *devinfo = p->devinfo;
   struct brw_inst *insn;

   struct brw_reg src = brw_notification_reg();

   insn = next_insn(p, BRW_OPCODE_WAIT);
   brw_set_dest(p, insn, src);
   brw_set_src0(p, insn, src);
   brw_set_src1(p, insn, brw_null_reg());

   brw_inst_set_exec_size(devinfo, insn, BRW_EXECUTE_1);
   brw_inst_set_mask_control(devinfo, insn, BRW_MASK_DISABLE);
}