summaryrefslogtreecommitdiffstats
path: root/src/amd/common/ac_llvm_build.c
blob: 54e90288bda5d19b515682616df02698ea0a3ae6 (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
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
/*
 * Copyright 2014 Advanced Micro Devices, Inc.
 *
 * 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, sub license, 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 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 NON-INFRINGEMENT. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDERS, AUTHORS 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.
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 *
 */
/* based on pieces from si_pipe.c and radeon_llvm_emit.c */
#include "ac_llvm_build.h"

#include <llvm-c/Core.h>

#include "c11/threads.h"

#include <assert.h>
#include <stdio.h>

#include "ac_llvm_util.h"
#include "ac_exp_param.h"
#include "util/bitscan.h"
#include "util/macros.h"
#include "util/u_atomic.h"
#include "util/u_math.h"
#include "sid.h"

#include "shader_enums.h"

#define AC_LLVM_INITIAL_CF_DEPTH 4

/* Data for if/else/endif and bgnloop/endloop control flow structures.
 */
struct ac_llvm_flow {
	/* Loop exit or next part of if/else/endif. */
	LLVMBasicBlockRef next_block;
	LLVMBasicBlockRef loop_entry_block;
};

/* Initialize module-independent parts of the context.
 *
 * The caller is responsible for initializing ctx::module and ctx::builder.
 */
void
ac_llvm_context_init(struct ac_llvm_context *ctx,
		     enum chip_class chip_class, enum radeon_family family)
{
	LLVMValueRef args[1];

	ctx->context = LLVMContextCreate();

	ctx->chip_class = chip_class;
	ctx->family = family;
	ctx->module = NULL;
	ctx->builder = NULL;

	ctx->voidt = LLVMVoidTypeInContext(ctx->context);
	ctx->i1 = LLVMInt1TypeInContext(ctx->context);
	ctx->i8 = LLVMInt8TypeInContext(ctx->context);
	ctx->i16 = LLVMIntTypeInContext(ctx->context, 16);
	ctx->i32 = LLVMIntTypeInContext(ctx->context, 32);
	ctx->i64 = LLVMIntTypeInContext(ctx->context, 64);
	ctx->intptr = ctx->i32;
	ctx->f16 = LLVMHalfTypeInContext(ctx->context);
	ctx->f32 = LLVMFloatTypeInContext(ctx->context);
	ctx->f64 = LLVMDoubleTypeInContext(ctx->context);
	ctx->v2i16 = LLVMVectorType(ctx->i16, 2);
	ctx->v2i32 = LLVMVectorType(ctx->i32, 2);
	ctx->v3i32 = LLVMVectorType(ctx->i32, 3);
	ctx->v4i32 = LLVMVectorType(ctx->i32, 4);
	ctx->v2f32 = LLVMVectorType(ctx->f32, 2);
	ctx->v4f32 = LLVMVectorType(ctx->f32, 4);
	ctx->v8i32 = LLVMVectorType(ctx->i32, 8);

	ctx->i8_0 = LLVMConstInt(ctx->i8, 0, false);
	ctx->i8_1 = LLVMConstInt(ctx->i8, 1, false);
	ctx->i16_0 = LLVMConstInt(ctx->i16, 0, false);
	ctx->i16_1 = LLVMConstInt(ctx->i16, 1, false);
	ctx->i32_0 = LLVMConstInt(ctx->i32, 0, false);
	ctx->i32_1 = LLVMConstInt(ctx->i32, 1, false);
	ctx->i64_0 = LLVMConstInt(ctx->i64, 0, false);
	ctx->i64_1 = LLVMConstInt(ctx->i64, 1, false);
	ctx->f16_0 = LLVMConstReal(ctx->f16, 0.0);
	ctx->f16_1 = LLVMConstReal(ctx->f16, 1.0);
	ctx->f32_0 = LLVMConstReal(ctx->f32, 0.0);
	ctx->f32_1 = LLVMConstReal(ctx->f32, 1.0);
	ctx->f64_0 = LLVMConstReal(ctx->f64, 0.0);
	ctx->f64_1 = LLVMConstReal(ctx->f64, 1.0);

	ctx->i1false = LLVMConstInt(ctx->i1, 0, false);
	ctx->i1true = LLVMConstInt(ctx->i1, 1, false);

	ctx->range_md_kind = LLVMGetMDKindIDInContext(ctx->context,
						     "range", 5);

	ctx->invariant_load_md_kind = LLVMGetMDKindIDInContext(ctx->context,
							       "invariant.load", 14);

	ctx->fpmath_md_kind = LLVMGetMDKindIDInContext(ctx->context, "fpmath", 6);

	args[0] = LLVMConstReal(ctx->f32, 2.5);
	ctx->fpmath_md_2p5_ulp = LLVMMDNodeInContext(ctx->context, args, 1);

	ctx->uniform_md_kind = LLVMGetMDKindIDInContext(ctx->context,
							"amdgpu.uniform", 14);

	ctx->empty_md = LLVMMDNodeInContext(ctx->context, NULL, 0);
}

void
ac_llvm_context_dispose(struct ac_llvm_context *ctx)
{
	free(ctx->flow);
	ctx->flow = NULL;
	ctx->flow_depth_max = 0;
}

int
ac_get_llvm_num_components(LLVMValueRef value)
{
	LLVMTypeRef type = LLVMTypeOf(value);
	unsigned num_components = LLVMGetTypeKind(type) == LLVMVectorTypeKind
	                              ? LLVMGetVectorSize(type)
	                              : 1;
	return num_components;
}

LLVMValueRef
ac_llvm_extract_elem(struct ac_llvm_context *ac,
		     LLVMValueRef value,
		     int index)
{
	if (LLVMGetTypeKind(LLVMTypeOf(value)) != LLVMVectorTypeKind) {
		assert(index == 0);
		return value;
	}

	return LLVMBuildExtractElement(ac->builder, value,
				       LLVMConstInt(ac->i32, index, false), "");
}

int
ac_get_elem_bits(struct ac_llvm_context *ctx, LLVMTypeRef type)
{
	if (LLVMGetTypeKind(type) == LLVMVectorTypeKind)
		type = LLVMGetElementType(type);

	if (LLVMGetTypeKind(type) == LLVMIntegerTypeKind)
		return LLVMGetIntTypeWidth(type);

	if (type == ctx->f16)
		return 16;
	if (type == ctx->f32)
		return 32;
	if (type == ctx->f64)
		return 64;

	unreachable("Unhandled type kind in get_elem_bits");
}

unsigned
ac_get_type_size(LLVMTypeRef type)
{
	LLVMTypeKind kind = LLVMGetTypeKind(type);

	switch (kind) {
	case LLVMIntegerTypeKind:
		return LLVMGetIntTypeWidth(type) / 8;
	case LLVMHalfTypeKind:
		return 2;
	case LLVMFloatTypeKind:
		return 4;
	case LLVMDoubleTypeKind:
		return 8;
	case LLVMPointerTypeKind:
		if (LLVMGetPointerAddressSpace(type) == AC_ADDR_SPACE_CONST_32BIT)
			return 4;
		return 8;
	case LLVMVectorTypeKind:
		return LLVMGetVectorSize(type) *
		       ac_get_type_size(LLVMGetElementType(type));
	case LLVMArrayTypeKind:
		return LLVMGetArrayLength(type) *
		       ac_get_type_size(LLVMGetElementType(type));
	default:
		assert(0);
		return 0;
	}
}

static LLVMTypeRef to_integer_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
{
	if (t == ctx->i8)
		return ctx->i8;
	else if (t == ctx->f16 || t == ctx->i16)
		return ctx->i16;
	else if (t == ctx->f32 || t == ctx->i32)
		return ctx->i32;
	else if (t == ctx->f64 || t == ctx->i64)
		return ctx->i64;
	else
		unreachable("Unhandled integer size");
}

LLVMTypeRef
ac_to_integer_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
{
	if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
		LLVMTypeRef elem_type = LLVMGetElementType(t);
		return LLVMVectorType(to_integer_type_scalar(ctx, elem_type),
		                      LLVMGetVectorSize(t));
	}
	if (LLVMGetTypeKind(t) == LLVMPointerTypeKind) {
		switch (LLVMGetPointerAddressSpace(t)) {
		case AC_ADDR_SPACE_GLOBAL:
			return ctx->i64;
		case AC_ADDR_SPACE_LDS:
			return ctx->i32;
		default:
			unreachable("unhandled address space");
		}
	}
	return to_integer_type_scalar(ctx, t);
}

LLVMValueRef
ac_to_integer(struct ac_llvm_context *ctx, LLVMValueRef v)
{
	LLVMTypeRef type = LLVMTypeOf(v);
	if (LLVMGetTypeKind(type) == LLVMPointerTypeKind) {
		return LLVMBuildPtrToInt(ctx->builder, v, ac_to_integer_type(ctx, type), "");
	}
	return LLVMBuildBitCast(ctx->builder, v, ac_to_integer_type(ctx, type), "");
}

LLVMValueRef
ac_to_integer_or_pointer(struct ac_llvm_context *ctx, LLVMValueRef v)
{
	LLVMTypeRef type = LLVMTypeOf(v);
	if (LLVMGetTypeKind(type) == LLVMPointerTypeKind)
		return v;
	return ac_to_integer(ctx, v);
}

static LLVMTypeRef to_float_type_scalar(struct ac_llvm_context *ctx, LLVMTypeRef t)
{
	if (t == ctx->i8)
		return ctx->i8;
	else if (t == ctx->i16 || t == ctx->f16)
		return ctx->f16;
	else if (t == ctx->i32 || t == ctx->f32)
		return ctx->f32;
	else if (t == ctx->i64 || t == ctx->f64)
		return ctx->f64;
	else
		unreachable("Unhandled float size");
}

LLVMTypeRef
ac_to_float_type(struct ac_llvm_context *ctx, LLVMTypeRef t)
{
	if (LLVMGetTypeKind(t) == LLVMVectorTypeKind) {
		LLVMTypeRef elem_type = LLVMGetElementType(t);
		return LLVMVectorType(to_float_type_scalar(ctx, elem_type),
		                      LLVMGetVectorSize(t));
	}
	return to_float_type_scalar(ctx, t);
}

LLVMValueRef
ac_to_float(struct ac_llvm_context *ctx, LLVMValueRef v)
{
	LLVMTypeRef type = LLVMTypeOf(v);
	return LLVMBuildBitCast(ctx->builder, v, ac_to_float_type(ctx, type), "");
}


LLVMValueRef
ac_build_intrinsic(struct ac_llvm_context *ctx, const char *name,
		   LLVMTypeRef return_type, LLVMValueRef *params,
		   unsigned param_count, unsigned attrib_mask)
{
	LLVMValueRef function, call;
	bool set_callsite_attrs = !(attrib_mask & AC_FUNC_ATTR_LEGACY);

	function = LLVMGetNamedFunction(ctx->module, name);
	if (!function) {
		LLVMTypeRef param_types[32], function_type;
		unsigned i;

		assert(param_count <= 32);

		for (i = 0; i < param_count; ++i) {
			assert(params[i]);
			param_types[i] = LLVMTypeOf(params[i]);
		}
		function_type =
		    LLVMFunctionType(return_type, param_types, param_count, 0);
		function = LLVMAddFunction(ctx->module, name, function_type);

		LLVMSetFunctionCallConv(function, LLVMCCallConv);
		LLVMSetLinkage(function, LLVMExternalLinkage);

		if (!set_callsite_attrs)
			ac_add_func_attributes(ctx->context, function, attrib_mask);
	}

	call = LLVMBuildCall(ctx->builder, function, params, param_count, "");
	if (set_callsite_attrs)
		ac_add_func_attributes(ctx->context, call, attrib_mask);
	return call;
}

/**
 * Given the i32 or vNi32 \p type, generate the textual name (e.g. for use with
 * intrinsic names).
 */
void ac_build_type_name_for_intr(LLVMTypeRef type, char *buf, unsigned bufsize)
{
	LLVMTypeRef elem_type = type;

	assert(bufsize >= 8);

	if (LLVMGetTypeKind(type) == LLVMVectorTypeKind) {
		int ret = snprintf(buf, bufsize, "v%u",
					LLVMGetVectorSize(type));
		if (ret < 0) {
			char *type_name = LLVMPrintTypeToString(type);
			fprintf(stderr, "Error building type name for: %s\n",
				type_name);
			return;
		}
		elem_type = LLVMGetElementType(type);
		buf += ret;
		bufsize -= ret;
	}
	switch (LLVMGetTypeKind(elem_type)) {
	default: break;
	case LLVMIntegerTypeKind:
		snprintf(buf, bufsize, "i%d", LLVMGetIntTypeWidth(elem_type));
		break;
	case LLVMHalfTypeKind:
		snprintf(buf, bufsize, "f16");
		break;
	case LLVMFloatTypeKind:
		snprintf(buf, bufsize, "f32");
		break;
	case LLVMDoubleTypeKind:
		snprintf(buf, bufsize, "f64");
		break;
	}
}

/**
 * Helper function that builds an LLVM IR PHI node and immediately adds
 * incoming edges.
 */
LLVMValueRef
ac_build_phi(struct ac_llvm_context *ctx, LLVMTypeRef type,
	     unsigned count_incoming, LLVMValueRef *values,
	     LLVMBasicBlockRef *blocks)
{
	LLVMValueRef phi = LLVMBuildPhi(ctx->builder, type, "");
	LLVMAddIncoming(phi, values, blocks, count_incoming);
	return phi;
}

void ac_build_s_barrier(struct ac_llvm_context *ctx)
{
	ac_build_intrinsic(ctx, "llvm.amdgcn.s.barrier", ctx->voidt, NULL,
			   0, AC_FUNC_ATTR_CONVERGENT);
}

/* Prevent optimizations (at least of memory accesses) across the current
 * point in the program by emitting empty inline assembly that is marked as
 * having side effects.
 *
 * Optionally, a value can be passed through the inline assembly to prevent
 * LLVM from hoisting calls to ReadNone functions.
 */
void
ac_build_optimization_barrier(struct ac_llvm_context *ctx,
			      LLVMValueRef *pvgpr)
{
	static int counter = 0;

	LLVMBuilderRef builder = ctx->builder;
	char code[16];

	snprintf(code, sizeof(code), "; %d", p_atomic_inc_return(&counter));

	if (!pvgpr) {
		LLVMTypeRef ftype = LLVMFunctionType(ctx->voidt, NULL, 0, false);
		LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "", true, false);
		LLVMBuildCall(builder, inlineasm, NULL, 0, "");
	} else {
		LLVMTypeRef ftype = LLVMFunctionType(ctx->i32, &ctx->i32, 1, false);
		LLVMValueRef inlineasm = LLVMConstInlineAsm(ftype, code, "=v,0", true, false);
		LLVMValueRef vgpr = *pvgpr;
		LLVMTypeRef vgpr_type = LLVMTypeOf(vgpr);
		unsigned vgpr_size = ac_get_type_size(vgpr_type);
		LLVMValueRef vgpr0;

		assert(vgpr_size % 4 == 0);

		vgpr = LLVMBuildBitCast(builder, vgpr, LLVMVectorType(ctx->i32, vgpr_size / 4), "");
		vgpr0 = LLVMBuildExtractElement(builder, vgpr, ctx->i32_0, "");
		vgpr0 = LLVMBuildCall(builder, inlineasm, &vgpr0, 1, "");
		vgpr = LLVMBuildInsertElement(builder, vgpr, vgpr0, ctx->i32_0, "");
		vgpr = LLVMBuildBitCast(builder, vgpr, vgpr_type, "");

		*pvgpr = vgpr;
	}
}

LLVMValueRef
ac_build_shader_clock(struct ac_llvm_context *ctx)
{
	LLVMValueRef tmp = ac_build_intrinsic(ctx, "llvm.readcyclecounter",
					      ctx->i64, NULL, 0, 0);
	return LLVMBuildBitCast(ctx->builder, tmp, ctx->v2i32, "");
}

LLVMValueRef
ac_build_ballot(struct ac_llvm_context *ctx,
		LLVMValueRef value)
{
	LLVMValueRef args[3] = {
		value,
		ctx->i32_0,
		LLVMConstInt(ctx->i32, LLVMIntNE, 0)
	};

	/* We currently have no other way to prevent LLVM from lifting the icmp
	 * calls to a dominating basic block.
	 */
	ac_build_optimization_barrier(ctx, &args[0]);

	args[0] = ac_to_integer(ctx, args[0]);

	return ac_build_intrinsic(ctx,
				  "llvm.amdgcn.icmp.i32",
				  ctx->i64, args, 3,
				  AC_FUNC_ATTR_NOUNWIND |
				  AC_FUNC_ATTR_READNONE |
				  AC_FUNC_ATTR_CONVERGENT);
}

LLVMValueRef
ac_build_vote_all(struct ac_llvm_context *ctx, LLVMValueRef value)
{
	LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
	LLVMValueRef vote_set = ac_build_ballot(ctx, value);
	return LLVMBuildICmp(ctx->builder, LLVMIntEQ, vote_set, active_set, "");
}

LLVMValueRef
ac_build_vote_any(struct ac_llvm_context *ctx, LLVMValueRef value)
{
	LLVMValueRef vote_set = ac_build_ballot(ctx, value);
	return LLVMBuildICmp(ctx->builder, LLVMIntNE, vote_set,
			     LLVMConstInt(ctx->i64, 0, 0), "");
}

LLVMValueRef
ac_build_vote_eq(struct ac_llvm_context *ctx, LLVMValueRef value)
{
	LLVMValueRef active_set = ac_build_ballot(ctx, ctx->i32_1);
	LLVMValueRef vote_set = ac_build_ballot(ctx, value);

	LLVMValueRef all = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
					 vote_set, active_set, "");
	LLVMValueRef none = LLVMBuildICmp(ctx->builder, LLVMIntEQ,
					  vote_set,
					  LLVMConstInt(ctx->i64, 0, 0), "");
	return LLVMBuildOr(ctx->builder, all, none, "");
}

LLVMValueRef
ac_build_varying_gather_values(struct ac_llvm_context *ctx, LLVMValueRef *values,
			       unsigned value_count, unsigned component)
{
	LLVMValueRef vec = NULL;

	if (value_count == 1) {
		return values[component];
	} else if (!value_count)
		unreachable("value_count is 0");

	for (unsigned i = component; i < value_count + component; i++) {
		LLVMValueRef value = values[i];

		if (i == component)
			vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
		LLVMValueRef index = LLVMConstInt(ctx->i32, i - component, false);
		vec = LLVMBuildInsertElement(ctx->builder, vec, value, index, "");
	}
	return vec;
}

LLVMValueRef
ac_build_gather_values_extended(struct ac_llvm_context *ctx,
				LLVMValueRef *values,
				unsigned value_count,
				unsigned value_stride,
				bool load,
				bool always_vector)
{
	LLVMBuilderRef builder = ctx->builder;
	LLVMValueRef vec = NULL;
	unsigned i;

	if (value_count == 1 && !always_vector) {
		if (load)
			return LLVMBuildLoad(builder, values[0], "");
		return values[0];
	} else if (!value_count)
		unreachable("value_count is 0");

	for (i = 0; i < value_count; i++) {
		LLVMValueRef value = values[i * value_stride];
		if (load)
			value = LLVMBuildLoad(builder, value, "");

		if (!i)
			vec = LLVMGetUndef( LLVMVectorType(LLVMTypeOf(value), value_count));
		LLVMValueRef index = LLVMConstInt(ctx->i32, i, false);
		vec = LLVMBuildInsertElement(builder, vec, value, index, "");
	}
	return vec;
}

LLVMValueRef
ac_build_gather_values(struct ac_llvm_context *ctx,
		       LLVMValueRef *values,
		       unsigned value_count)
{
	return ac_build_gather_values_extended(ctx, values, value_count, 1, false, false);
}

/* Expand a scalar or vector to <dst_channels x type> by filling the remaining
 * channels with undef. Extract at most src_channels components from the input.
 */
static LLVMValueRef
ac_build_expand(struct ac_llvm_context *ctx,
		LLVMValueRef value,
		unsigned src_channels,
		unsigned dst_channels)
{
	LLVMTypeRef elemtype;
	LLVMValueRef chan[dst_channels];

	if (LLVMGetTypeKind(LLVMTypeOf(value)) == LLVMVectorTypeKind) {
		unsigned vec_size = LLVMGetVectorSize(LLVMTypeOf(value));

		if (src_channels == dst_channels && vec_size == dst_channels)
			return value;

		src_channels = MIN2(src_channels, vec_size);

		for (unsigned i = 0; i < src_channels; i++)
			chan[i] = ac_llvm_extract_elem(ctx, value, i);

		elemtype = LLVMGetElementType(LLVMTypeOf(value));
	} else {
		if (src_channels) {
			assert(src_channels == 1);
			chan[0] = value;
		}
		elemtype = LLVMTypeOf(value);
	}

	for (unsigned i = src_channels; i < dst_channels; i++)
		chan[i] = LLVMGetUndef(elemtype);

	return ac_build_gather_values(ctx, chan, dst_channels);
}

/* Expand a scalar or vector to <4 x type> by filling the remaining channels
 * with undef. Extract at most num_channels components from the input.
 */
LLVMValueRef ac_build_expand_to_vec4(struct ac_llvm_context *ctx,
				     LLVMValueRef value,
				     unsigned num_channels)
{
	return ac_build_expand(ctx, value, num_channels, 4);
}

LLVMValueRef ac_build_round(struct ac_llvm_context *ctx, LLVMValueRef value)
{
	unsigned type_size = ac_get_type_size(LLVMTypeOf(value));
	const char *name;

	if (type_size == 2)
		name = "llvm.rint.f16";
	else if (type_size == 4)
		name = "llvm.rint.f32";
	else
		name = "llvm.rint.f64";

	return ac_build_intrinsic(ctx, name, LLVMTypeOf(value), &value, 1,
				  AC_FUNC_ATTR_READNONE);
}

LLVMValueRef
ac_build_fdiv(struct ac_llvm_context *ctx,
	      LLVMValueRef num,
	      LLVMValueRef den)
{
	/* If we do (num / den), LLVM >= 7.0 does:
	 *    return num * v_rcp_f32(den * (fabs(den) > 0x1.0p+96f ? 0x1.0p-32f : 1.0f));
	 *
	 * If we do (num * (1 / den)), LLVM does:
	 *    return num * v_rcp_f32(den);
	 */
	LLVMValueRef one = LLVMConstReal(LLVMTypeOf(num), 1.0);
	LLVMValueRef rcp = LLVMBuildFDiv(ctx->builder, one, den, "");
	LLVMValueRef ret = LLVMBuildFMul(ctx->builder, num, rcp, "");

	/* Use v_rcp_f32 instead of precise division. */
	if (!LLVMIsConstant(ret))
		LLVMSetMetadata(ret, ctx->fpmath_md_kind, ctx->fpmath_md_2p5_ulp);
	return ret;
}

/* See fast_idiv_by_const.h. */
/* Set: increment = util_fast_udiv_info::increment ? multiplier : 0; */
LLVMValueRef ac_build_fast_udiv(struct ac_llvm_context *ctx,
				LLVMValueRef num,
				LLVMValueRef multiplier,
				LLVMValueRef pre_shift,
				LLVMValueRef post_shift,
				LLVMValueRef increment)
{
	LLVMBuilderRef builder = ctx->builder;

	num = LLVMBuildLShr(builder, num, pre_shift, "");
	num = LLVMBuildMul(builder,
			   LLVMBuildZExt(builder, num, ctx->i64, ""),
			   LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
	num = LLVMBuildAdd(builder, num,
			   LLVMBuildZExt(builder, increment, ctx->i64, ""), "");
	num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
	num = LLVMBuildTrunc(builder, num, ctx->i32, "");
	return LLVMBuildLShr(builder, num, post_shift, "");
}

/* See fast_idiv_by_const.h. */
/* If num != UINT_MAX, this more efficient version can be used. */
/* Set: increment = util_fast_udiv_info::increment; */
LLVMValueRef ac_build_fast_udiv_nuw(struct ac_llvm_context *ctx,
				    LLVMValueRef num,
				    LLVMValueRef multiplier,
				    LLVMValueRef pre_shift,
				    LLVMValueRef post_shift,
				    LLVMValueRef increment)
{
	LLVMBuilderRef builder = ctx->builder;

	num = LLVMBuildLShr(builder, num, pre_shift, "");
	num = LLVMBuildNUWAdd(builder, num, increment, "");
	num = LLVMBuildMul(builder,
			   LLVMBuildZExt(builder, num, ctx->i64, ""),
			   LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
	num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
	num = LLVMBuildTrunc(builder, num, ctx->i32, "");
	return LLVMBuildLShr(builder, num, post_shift, "");
}

/* See fast_idiv_by_const.h. */
/* Both operands must fit in 31 bits and the divisor must not be 1. */
LLVMValueRef ac_build_fast_udiv_u31_d_not_one(struct ac_llvm_context *ctx,
					      LLVMValueRef num,
					      LLVMValueRef multiplier,
					      LLVMValueRef post_shift)
{
	LLVMBuilderRef builder = ctx->builder;

	num = LLVMBuildMul(builder,
			   LLVMBuildZExt(builder, num, ctx->i64, ""),
			   LLVMBuildZExt(builder, multiplier, ctx->i64, ""), "");
	num = LLVMBuildLShr(builder, num, LLVMConstInt(ctx->i64, 32, 0), "");
	num = LLVMBuildTrunc(builder, num, ctx->i32, "");
	return LLVMBuildLShr(builder, num, post_shift, "");
}

/* Coordinates for cube map selection. sc, tc, and ma are as in Table 8.27
 * of the OpenGL 4.5 (Compatibility Profile) specification, except ma is
 * already multiplied by two. id is the cube face number.
 */
struct cube_selection_coords {
	LLVMValueRef stc[2];
	LLVMValueRef ma;
	LLVMValueRef id;
};

static void
build_cube_intrinsic(struct ac_llvm_context *ctx,
		     LLVMValueRef in[3],
		     struct cube_selection_coords *out)
{
	LLVMTypeRef f32 = ctx->f32;

	out->stc[1] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubetc",
					 f32, in, 3, AC_FUNC_ATTR_READNONE);
	out->stc[0] = ac_build_intrinsic(ctx, "llvm.amdgcn.cubesc",
					 f32, in, 3, AC_FUNC_ATTR_READNONE);
	out->ma = ac_build_intrinsic(ctx, "llvm.amdgcn.cubema",
				     f32, in, 3, AC_FUNC_ATTR_READNONE);
	out->id = ac_build_intrinsic(ctx, "llvm.amdgcn.cubeid",
				     f32, in, 3, AC_FUNC_ATTR_READNONE);
}

/**
 * Build a manual selection sequence for cube face sc/tc coordinates and
 * major axis vector (multiplied by 2 for consistency) for the given
 * vec3 \p coords, for the face implied by \p selcoords.
 *
 * For the major axis, we always adjust the sign to be in the direction of
 * selcoords.ma; i.e., a positive out_ma means that coords is pointed towards
 * the selcoords major axis.
 */
static void build_cube_select(struct ac_llvm_context *ctx,
			      const struct cube_selection_coords *selcoords,
			      const LLVMValueRef *coords,
			      LLVMValueRef *out_st,
			      LLVMValueRef *out_ma)
{
	LLVMBuilderRef builder = ctx->builder;
	LLVMTypeRef f32 = LLVMTypeOf(coords[0]);
	LLVMValueRef is_ma_positive;
	LLVMValueRef sgn_ma;
	LLVMValueRef is_ma_z, is_not_ma_z;
	LLVMValueRef is_ma_y;
	LLVMValueRef is_ma_x;
	LLVMValueRef sgn;
	LLVMValueRef tmp;

	is_ma_positive = LLVMBuildFCmp(builder, LLVMRealUGE,
		selcoords->ma, LLVMConstReal(f32, 0.0), "");
	sgn_ma = LLVMBuildSelect(builder, is_ma_positive,
		LLVMConstReal(f32, 1.0), LLVMConstReal(f32, -1.0), "");

	is_ma_z = LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 4.0), "");
	is_not_ma_z = LLVMBuildNot(builder, is_ma_z, "");
	is_ma_y = LLVMBuildAnd(builder, is_not_ma_z,
		LLVMBuildFCmp(builder, LLVMRealUGE, selcoords->id, LLVMConstReal(f32, 2.0), ""), "");
	is_ma_x = LLVMBuildAnd(builder, is_not_ma_z, LLVMBuildNot(builder, is_ma_y, ""), "");

	/* Select sc */
	tmp = LLVMBuildSelect(builder, is_ma_x, coords[2], coords[0], "");
	sgn = LLVMBuildSelect(builder, is_ma_y, LLVMConstReal(f32, 1.0),
		LLVMBuildSelect(builder, is_ma_z, sgn_ma,
			LLVMBuildFNeg(builder, sgn_ma, ""), ""), "");
	out_st[0] = LLVMBuildFMul(builder, tmp, sgn, "");

	/* Select tc */
	tmp = LLVMBuildSelect(builder, is_ma_y, coords[2], coords[1], "");
	sgn = LLVMBuildSelect(builder, is_ma_y, sgn_ma,
		LLVMConstReal(f32, -1.0), "");
	out_st[1] = LLVMBuildFMul(builder, tmp, sgn, "");

	/* Select ma */
	tmp = LLVMBuildSelect(builder, is_ma_z, coords[2],
		LLVMBuildSelect(builder, is_ma_y, coords[1], coords[0], ""), "");
	tmp = ac_build_intrinsic(ctx, "llvm.fabs.f32",
				 ctx->f32, &tmp, 1, AC_FUNC_ATTR_READNONE);
	*out_ma = LLVMBuildFMul(builder, tmp, LLVMConstReal(f32, 2.0), "");
}

void
ac_prepare_cube_coords(struct ac_llvm_context *ctx,
		       bool is_deriv, bool is_array, bool is_lod,
		       LLVMValueRef *coords_arg,
		       LLVMValueRef *derivs_arg)
{

	LLVMBuilderRef builder = ctx->builder;
	struct cube_selection_coords selcoords;
	LLVMValueRef coords[3];
	LLVMValueRef invma;

	if (is_array && !is_lod) {
		LLVMValueRef tmp = ac_build_round(ctx, coords_arg[3]);

		/* Section 8.9 (Texture Functions) of the GLSL 4.50 spec says:
		 *
		 *    "For Array forms, the array layer used will be
		 *
		 *       max(0, min(d−1, floor(layer+0.5)))
		 *
		 *     where d is the depth of the texture array and layer
		 *     comes from the component indicated in the tables below.
		 *     Workaroudn for an issue where the layer is taken from a
		 *     helper invocation which happens to fall on a different
		 *     layer due to extrapolation."
		 *
		 * VI and earlier attempt to implement this in hardware by
		 * clamping the value of coords[2] = (8 * layer) + face.
		 * Unfortunately, this means that the we end up with the wrong
		 * face when clamping occurs.
		 *
		 * Clamp the layer earlier to work around the issue.
		 */
		if (ctx->chip_class <= VI) {
			LLVMValueRef ge0;
			ge0 = LLVMBuildFCmp(builder, LLVMRealOGE, tmp, ctx->f32_0, "");
			tmp = LLVMBuildSelect(builder, ge0, tmp, ctx->f32_0, "");
		}

		coords_arg[3] = tmp;
	}

	build_cube_intrinsic(ctx, coords_arg, &selcoords);

	invma = ac_build_intrinsic(ctx, "llvm.fabs.f32",
			ctx->f32, &selcoords.ma, 1, AC_FUNC_ATTR_READNONE);
	invma = ac_build_fdiv(ctx, LLVMConstReal(ctx->f32, 1.0), invma);

	for (int i = 0; i < 2; ++i)
		coords[i] = LLVMBuildFMul(builder, selcoords.stc[i], invma, "");

	coords[2] = selcoords.id;

	if (is_deriv && derivs_arg) {
		LLVMValueRef derivs[4];
		int axis;

		/* Convert cube derivatives to 2D derivatives. */
		for (axis = 0; axis < 2; axis++) {
			LLVMValueRef deriv_st[2];
			LLVMValueRef deriv_ma;

			/* Transform the derivative alongside the texture
			 * coordinate. Mathematically, the correct formula is
			 * as follows. Assume we're projecting onto the +Z face
			 * and denote by dx/dh the derivative of the (original)
			 * X texture coordinate with respect to horizontal
			 * window coordinates. The projection onto the +Z face
			 * plane is:
			 *
			 *   f(x,z) = x/z
			 *
			 * Then df/dh = df/dx * dx/dh + df/dz * dz/dh
			 *            = 1/z * dx/dh - x/z * 1/z * dz/dh.
			 *
			 * This motivatives the implementation below.
			 *
			 * Whether this actually gives the expected results for
			 * apps that might feed in derivatives obtained via
			 * finite differences is anyone's guess. The OpenGL spec
			 * seems awfully quiet about how textureGrad for cube
			 * maps should be handled.
			 */
			build_cube_select(ctx, &selcoords, &derivs_arg[axis * 3],
					  deriv_st, &deriv_ma);

			deriv_ma = LLVMBuildFMul(builder, deriv_ma, invma, "");

			for (int i = 0; i < 2; ++i)
				derivs[axis * 2 + i] =
					LLVMBuildFSub(builder,
						LLVMBuildFMul(builder, deriv_st[i], invma, ""),
						LLVMBuildFMul(builder, deriv_ma, coords[i], ""), "");
		}

		memcpy(derivs_arg, derivs, sizeof(derivs));
	}

	/* Shift the texture coordinate. This must be applied after the
	 * derivative calculation.
	 */
	for (int i = 0; i < 2; ++i)
		coords[i] = LLVMBuildFAdd(builder, coords[i], LLVMConstReal(ctx->f32, 1.5), "");

	if (is_array) {
		/* for cube arrays coord.z = coord.w(array_index) * 8 + face */
		/* coords_arg.w component - array_index for cube arrays */
		coords[2] = ac_build_fmad(ctx, coords_arg[3], LLVMConstReal(ctx->f32, 8.0), coords[2]);
	}

	memcpy(coords_arg, coords, sizeof(coords));
}


LLVMValueRef
ac_build_fs_interp(struct ac_llvm_context *ctx,
		   LLVMValueRef llvm_chan,
		   LLVMValueRef attr_number,
		   LLVMValueRef params,
		   LLVMValueRef i,
		   LLVMValueRef j)
{
	LLVMValueRef args[5];
	LLVMValueRef p1;

	args[0] = i;
	args[1] = llvm_chan;
	args[2] = attr_number;
	args[3] = params;

	p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1",
				ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);

	args[0] = p1;
	args[1] = j;
	args[2] = llvm_chan;
	args[3] = attr_number;
	args[4] = params;

	return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2",
				  ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);
}

LLVMValueRef
ac_build_fs_interp_f16(struct ac_llvm_context *ctx,
		       LLVMValueRef llvm_chan,
		       LLVMValueRef attr_number,
		       LLVMValueRef params,
		       LLVMValueRef i,
		       LLVMValueRef j)
{
	LLVMValueRef args[6];
	LLVMValueRef p1;

	args[0] = i;
	args[1] = llvm_chan;
	args[2] = attr_number;
	args[3] = ctx->i1false;
	args[4] = params;

	p1 = ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p1.f16",
				ctx->f32, args, 5, AC_FUNC_ATTR_READNONE);

	args[0] = p1;
	args[1] = j;
	args[2] = llvm_chan;
	args[3] = attr_number;
	args[4] = ctx->i1false;
	args[5] = params;

	return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.p2.f16",
				  ctx->f16, args, 6, AC_FUNC_ATTR_READNONE);
}

LLVMValueRef
ac_build_fs_interp_mov(struct ac_llvm_context *ctx,
		       LLVMValueRef parameter,
		       LLVMValueRef llvm_chan,
		       LLVMValueRef attr_number,
		       LLVMValueRef params)
{
	LLVMValueRef args[4];

	args[0] = parameter;
	args[1] = llvm_chan;
	args[2] = attr_number;
	args[3] = params;

	return ac_build_intrinsic(ctx, "llvm.amdgcn.interp.mov",
				  ctx->f32, args, 4, AC_FUNC_ATTR_READNONE);
}

LLVMValueRef
ac_build_gep_ptr(struct ac_llvm_context *ctx,
	         LLVMValueRef base_ptr,
	         LLVMValueRef index)
{
	return LLVMBuildGEP(ctx->builder, base_ptr, &index, 1, "");
}

LLVMValueRef
ac_build_gep0(struct ac_llvm_context *ctx,
	      LLVMValueRef base_ptr,
	      LLVMValueRef index)
{
	LLVMValueRef indices[2] = {
		ctx->i32_0,
		index,
	};
	return LLVMBuildGEP(ctx->builder, base_ptr, indices, 2, "");
}

LLVMValueRef ac_build_pointer_add(struct ac_llvm_context *ctx, LLVMValueRef ptr,
				  LLVMValueRef index)
{
	return LLVMBuildPointerCast(ctx->builder,
				    ac_build_gep0(ctx, ptr, index),
				    LLVMTypeOf(ptr), "");
}

void
ac_build_indexed_store(struct ac_llvm_context *ctx,
		       LLVMValueRef base_ptr, LLVMValueRef index,
		       LLVMValueRef value)
{
	LLVMBuildStore(ctx->builder, value,
		       ac_build_gep0(ctx, base_ptr, index));
}

/**
 * Build an LLVM bytecode indexed load using LLVMBuildGEP + LLVMBuildLoad.
 * It's equivalent to doing a load from &base_ptr[index].
 *
 * \param base_ptr  Where the array starts.
 * \param index     The element index into the array.
 * \param uniform   Whether the base_ptr and index can be assumed to be
 *                  dynamically uniform (i.e. load to an SGPR)
 * \param invariant Whether the load is invariant (no other opcodes affect it)
 * \param no_unsigned_wraparound
 *    For all possible re-associations and re-distributions of an expression
 *    "base_ptr + index * elemsize" into "addr + offset" (excluding GEPs
 *    without inbounds in base_ptr), this parameter is true if "addr + offset"
 *    does not result in an unsigned integer wraparound. This is used for
 *    optimal code generation of 32-bit pointer arithmetic.
 *
 *    For example, a 32-bit immediate offset that causes a 32-bit unsigned
 *    integer wraparound can't be an imm offset in s_load_dword, because
 *    the instruction performs "addr + offset" in 64 bits.
 *
 *    Expected usage for bindless textures by chaining GEPs:
 *      // possible unsigned wraparound, don't use InBounds:
 *      ptr1 = LLVMBuildGEP(base_ptr, index);
 *      image = load(ptr1); // becomes "s_load ptr1, 0"
 *
 *      ptr2 = LLVMBuildInBoundsGEP(ptr1, 32 / elemsize);
 *      sampler = load(ptr2); // becomes "s_load ptr1, 32" thanks to InBounds
 */
static LLVMValueRef
ac_build_load_custom(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
		     LLVMValueRef index, bool uniform, bool invariant,
		     bool no_unsigned_wraparound)
{
	LLVMValueRef pointer, result;
	LLVMValueRef indices[2] = {ctx->i32_0, index};

	if (no_unsigned_wraparound &&
	    LLVMGetPointerAddressSpace(LLVMTypeOf(base_ptr)) == AC_ADDR_SPACE_CONST_32BIT)
		pointer = LLVMBuildInBoundsGEP(ctx->builder, base_ptr, indices, 2, "");
	else
		pointer = LLVMBuildGEP(ctx->builder, base_ptr, indices, 2, "");

	if (uniform)
		LLVMSetMetadata(pointer, ctx->uniform_md_kind, ctx->empty_md);
	result = LLVMBuildLoad(ctx->builder, pointer, "");
	if (invariant)
		LLVMSetMetadata(result, ctx->invariant_load_md_kind, ctx->empty_md);
	return result;
}

LLVMValueRef ac_build_load(struct ac_llvm_context *ctx, LLVMValueRef base_ptr,
			   LLVMValueRef index)
{
	return ac_build_load_custom(ctx, base_ptr, index, false, false, false);
}

LLVMValueRef ac_build_load_invariant(struct ac_llvm_context *ctx,
				     LLVMValueRef base_ptr, LLVMValueRef index)
{
	return ac_build_load_custom(ctx, base_ptr, index, false, true, false);
}

/* This assumes that there is no unsigned integer wraparound during the address
 * computation, excluding all GEPs within base_ptr. */
LLVMValueRef ac_build_load_to_sgpr(struct ac_llvm_context *ctx,
				   LLVMValueRef base_ptr, LLVMValueRef index)
{
	return ac_build_load_custom(ctx, base_ptr, index, true, true, true);
}

/* See ac_build_load_custom() documentation. */
LLVMValueRef ac_build_load_to_sgpr_uint_wraparound(struct ac_llvm_context *ctx,
				   LLVMValueRef base_ptr, LLVMValueRef index)
{
	return ac_build_load_custom(ctx, base_ptr, index, true, true, false);
}

static void
ac_build_buffer_store_common(struct ac_llvm_context *ctx,
			     LLVMValueRef rsrc,
			     LLVMValueRef data,
			     LLVMValueRef vindex,
			     LLVMValueRef voffset,
			     unsigned num_channels,
			     bool glc,
			     bool slc,
			     bool writeonly_memory,
			     bool use_format)
{
	LLVMValueRef args[] = {
		data,
		LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
		vindex ? vindex : ctx->i32_0,
		voffset,
		LLVMConstInt(ctx->i1, glc, 0),
		LLVMConstInt(ctx->i1, slc, 0)
	};
	unsigned func = CLAMP(num_channels, 1, 3) - 1;

	const char *type_names[] = {"f32", "v2f32", "v4f32"};
	char name[256];

	if (use_format) {
		snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.format.%s",
			 type_names[func]);
	} else {
		snprintf(name, sizeof(name), "llvm.amdgcn.buffer.store.%s",
			 type_names[func]);
	}

	ac_build_intrinsic(ctx, name, ctx->voidt, args, ARRAY_SIZE(args),
			   ac_get_store_intr_attribs(writeonly_memory));
}

static void
ac_build_llvm8_buffer_store_common(struct ac_llvm_context *ctx,
				   LLVMValueRef rsrc,
				   LLVMValueRef data,
				   LLVMValueRef vindex,
				   LLVMValueRef voffset,
				   LLVMValueRef soffset,
				   unsigned num_channels,
				   bool glc,
				   bool slc,
				   bool writeonly_memory,
				   bool use_format,
				   bool structurized)
{
	LLVMValueRef args[6];
	int idx = 0;
	args[idx++] = data;
	args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
	if (structurized)
		args[idx++] = vindex ? vindex : ctx->i32_0;
	args[idx++] = voffset ? voffset : ctx->i32_0;
	args[idx++] = soffset ? soffset : ctx->i32_0;
	args[idx++] = LLVMConstInt(ctx->i32, (glc ? 1 : 0) + (slc ? 2 : 0), 0);
	unsigned func = CLAMP(num_channels, 1, 3) - 1;

	const char *type_names[] = {"f32", "v2f32", "v4f32"};
	const char *indexing_kind = structurized ? "struct" : "raw";
	char name[256];

	if (use_format) {
		snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.format.%s",
			 indexing_kind, type_names[func]);
	} else {
		snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.store.%s",
			 indexing_kind, type_names[func]);
	}

	ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
			   ac_get_store_intr_attribs(writeonly_memory));
}

void
ac_build_buffer_store_format(struct ac_llvm_context *ctx,
			     LLVMValueRef rsrc,
			     LLVMValueRef data,
			     LLVMValueRef vindex,
			     LLVMValueRef voffset,
			     unsigned num_channels,
			     bool glc,
			     bool writeonly_memory)
{
	if (HAVE_LLVM >= 0x800) {
		ac_build_llvm8_buffer_store_common(ctx, rsrc, data, vindex,
						   voffset, NULL, num_channels,
						   glc, false, writeonly_memory,
						   true, true);
	} else {
		ac_build_buffer_store_common(ctx, rsrc, data, vindex, voffset,
					     num_channels, glc, false,
					     writeonly_memory, true);
	}
}

/* TBUFFER_STORE_FORMAT_{X,XY,XYZ,XYZW} <- the suffix is selected by num_channels=1..4.
 * The type of vdata must be one of i32 (num_channels=1), v2i32 (num_channels=2),
 * or v4i32 (num_channels=3,4).
 */
void
ac_build_buffer_store_dword(struct ac_llvm_context *ctx,
			    LLVMValueRef rsrc,
			    LLVMValueRef vdata,
			    unsigned num_channels,
			    LLVMValueRef voffset,
			    LLVMValueRef soffset,
			    unsigned inst_offset,
			    bool glc,
			    bool slc,
			    bool writeonly_memory,
			    bool swizzle_enable_hint)
{
	/* Split 3 channel stores, becase LLVM doesn't support 3-channel
	 * intrinsics. */
	if (num_channels == 3) {
		LLVMValueRef v[3], v01;

		for (int i = 0; i < 3; i++) {
			v[i] = LLVMBuildExtractElement(ctx->builder, vdata,
					LLVMConstInt(ctx->i32, i, 0), "");
		}
		v01 = ac_build_gather_values(ctx, v, 2);

		ac_build_buffer_store_dword(ctx, rsrc, v01, 2, voffset,
					    soffset, inst_offset, glc, slc,
					    writeonly_memory, swizzle_enable_hint);
		ac_build_buffer_store_dword(ctx, rsrc, v[2], 1, voffset,
					    soffset, inst_offset + 8,
					    glc, slc,
					    writeonly_memory, swizzle_enable_hint);
		return;
	}

	/* SWIZZLE_ENABLE requires that soffset isn't folded into voffset
	 * (voffset is swizzled, but soffset isn't swizzled).
	 * llvm.amdgcn.buffer.store doesn't have a separate soffset parameter.
	 */
	if (!swizzle_enable_hint) {
		LLVMValueRef offset = soffset;

		if (inst_offset)
			offset = LLVMBuildAdd(ctx->builder, offset,
					      LLVMConstInt(ctx->i32, inst_offset, 0), "");

		if (HAVE_LLVM >= 0x800) {
			ac_build_llvm8_buffer_store_common(ctx, rsrc,
							   ac_to_float(ctx, vdata),
							   ctx->i32_0,
							   voffset, offset,
							   num_channels,
							   glc, slc,
							   writeonly_memory,
							   false, false);
		} else {
			if (voffset)
				offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");

			ac_build_buffer_store_common(ctx, rsrc,
						     ac_to_float(ctx, vdata),
						     ctx->i32_0, offset,
						     num_channels, glc, slc,
						     writeonly_memory, false);
		}
		return;
	}

	static const unsigned dfmts[] = {
		V_008F0C_BUF_DATA_FORMAT_32,
		V_008F0C_BUF_DATA_FORMAT_32_32,
		V_008F0C_BUF_DATA_FORMAT_32_32_32,
		V_008F0C_BUF_DATA_FORMAT_32_32_32_32
	};
	unsigned dfmt = dfmts[num_channels - 1];
	unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
	LLVMValueRef immoffset = LLVMConstInt(ctx->i32, inst_offset, 0);

	ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
			           immoffset, num_channels, dfmt, nfmt, glc,
				   slc, writeonly_memory);
}

static LLVMValueRef
ac_build_buffer_load_common(struct ac_llvm_context *ctx,
			    LLVMValueRef rsrc,
			    LLVMValueRef vindex,
			    LLVMValueRef voffset,
			    unsigned num_channels,
			    bool glc,
			    bool slc,
			    bool can_speculate,
			    bool use_format)
{
	LLVMValueRef args[] = {
		LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, ""),
		vindex ? vindex : ctx->i32_0,
		voffset,
		LLVMConstInt(ctx->i1, glc, 0),
		LLVMConstInt(ctx->i1, slc, 0)
	};
	unsigned func = CLAMP(num_channels, 1, 3) - 1;

	LLVMTypeRef types[] = {ctx->f32, ctx->v2f32, ctx->v4f32};
	const char *type_names[] = {"f32", "v2f32", "v4f32"};
	char name[256];

	if (use_format) {
		snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.format.%s",
			 type_names[func]);
	} else {
		snprintf(name, sizeof(name), "llvm.amdgcn.buffer.load.%s",
			 type_names[func]);
	}

	return ac_build_intrinsic(ctx, name, types[func], args,
				  ARRAY_SIZE(args),
				  ac_get_load_intr_attribs(can_speculate));
}

static LLVMValueRef
ac_build_llvm8_buffer_load_common(struct ac_llvm_context *ctx,
				  LLVMValueRef rsrc,
				  LLVMValueRef vindex,
				  LLVMValueRef voffset,
				  LLVMValueRef soffset,
				  unsigned num_channels,
				  bool glc,
				  bool slc,
				  bool can_speculate,
				  bool use_format,
				  bool structurized)
{
	LLVMValueRef args[5];
	int idx = 0;
	args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
	if (structurized)
		args[idx++] = vindex ? vindex : ctx->i32_0;
	args[idx++] = voffset ? voffset : ctx->i32_0;
	args[idx++] = soffset ? soffset : ctx->i32_0;
	args[idx++] = LLVMConstInt(ctx->i32, (glc ? 1 : 0) + (slc ? 2 : 0), 0);
	unsigned func = CLAMP(num_channels, 1, 3) - 1;

	LLVMTypeRef types[] = {ctx->f32, ctx->v2f32, ctx->v4f32};
	const char *type_names[] = {"f32", "v2f32", "v4f32"};
	const char *indexing_kind = structurized ? "struct" : "raw";
	char name[256];

	if (use_format) {
		snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.format.%s",
			 indexing_kind, type_names[func]);
	} else {
		snprintf(name, sizeof(name), "llvm.amdgcn.%s.buffer.load.%s",
			 indexing_kind, type_names[func]);
	}

	return ac_build_intrinsic(ctx, name, types[func], args,
				  idx,
				  ac_get_load_intr_attribs(can_speculate));
}

LLVMValueRef
ac_build_buffer_load(struct ac_llvm_context *ctx,
		     LLVMValueRef rsrc,
		     int num_channels,
		     LLVMValueRef vindex,
		     LLVMValueRef voffset,
		     LLVMValueRef soffset,
		     unsigned inst_offset,
		     unsigned glc,
		     unsigned slc,
		     bool can_speculate,
		     bool allow_smem)
{
	LLVMValueRef offset = LLVMConstInt(ctx->i32, inst_offset, 0);
	if (voffset)
		offset = LLVMBuildAdd(ctx->builder, offset, voffset, "");
	if (soffset)
		offset = LLVMBuildAdd(ctx->builder, offset, soffset, "");

	if (allow_smem && !slc &&
	    (!glc || (HAVE_LLVM >= 0x0800 && ctx->chip_class >= VI))) {
		assert(vindex == NULL);

		LLVMValueRef result[8];

		for (int i = 0; i < num_channels; i++) {
			if (i) {
				offset = LLVMBuildAdd(ctx->builder, offset,
						      LLVMConstInt(ctx->i32, 4, 0), "");
			}
			const char *intrname =
				HAVE_LLVM >= 0x0800 ? "llvm.amdgcn.s.buffer.load.f32"
						    : "llvm.SI.load.const.v4i32";
			unsigned num_args = HAVE_LLVM >= 0x0800 ? 3 : 2;
			LLVMValueRef args[3] = {
				rsrc,
				offset,
				glc ? ctx->i32_1 : ctx->i32_0,
			};
			result[i] = ac_build_intrinsic(ctx, intrname,
						       ctx->f32, args, num_args,
						       AC_FUNC_ATTR_READNONE |
						       (HAVE_LLVM < 0x0800 ? AC_FUNC_ATTR_LEGACY : 0));
		}
		if (num_channels == 1)
			return result[0];

		if (num_channels == 3)
			result[num_channels++] = LLVMGetUndef(ctx->f32);
		return ac_build_gather_values(ctx, result, num_channels);
	}

	if (HAVE_LLVM >= 0x0800) {
		return ac_build_llvm8_buffer_load_common(ctx, rsrc, vindex,
							 offset, ctx->i32_0,
							 num_channels, glc, slc,
							 can_speculate, false,
							 false);
	}

	return ac_build_buffer_load_common(ctx, rsrc, vindex, offset,
					   num_channels, glc, slc,
					   can_speculate, false);
}

LLVMValueRef ac_build_buffer_load_format(struct ac_llvm_context *ctx,
					 LLVMValueRef rsrc,
					 LLVMValueRef vindex,
					 LLVMValueRef voffset,
					 unsigned num_channels,
					 bool glc,
					 bool can_speculate)
{
	if (HAVE_LLVM >= 0x800) {
		return ac_build_llvm8_buffer_load_common(ctx, rsrc, vindex, voffset, ctx->i32_0,
							 num_channels, glc, false,
							 can_speculate, true, true);
	}
	return ac_build_buffer_load_common(ctx, rsrc, vindex, voffset,
					   num_channels, glc, false,
					   can_speculate, true);
}

LLVMValueRef ac_build_buffer_load_format_gfx9_safe(struct ac_llvm_context *ctx,
                                                  LLVMValueRef rsrc,
                                                  LLVMValueRef vindex,
                                                  LLVMValueRef voffset,
                                                  unsigned num_channels,
                                                  bool glc,
                                                  bool can_speculate)
{
	if (HAVE_LLVM >= 0x800) {
		return ac_build_llvm8_buffer_load_common(ctx, rsrc, vindex, voffset, ctx->i32_0,
							 num_channels, glc, false,
							 can_speculate, true, true);
	}

	LLVMValueRef elem_count = LLVMBuildExtractElement(ctx->builder, rsrc, LLVMConstInt(ctx->i32, 2, 0), "");
	LLVMValueRef stride = LLVMBuildExtractElement(ctx->builder, rsrc, ctx->i32_1, "");
	stride = LLVMBuildLShr(ctx->builder, stride, LLVMConstInt(ctx->i32, 16, 0), "");

	LLVMValueRef new_elem_count = LLVMBuildSelect(ctx->builder,
	                                              LLVMBuildICmp(ctx->builder, LLVMIntUGT, elem_count, stride, ""),
	                                              elem_count, stride, "");

	LLVMValueRef new_rsrc = LLVMBuildInsertElement(ctx->builder, rsrc, new_elem_count,
	                                               LLVMConstInt(ctx->i32, 2, 0), "");

	return ac_build_buffer_load_common(ctx, new_rsrc, vindex, voffset,
	                                   num_channels, glc, false,
	                                   can_speculate, true);
}

static LLVMValueRef
ac_build_llvm8_tbuffer_load(struct ac_llvm_context *ctx,
			    LLVMValueRef rsrc,
			    LLVMValueRef vindex,
			    LLVMValueRef voffset,
			    LLVMValueRef soffset,
			    unsigned num_channels,
			    unsigned dfmt,
			    unsigned nfmt,
			    bool glc,
			    bool slc,
			    bool can_speculate,
			    bool structurized)
{
	LLVMValueRef args[6];
	int idx = 0;
	args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
	if (structurized)
		args[idx++] = vindex ? vindex : ctx->i32_0;
	args[idx++] = voffset ? voffset : ctx->i32_0;
	args[idx++] = soffset ? soffset : ctx->i32_0;
	args[idx++] = LLVMConstInt(ctx->i32, dfmt | (nfmt << 4), 0);
	args[idx++] = LLVMConstInt(ctx->i32, (glc ? 1 : 0) + (slc ? 2 : 0), 0);
	unsigned func = CLAMP(num_channels, 1, 3) - 1;

	LLVMTypeRef types[] = {ctx->i32, ctx->v2i32, ctx->v4i32};
	const char *type_names[] = {"i32", "v2i32", "v4i32"};
	const char *indexing_kind = structurized ? "struct" : "raw";
	char name[256];

	snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.load.%s",
		 indexing_kind, type_names[func]);

	return ac_build_intrinsic(ctx, name, types[func], args,
				  idx,
				  ac_get_load_intr_attribs(can_speculate));
}

static LLVMValueRef
ac_build_tbuffer_load(struct ac_llvm_context *ctx,
			    LLVMValueRef rsrc,
			    LLVMValueRef vindex,
			    LLVMValueRef voffset,
			    LLVMValueRef soffset,
			    LLVMValueRef immoffset,
			    unsigned num_channels,
			    unsigned dfmt,
			    unsigned nfmt,
			    bool glc,
			    bool slc,
			    bool can_speculate,
			    bool structurized) /* only matters for LLVM 8+ */
{
	if (HAVE_LLVM >= 0x800) {
		voffset = LLVMBuildAdd(ctx->builder, voffset, immoffset, "");

		return ac_build_llvm8_tbuffer_load(ctx, rsrc, vindex, voffset,
						   soffset, num_channels,
						   dfmt, nfmt, glc, slc,
						   can_speculate, structurized);
	}

	LLVMValueRef args[] = {
		rsrc,
		vindex ? vindex : ctx->i32_0,
		voffset,
		soffset,
		immoffset,
		LLVMConstInt(ctx->i32, dfmt, false),
		LLVMConstInt(ctx->i32, nfmt, false),
		LLVMConstInt(ctx->i1, glc, false),
		LLVMConstInt(ctx->i1, slc, false),
	};
	unsigned func = CLAMP(num_channels, 1, 3) - 1;
	LLVMTypeRef types[] = {ctx->i32, ctx->v2i32, ctx->v4i32};
	const char *type_names[] = {"i32", "v2i32", "v4i32"};
	char name[256];

	snprintf(name, sizeof(name), "llvm.amdgcn.tbuffer.load.%s",
		 type_names[func]);

	return ac_build_intrinsic(ctx, name, types[func], args, 9,
				  ac_get_load_intr_attribs(can_speculate));
}

LLVMValueRef
ac_build_struct_tbuffer_load(struct ac_llvm_context *ctx,
			     LLVMValueRef rsrc,
			     LLVMValueRef vindex,
			     LLVMValueRef voffset,
			     LLVMValueRef soffset,
			     LLVMValueRef immoffset,
			     unsigned num_channels,
			     unsigned dfmt,
			     unsigned nfmt,
			     bool glc,
			     bool slc,
			     bool can_speculate)
{
	return ac_build_tbuffer_load(ctx, rsrc, vindex, voffset, soffset,
				     immoffset, num_channels, dfmt, nfmt, glc,
				     slc, can_speculate, true);
}

LLVMValueRef
ac_build_raw_tbuffer_load(struct ac_llvm_context *ctx,
			  LLVMValueRef rsrc,
			  LLVMValueRef voffset,
			  LLVMValueRef soffset,
			  LLVMValueRef immoffset,
			  unsigned num_channels,
			  unsigned dfmt,
			  unsigned nfmt,
			  bool glc,
			  bool slc,
		          bool can_speculate)
{
	return ac_build_tbuffer_load(ctx, rsrc, NULL, voffset, soffset,
				     immoffset, num_channels, dfmt, nfmt, glc,
				     slc, can_speculate, false);
}

LLVMValueRef
ac_build_tbuffer_load_short(struct ac_llvm_context *ctx,
			    LLVMValueRef rsrc,
			    LLVMValueRef voffset,
			    LLVMValueRef soffset,
			    LLVMValueRef immoffset,
			    bool glc)
{
	unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
	unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
	LLVMValueRef res;

	res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
					immoffset, 1, dfmt, nfmt, glc, false,
					false);

	return LLVMBuildTrunc(ctx->builder, res, ctx->i16, "");
}

LLVMValueRef
ac_build_tbuffer_load_byte(struct ac_llvm_context *ctx,
			   LLVMValueRef rsrc,
			   LLVMValueRef voffset,
			   LLVMValueRef soffset,
			   LLVMValueRef immoffset,
			   bool glc)
{
	unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
	unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;
	LLVMValueRef res;

	res = ac_build_raw_tbuffer_load(ctx, rsrc, voffset, soffset,
					immoffset, 1, dfmt, nfmt, glc, false,
					false);

	return LLVMBuildTrunc(ctx->builder, res, ctx->i8, "");
}
static void
ac_build_llvm8_tbuffer_store(struct ac_llvm_context *ctx,
			     LLVMValueRef rsrc,
			     LLVMValueRef vdata,
			     LLVMValueRef vindex,
			     LLVMValueRef voffset,
			     LLVMValueRef soffset,
			     unsigned num_channels,
			     unsigned dfmt,
			     unsigned nfmt,
			     bool glc,
			     bool slc,
			     bool writeonly_memory,
			     bool structurized)
{
	LLVMValueRef args[7];
	int idx = 0;
	args[idx++] = vdata;
	args[idx++] = LLVMBuildBitCast(ctx->builder, rsrc, ctx->v4i32, "");
	if (structurized)
		args[idx++] = vindex ? vindex : ctx->i32_0;
	args[idx++] = voffset ? voffset : ctx->i32_0;
	args[idx++] = soffset ? soffset : ctx->i32_0;
	args[idx++] = LLVMConstInt(ctx->i32, dfmt | (nfmt << 4), 0);
	args[idx++] = LLVMConstInt(ctx->i32, (glc ? 1 : 0) + (slc ? 2 : 0), 0);
	unsigned func = CLAMP(num_channels, 1, 3) - 1;

	const char *type_names[] = {"i32", "v2i32", "v4i32"};
	const char *indexing_kind = structurized ? "struct" : "raw";
	char name[256];

	snprintf(name, sizeof(name), "llvm.amdgcn.%s.tbuffer.store.%s",
		 indexing_kind, type_names[func]);

	ac_build_intrinsic(ctx, name, ctx->voidt, args, idx,
			   ac_get_store_intr_attribs(writeonly_memory));
}

static void
ac_build_tbuffer_store(struct ac_llvm_context *ctx,
		       LLVMValueRef rsrc,
		       LLVMValueRef vdata,
		       LLVMValueRef vindex,
		       LLVMValueRef voffset,
		       LLVMValueRef soffset,
		       LLVMValueRef immoffset,
		       unsigned num_channels,
		       unsigned dfmt,
		       unsigned nfmt,
		       bool glc,
		       bool slc,
		       bool writeonly_memory,
		       bool structurized) /* only matters for LLVM 8+ */
{
	if (HAVE_LLVM >= 0x800) {
		voffset = LLVMBuildAdd(ctx->builder,
				       voffset ? voffset : ctx->i32_0,
				       immoffset, "");

		ac_build_llvm8_tbuffer_store(ctx, rsrc, vdata, vindex, voffset,
					     soffset, num_channels, dfmt, nfmt,
					     glc, slc, writeonly_memory,
					     structurized);
	} else {
		LLVMValueRef params[] = {
			vdata,
			rsrc,
			vindex ? vindex : ctx->i32_0,
			voffset ? voffset : ctx->i32_0,
			soffset ? soffset : ctx->i32_0,
			immoffset,
			LLVMConstInt(ctx->i32, dfmt, false),
			LLVMConstInt(ctx->i32, nfmt, false),
			LLVMConstInt(ctx->i1, glc, false),
			LLVMConstInt(ctx->i1, slc, false),
		};
		unsigned func = CLAMP(num_channels, 1, 3) - 1;
		const char *type_names[] = {"i32", "v2i32", "v4i32"};
		char name[256];

		snprintf(name, sizeof(name), "llvm.amdgcn.tbuffer.store.%s",
			 type_names[func]);

		ac_build_intrinsic(ctx, name, ctx->voidt, params, 10,
				   ac_get_store_intr_attribs(writeonly_memory));
	}
}

void
ac_build_struct_tbuffer_store(struct ac_llvm_context *ctx,
			      LLVMValueRef rsrc,
			      LLVMValueRef vdata,
			      LLVMValueRef vindex,
			      LLVMValueRef voffset,
			      LLVMValueRef soffset,
			      LLVMValueRef immoffset,
			      unsigned num_channels,
			      unsigned dfmt,
			      unsigned nfmt,
			      bool glc,
			      bool slc,
			      bool writeonly_memory)
{
	ac_build_tbuffer_store(ctx, rsrc, vdata, vindex, voffset, soffset,
			       immoffset, num_channels, dfmt, nfmt, glc, slc,
			       writeonly_memory, true);
}

void
ac_build_raw_tbuffer_store(struct ac_llvm_context *ctx,
			   LLVMValueRef rsrc,
			   LLVMValueRef vdata,
			   LLVMValueRef voffset,
			   LLVMValueRef soffset,
			   LLVMValueRef immoffset,
			   unsigned num_channels,
			   unsigned dfmt,
			   unsigned nfmt,
			   bool glc,
			   bool slc,
			   bool writeonly_memory)
{
	ac_build_tbuffer_store(ctx, rsrc, vdata, NULL, voffset, soffset,
			       immoffset, num_channels, dfmt, nfmt, glc, slc,
			       writeonly_memory, false);
}

void
ac_build_tbuffer_store_short(struct ac_llvm_context *ctx,
			     LLVMValueRef rsrc,
			     LLVMValueRef vdata,
			     LLVMValueRef voffset,
			     LLVMValueRef soffset,
			     bool glc,
			     bool writeonly_memory)
{
	unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_16;
	unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;

	vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i16, "");
	vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");

	ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
				   ctx->i32_0, 1, dfmt, nfmt, glc, false,
				   writeonly_memory);
}

void
ac_build_tbuffer_store_byte(struct ac_llvm_context *ctx,
			    LLVMValueRef rsrc,
			    LLVMValueRef vdata,
			    LLVMValueRef voffset,
			    LLVMValueRef soffset,
			    bool glc,
			    bool writeonly_memory)
{
	unsigned dfmt = V_008F0C_BUF_DATA_FORMAT_8;
	unsigned nfmt = V_008F0C_BUF_NUM_FORMAT_UINT;

	vdata = LLVMBuildBitCast(ctx->builder, vdata, ctx->i8, "");
	vdata = LLVMBuildZExt(ctx->builder, vdata, ctx->i32, "");

	ac_build_raw_tbuffer_store(ctx, rsrc, vdata, voffset, soffset,
				   ctx->i32_0, 1, dfmt, nfmt, glc, false,
				   writeonly_memory);
}
/**
 * Set range metadata on an instruction.  This can only be used on load and
 * call instructions.  If you know an instruction can only produce the values
 * 0, 1, 2, you would do set_range_metadata(value, 0, 3);
 * \p lo is the minimum value inclusive.
 * \p hi is the maximum value exclusive.
 */
static void set_range_metadata(struct ac_llvm_context *ctx,
			       LLVMValueRef value, unsigned lo, unsigned hi)
{
	LLVMValueRef range_md, md_args[2];
	LLVMTypeRef type = LLVMTypeOf(value);
	LLVMContextRef context = LLVMGetTypeContext(type);

	md_args[0] = LLVMConstInt(type, lo, false);
	md_args[1] = LLVMConstInt(type, hi, false);
	range_md = LLVMMDNodeInContext(context, md_args, 2);
	LLVMSetMetadata(value, ctx->range_md_kind, range_md);
}

LLVMValueRef
ac_get_thread_id(struct ac_llvm_context *ctx)
{
	LLVMValueRef tid;

	LLVMValueRef tid_args[2];
	tid_args[0] = LLVMConstInt(ctx->i32, 0xffffffff, false);
	tid_args[1] = ctx->i32_0;
	tid_args[1] = ac_build_intrinsic(ctx,
					 "llvm.amdgcn.mbcnt.lo", ctx->i32,
					 tid_args, 2, AC_FUNC_ATTR_READNONE);

	tid = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi",
				 ctx->i32, tid_args,
				 2, AC_FUNC_ATTR_READNONE);
	set_range_metadata(ctx, tid, 0, 64);
	return tid;
}

/*
 * SI implements derivatives using the local data store (LDS)
 * All writes to the LDS happen in all executing threads at
 * the same time. TID is the Thread ID for the current
 * thread and is a value between 0 and 63, representing
 * the thread's position in the wavefront.
 *
 * For the pixel shader threads are grouped into quads of four pixels.
 * The TIDs of the pixels of a quad are:
 *
 *  +------+------+
 *  |4n + 0|4n + 1|
 *  +------+------+
 *  |4n + 2|4n + 3|
 *  +------+------+
 *
 * So, masking the TID with 0xfffffffc yields the TID of the top left pixel
 * of the quad, masking with 0xfffffffd yields the TID of the top pixel of
 * the current pixel's column, and masking with 0xfffffffe yields the TID
 * of the left pixel of the current pixel's row.
 *
 * Adding 1 yields the TID of the pixel to the right of the left pixel, and
 * adding 2 yields the TID of the pixel below the top pixel.
 */
LLVMValueRef
ac_build_ddxy(struct ac_llvm_context *ctx,
	      uint32_t mask,
	      int idx,
	      LLVMValueRef val)
{
	unsigned tl_lanes[4], trbl_lanes[4];
	LLVMValueRef tl, trbl;
	LLVMValueRef result;

	for (unsigned i = 0; i < 4; ++i) {
		tl_lanes[i] = i & mask;
		trbl_lanes[i] = (i & mask) + idx;
	}

	tl = ac_build_quad_swizzle(ctx, val,
				   tl_lanes[0], tl_lanes[1],
				   tl_lanes[2], tl_lanes[3]);
	trbl = ac_build_quad_swizzle(ctx, val,
				     trbl_lanes[0], trbl_lanes[1],
				     trbl_lanes[2], trbl_lanes[3]);

	tl = LLVMBuildBitCast(ctx->builder, tl, ctx->f32, "");
	trbl = LLVMBuildBitCast(ctx->builder, trbl, ctx->f32, "");
	result = LLVMBuildFSub(ctx->builder, trbl, tl, "");

	result = ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.f32", ctx->f32,
				    &result, 1, 0);

	return result;
}

void
ac_build_sendmsg(struct ac_llvm_context *ctx,
		 uint32_t msg,
		 LLVMValueRef wave_id)
{
	LLVMValueRef args[2];
	args[0] = LLVMConstInt(ctx->i32, msg, false);
	args[1] = wave_id;
	ac_build_intrinsic(ctx, "llvm.amdgcn.s.sendmsg", ctx->voidt, args, 2, 0);
}

LLVMValueRef
ac_build_imsb(struct ac_llvm_context *ctx,
	      LLVMValueRef arg,
	      LLVMTypeRef dst_type)
{
	LLVMValueRef msb = ac_build_intrinsic(ctx, "llvm.amdgcn.sffbh.i32",
					      dst_type, &arg, 1,
					      AC_FUNC_ATTR_READNONE);

	/* The HW returns the last bit index from MSB, but NIR/TGSI wants
	 * the index from LSB. Invert it by doing "31 - msb". */
	msb = LLVMBuildSub(ctx->builder, LLVMConstInt(ctx->i32, 31, false),
			   msb, "");

	LLVMValueRef all_ones = LLVMConstInt(ctx->i32, -1, true);
	LLVMValueRef cond = LLVMBuildOr(ctx->builder,
					LLVMBuildICmp(ctx->builder, LLVMIntEQ,
						      arg, ctx->i32_0, ""),
					LLVMBuildICmp(ctx->builder, LLVMIntEQ,
						      arg, all_ones, ""), "");

	return LLVMBuildSelect(ctx->builder, cond, all_ones, msb, "");
}

LLVMValueRef
ac_build_umsb(struct ac_llvm_context *ctx,
	      LLVMValueRef arg,
	      LLVMTypeRef dst_type)
{
	const char *intrin_name;
	LLVMTypeRef type;
	LLVMValueRef highest_bit;
	LLVMValueRef zero;
	unsigned bitsize;

	bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(arg));
	switch (bitsize) {
	case 64:
		intrin_name = "llvm.ctlz.i64";
		type = ctx->i64;
		highest_bit = LLVMConstInt(ctx->i64, 63, false);
		zero = ctx->i64_0;
		break;
	case 32:
		intrin_name = "llvm.ctlz.i32";
		type = ctx->i32;
		highest_bit = LLVMConstInt(ctx->i32, 31, false);
		zero = ctx->i32_0;
		break;
	case 16:
		intrin_name = "llvm.ctlz.i16";
		type = ctx->i16;
		highest_bit = LLVMConstInt(ctx->i16, 15, false);
		zero = ctx->i16_0;
		break;
	case 8:
		intrin_name = "llvm.ctlz.i8";
		type = ctx->i8;
		highest_bit = LLVMConstInt(ctx->i8, 7, false);
		zero = ctx->i8_0;
		break;
	default:
		unreachable(!"invalid bitsize");
		break;
	}

	LLVMValueRef params[2] = {
		arg,
		ctx->i1true,
	};

	LLVMValueRef msb = ac_build_intrinsic(ctx, intrin_name, type,
					      params, 2,
					      AC_FUNC_ATTR_READNONE);

	/* The HW returns the last bit index from MSB, but TGSI/NIR wants
	 * the index from LSB. Invert it by doing "31 - msb". */
	msb = LLVMBuildSub(ctx->builder, highest_bit, msb, "");

	if (bitsize == 64) {
		msb = LLVMBuildTrunc(ctx->builder, msb, ctx->i32, "");
	} else if (bitsize < 32) {
		msb = LLVMBuildSExt(ctx->builder, msb, ctx->i32, "");
	}

	/* check for zero */
	return LLVMBuildSelect(ctx->builder,
			       LLVMBuildICmp(ctx->builder, LLVMIntEQ, arg, zero, ""),
			       LLVMConstInt(ctx->i32, -1, true), msb, "");
}

LLVMValueRef ac_build_fmin(struct ac_llvm_context *ctx, LLVMValueRef a,
			   LLVMValueRef b)
{
	char name[64];
	snprintf(name, sizeof(name), "llvm.minnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
	LLVMValueRef args[2] = {a, b};
	return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
				  AC_FUNC_ATTR_READNONE);
}

LLVMValueRef ac_build_fmax(struct ac_llvm_context *ctx, LLVMValueRef a,
			   LLVMValueRef b)
{
	char name[64];
	snprintf(name, sizeof(name), "llvm.maxnum.f%d", ac_get_elem_bits(ctx, LLVMTypeOf(a)));
	LLVMValueRef args[2] = {a, b};
	return ac_build_intrinsic(ctx, name, LLVMTypeOf(a), args, 2,
				  AC_FUNC_ATTR_READNONE);
}

LLVMValueRef ac_build_imin(struct ac_llvm_context *ctx, LLVMValueRef a,
			   LLVMValueRef b)
{
	LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSLE, a, b, "");
	return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
}

LLVMValueRef ac_build_imax(struct ac_llvm_context *ctx, LLVMValueRef a,
			   LLVMValueRef b)
{
	LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, a, b, "");
	return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
}

LLVMValueRef ac_build_umin(struct ac_llvm_context *ctx, LLVMValueRef a,
			   LLVMValueRef b)
{
	LLVMValueRef cmp = LLVMBuildICmp(ctx->builder, LLVMIntULE, a, b, "");
	return LLVMBuildSelect(ctx->builder, cmp, a, b, "");
}

LLVMValueRef ac_build_clamp(struct ac_llvm_context *ctx, LLVMValueRef value)
{
	LLVMTypeRef t = LLVMTypeOf(value);
	return ac_build_fmin(ctx, ac_build_fmax(ctx, value, LLVMConstReal(t, 0.0)),
			     LLVMConstReal(t, 1.0));
}

void ac_build_export(struct ac_llvm_context *ctx, struct ac_export_args *a)
{
	LLVMValueRef args[9];

	args[0] = LLVMConstInt(ctx->i32, a->target, 0);
	args[1] = LLVMConstInt(ctx->i32, a->enabled_channels, 0);

	if (a->compr) {
		LLVMTypeRef i16 = LLVMInt16TypeInContext(ctx->context);
		LLVMTypeRef v2i16 = LLVMVectorType(i16, 2);

		args[2] = LLVMBuildBitCast(ctx->builder, a->out[0],
				v2i16, "");
		args[3] = LLVMBuildBitCast(ctx->builder, a->out[1],
				v2i16, "");
		args[4] = LLVMConstInt(ctx->i1, a->done, 0);
		args[5] = LLVMConstInt(ctx->i1, a->valid_mask, 0);

		ac_build_intrinsic(ctx, "llvm.amdgcn.exp.compr.v2i16",
				   ctx->voidt, args, 6, 0);
	} else {
		args[2] = a->out[0];
		args[3] = a->out[1];
		args[4] = a->out[2];
		args[5] = a->out[3];
		args[6] = LLVMConstInt(ctx->i1, a->done, 0);
		args[7] = LLVMConstInt(ctx->i1, a->valid_mask, 0);

		ac_build_intrinsic(ctx, "llvm.amdgcn.exp.f32",
				   ctx->voidt, args, 8, 0);
	}
}

void ac_build_export_null(struct ac_llvm_context *ctx)
{
	struct ac_export_args args;

	args.enabled_channels = 0x0; /* enabled channels */
	args.valid_mask = 1; /* whether the EXEC mask is valid */
	args.done = 1; /* DONE bit */
	args.target = V_008DFC_SQ_EXP_NULL;
	args.compr = 0; /* COMPR flag (0 = 32-bit export) */
	args.out[0] = LLVMGetUndef(ctx->f32); /* R */
	args.out[1] = LLVMGetUndef(ctx->f32); /* G */
	args.out[2] = LLVMGetUndef(ctx->f32); /* B */
	args.out[3] = LLVMGetUndef(ctx->f32); /* A */

	ac_build_export(ctx, &args);
}

static unsigned ac_num_coords(enum ac_image_dim dim)
{
	switch (dim) {
	case ac_image_1d:
		return 1;
	case ac_image_2d:
	case ac_image_1darray:
		 return 2;
	case ac_image_3d:
	case ac_image_cube:
	case ac_image_2darray:
	case ac_image_2dmsaa:
		return 3;
	case ac_image_2darraymsaa:
		return 4;
	default:
		unreachable("ac_num_coords: bad dim");
	}
}

static unsigned ac_num_derivs(enum ac_image_dim dim)
{
	switch (dim) {
	case ac_image_1d:
	case ac_image_1darray:
		return 2;
	case ac_image_2d:
	case ac_image_2darray:
	case ac_image_cube:
		return 4;
	case ac_image_3d:
		return 6;
	case ac_image_2dmsaa:
	case ac_image_2darraymsaa:
	default:
		unreachable("derivatives not supported");
	}
}

static const char *get_atomic_name(enum ac_atomic_op op)
{
	switch (op) {
	case ac_atomic_swap: return "swap";
	case ac_atomic_add: return "add";
	case ac_atomic_sub: return "sub";
	case ac_atomic_smin: return "smin";
	case ac_atomic_umin: return "umin";
	case ac_atomic_smax: return "smax";
	case ac_atomic_umax: return "umax";
	case ac_atomic_and: return "and";
	case ac_atomic_or: return "or";
	case ac_atomic_xor: return "xor";
	}
	unreachable("bad atomic op");
}

LLVMValueRef ac_build_image_opcode(struct ac_llvm_context *ctx,
				   struct ac_image_args *a)
{
	const char *overload[3] = { "", "", "" };
	unsigned num_overloads = 0;
	LLVMValueRef args[18];
	unsigned num_args = 0;
	enum ac_image_dim dim = a->dim;

	assert(!a->lod || a->lod == ctx->i32_0 || a->lod == ctx->f32_0 ||
	       !a->level_zero);
	assert((a->opcode != ac_image_get_resinfo && a->opcode != ac_image_load_mip &&
		a->opcode != ac_image_store_mip) ||
	       a->lod);
	assert(a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
	       (!a->compare && !a->offset));
	assert((a->opcode == ac_image_sample || a->opcode == ac_image_gather4 ||
		a->opcode == ac_image_get_lod) ||
	       !a->bias);
	assert((a->bias ? 1 : 0) +
	       (a->lod ? 1 : 0) +
	       (a->level_zero ? 1 : 0) +
	       (a->derivs[0] ? 1 : 0) <= 1);

	if (a->opcode == ac_image_get_lod) {
		switch (dim) {
		case ac_image_1darray:
			dim = ac_image_1d;
			break;
		case ac_image_2darray:
		case ac_image_cube:
			dim = ac_image_2d;
			break;
		default:
			break;
		}
	}

	bool sample = a->opcode == ac_image_sample ||
		      a->opcode == ac_image_gather4 ||
		      a->opcode == ac_image_get_lod;
	bool atomic = a->opcode == ac_image_atomic ||
		      a->opcode == ac_image_atomic_cmpswap;
	LLVMTypeRef coord_type = sample ? ctx->f32 : ctx->i32;

	if (atomic || a->opcode == ac_image_store || a->opcode == ac_image_store_mip) {
		args[num_args++] = a->data[0];
		if (a->opcode == ac_image_atomic_cmpswap)
			args[num_args++] = a->data[1];
	}

	if (!atomic)
		args[num_args++] = LLVMConstInt(ctx->i32, a->dmask, false);

	if (a->offset)
		args[num_args++] = ac_to_integer(ctx, a->offset);
	if (a->bias) {
		args[num_args++] = ac_to_float(ctx, a->bias);
		overload[num_overloads++] = ".f32";
	}
	if (a->compare)
		args[num_args++] = ac_to_float(ctx, a->compare);
	if (a->derivs[0]) {
		unsigned count = ac_num_derivs(dim);
		for (unsigned i = 0; i < count; ++i)
			args[num_args++] = ac_to_float(ctx, a->derivs[i]);
		overload[num_overloads++] = ".f32";
	}
	unsigned num_coords =
		a->opcode != ac_image_get_resinfo ? ac_num_coords(dim) : 0;
	for (unsigned i = 0; i < num_coords; ++i)
		args[num_args++] = LLVMBuildBitCast(ctx->builder, a->coords[i], coord_type, "");
	if (a->lod)
		args[num_args++] = LLVMBuildBitCast(ctx->builder, a->lod, coord_type, "");
	overload[num_overloads++] = sample ? ".f32" : ".i32";

	args[num_args++] = a->resource;
	if (sample) {
		args[num_args++] = a->sampler;
		args[num_args++] = LLVMConstInt(ctx->i1, a->unorm, false);
	}

	args[num_args++] = ctx->i32_0; /* texfailctrl */
	args[num_args++] = LLVMConstInt(ctx->i32, a->cache_policy, false);

	const char *name;
	const char *atomic_subop = "";
	switch (a->opcode) {
	case ac_image_sample: name = "sample"; break;
	case ac_image_gather4: name = "gather4"; break;
	case ac_image_load: name = "load"; break;
	case ac_image_load_mip: name = "load.mip"; break;
	case ac_image_store: name = "store"; break;
	case ac_image_store_mip: name = "store.mip"; break;
	case ac_image_atomic:
		name = "atomic.";
		atomic_subop = get_atomic_name(a->atomic);
		break;
	case ac_image_atomic_cmpswap:
		name = "atomic.";
		atomic_subop = "cmpswap";
		break;
	case ac_image_get_lod: name = "getlod"; break;
	case ac_image_get_resinfo: name = "getresinfo"; break;
	default: unreachable("invalid image opcode");
	}

	const char *dimname;
	switch (dim) {
	case ac_image_1d: dimname = "1d"; break;
	case ac_image_2d: dimname = "2d"; break;
	case ac_image_3d: dimname = "3d"; break;
	case ac_image_cube: dimname = "cube"; break;
	case ac_image_1darray: dimname = "1darray"; break;
	case ac_image_2darray: dimname = "2darray"; break;
	case ac_image_2dmsaa: dimname = "2dmsaa"; break;
	case ac_image_2darraymsaa: dimname = "2darraymsaa"; break;
	default: unreachable("invalid dim");
	}

	bool lod_suffix =
		a->lod && (a->opcode == ac_image_sample || a->opcode == ac_image_gather4);
	char intr_name[96];
	snprintf(intr_name, sizeof(intr_name),
		 "llvm.amdgcn.image.%s%s" /* base name */
		 "%s%s%s" /* sample/gather modifiers */
		 ".%s.%s%s%s%s", /* dimension and type overloads */
		 name, atomic_subop,
		 a->compare ? ".c" : "",
		 a->bias ? ".b" :
		 lod_suffix ? ".l" :
		 a->derivs[0] ? ".d" :
		 a->level_zero ? ".lz" : "",
		 a->offset ? ".o" : "",
		 dimname,
		 atomic ? "i32" : "v4f32",
		 overload[0], overload[1], overload[2]);

	LLVMTypeRef retty;
	if (atomic)
		retty = ctx->i32;
	else if (a->opcode == ac_image_store || a->opcode == ac_image_store_mip)
		retty = ctx->voidt;
	else
		retty = ctx->v4f32;

	LLVMValueRef result =
		ac_build_intrinsic(ctx, intr_name, retty, args, num_args,
				   a->attributes);
	if (!sample && retty == ctx->v4f32) {
		result = LLVMBuildBitCast(ctx->builder, result,
					  ctx->v4i32, "");
	}
	return result;
}

LLVMValueRef ac_build_cvt_pkrtz_f16(struct ac_llvm_context *ctx,
				    LLVMValueRef args[2])
{
	LLVMTypeRef v2f16 =
		LLVMVectorType(LLVMHalfTypeInContext(ctx->context), 2);

	return ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pkrtz", v2f16,
				  args, 2, AC_FUNC_ATTR_READNONE);
}

LLVMValueRef ac_build_cvt_pknorm_i16(struct ac_llvm_context *ctx,
				     LLVMValueRef args[2])
{
	LLVMValueRef res =
		ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.i16",
				   ctx->v2i16, args, 2,
				   AC_FUNC_ATTR_READNONE);
	return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
}

LLVMValueRef ac_build_cvt_pknorm_u16(struct ac_llvm_context *ctx,
				     LLVMValueRef args[2])
{
	LLVMValueRef res =
		ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pknorm.u16",
				   ctx->v2i16, args, 2,
				   AC_FUNC_ATTR_READNONE);
	return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
}

/* The 8-bit and 10-bit clamping is for HW workarounds. */
LLVMValueRef ac_build_cvt_pk_i16(struct ac_llvm_context *ctx,
				 LLVMValueRef args[2], unsigned bits, bool hi)
{
	assert(bits == 8 || bits == 10 || bits == 16);

	LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
		bits == 8 ? 127 : bits == 10 ? 511 : 32767, 0);
	LLVMValueRef min_rgb = LLVMConstInt(ctx->i32,
		bits == 8 ? -128 : bits == 10 ? -512 : -32768, 0);
	LLVMValueRef max_alpha =
		bits != 10 ? max_rgb : ctx->i32_1;
	LLVMValueRef min_alpha =
		bits != 10 ? min_rgb : LLVMConstInt(ctx->i32, -2, 0);

	/* Clamp. */
	if (bits != 16) {
		for (int i = 0; i < 2; i++) {
			bool alpha = hi && i == 1;
			args[i] = ac_build_imin(ctx, args[i],
						alpha ? max_alpha : max_rgb);
			args[i] = ac_build_imax(ctx, args[i],
						alpha ? min_alpha : min_rgb);
		}
	}

	LLVMValueRef res =
		ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.i16",
				   ctx->v2i16, args, 2,
				   AC_FUNC_ATTR_READNONE);
	return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
}

/* The 8-bit and 10-bit clamping is for HW workarounds. */
LLVMValueRef ac_build_cvt_pk_u16(struct ac_llvm_context *ctx,
				 LLVMValueRef args[2], unsigned bits, bool hi)
{
	assert(bits == 8 || bits == 10 || bits == 16);

	LLVMValueRef max_rgb = LLVMConstInt(ctx->i32,
		bits == 8 ? 255 : bits == 10 ? 1023 : 65535, 0);
	LLVMValueRef max_alpha =
		bits != 10 ? max_rgb : LLVMConstInt(ctx->i32, 3, 0);

	/* Clamp. */
	if (bits != 16) {
		for (int i = 0; i < 2; i++) {
			bool alpha = hi && i == 1;
			args[i] = ac_build_umin(ctx, args[i],
						alpha ? max_alpha : max_rgb);
		}
	}

	LLVMValueRef res =
		ac_build_intrinsic(ctx, "llvm.amdgcn.cvt.pk.u16",
				   ctx->v2i16, args, 2,
				   AC_FUNC_ATTR_READNONE);
	return LLVMBuildBitCast(ctx->builder, res, ctx->i32, "");
}

LLVMValueRef ac_build_wqm_vote(struct ac_llvm_context *ctx, LLVMValueRef i1)
{
	return ac_build_intrinsic(ctx, "llvm.amdgcn.wqm.vote", ctx->i1,
				  &i1, 1, AC_FUNC_ATTR_READNONE);
}

void ac_build_kill_if_false(struct ac_llvm_context *ctx, LLVMValueRef i1)
{
	ac_build_intrinsic(ctx, "llvm.amdgcn.kill", ctx->voidt,
			   &i1, 1, 0);
}

LLVMValueRef ac_build_bfe(struct ac_llvm_context *ctx, LLVMValueRef input,
			  LLVMValueRef offset, LLVMValueRef width,
			  bool is_signed)
{
	LLVMValueRef args[] = {
		input,
		offset,
		width,
	};

	return ac_build_intrinsic(ctx,
				  is_signed ? "llvm.amdgcn.sbfe.i32" :
					      "llvm.amdgcn.ubfe.i32",
				  ctx->i32, args, 3,
				  AC_FUNC_ATTR_READNONE);
}

LLVMValueRef ac_build_imad(struct ac_llvm_context *ctx, LLVMValueRef s0,
			   LLVMValueRef s1, LLVMValueRef s2)
{
	return LLVMBuildAdd(ctx->builder,
			    LLVMBuildMul(ctx->builder, s0, s1, ""), s2, "");
}

LLVMValueRef ac_build_fmad(struct ac_llvm_context *ctx, LLVMValueRef s0,
			   LLVMValueRef s1, LLVMValueRef s2)
{
	return LLVMBuildFAdd(ctx->builder,
			     LLVMBuildFMul(ctx->builder, s0, s1, ""), s2, "");
}

void ac_build_waitcnt(struct ac_llvm_context *ctx, unsigned simm16)
{
	LLVMValueRef args[1] = {
		LLVMConstInt(ctx->i32, simm16, false),
	};
	ac_build_intrinsic(ctx, "llvm.amdgcn.s.waitcnt",
			   ctx->voidt, args, 1, 0);
}

LLVMValueRef ac_build_fmed3(struct ac_llvm_context *ctx, LLVMValueRef src0,
			    LLVMValueRef src1, LLVMValueRef src2,
			    unsigned bitsize)
{
	LLVMTypeRef type;
	char *intr;

	if (bitsize == 16) {
		intr = "llvm.amdgcn.fmed3.f16";
		type = ctx->f16;
	} else if (bitsize == 32) {
		intr = "llvm.amdgcn.fmed3.f32";
		type = ctx->f32;
	} else {
		intr = "llvm.amdgcn.fmed3.f64";
		type = ctx->f64;
	}

	LLVMValueRef params[] = {
		src0,
		src1,
		src2,
	};
	return ac_build_intrinsic(ctx, intr, type, params, 3,
				  AC_FUNC_ATTR_READNONE);
}

LLVMValueRef ac_build_fract(struct ac_llvm_context *ctx, LLVMValueRef src0,
			    unsigned bitsize)
{
	LLVMTypeRef type;
	char *intr;

	if (bitsize == 16) {
		intr = "llvm.amdgcn.fract.f16";
		type = ctx->f16;
	} else if (bitsize == 32) {
		intr = "llvm.amdgcn.fract.f32";
		type = ctx->f32;
	} else {
		intr = "llvm.amdgcn.fract.f64";
		type = ctx->f64;
	}

	LLVMValueRef params[] = {
		src0,
	};
	return ac_build_intrinsic(ctx, intr, type, params, 1,
				  AC_FUNC_ATTR_READNONE);
}

LLVMValueRef ac_build_isign(struct ac_llvm_context *ctx, LLVMValueRef src0,
			    unsigned bitsize)
{
	LLVMTypeRef type = LLVMIntTypeInContext(ctx->context, bitsize);
	LLVMValueRef zero = LLVMConstInt(type, 0, false);
	LLVMValueRef one = LLVMConstInt(type, 1, false);

	LLVMValueRef cmp, val;
	cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGT, src0, zero, "");
	val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
	cmp = LLVMBuildICmp(ctx->builder, LLVMIntSGE, val, zero, "");
	val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstInt(type, -1, true), "");
	return val;
}

LLVMValueRef ac_build_fsign(struct ac_llvm_context *ctx, LLVMValueRef src0,
			    unsigned bitsize)
{
	LLVMValueRef cmp, val, zero, one;
	LLVMTypeRef type;

	if (bitsize == 16) {
		type = ctx->f16;
		zero = ctx->f16_0;
		one = ctx->f16_1;
	} else if (bitsize == 32) {
		type = ctx->f32;
		zero = ctx->f32_0;
		one = ctx->f32_1;
	} else {
		type = ctx->f64;
		zero = ctx->f64_0;
		one = ctx->f64_1;
	}

	cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGT, src0, zero, "");
	val = LLVMBuildSelect(ctx->builder, cmp, one, src0, "");
	cmp = LLVMBuildFCmp(ctx->builder, LLVMRealOGE, val, zero, "");
	val = LLVMBuildSelect(ctx->builder, cmp, val, LLVMConstReal(type, -1.0), "");
	return val;
}

LLVMValueRef ac_build_bit_count(struct ac_llvm_context *ctx, LLVMValueRef src0)
{
	LLVMValueRef result;
	unsigned bitsize;

	bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));

	switch (bitsize) {
	case 64:
		result = ac_build_intrinsic(ctx, "llvm.ctpop.i64", ctx->i64,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);

		result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
		break;
	case 32:
		result = ac_build_intrinsic(ctx, "llvm.ctpop.i32", ctx->i32,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);
		break;
	case 16:
		result = ac_build_intrinsic(ctx, "llvm.ctpop.i16", ctx->i16,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);

		result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
		break;
	case 8:
		result = ac_build_intrinsic(ctx, "llvm.ctpop.i8", ctx->i8,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);

		result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
		break;
	default:
		unreachable(!"invalid bitsize");
		break;
	}

	return result;
}

LLVMValueRef ac_build_bitfield_reverse(struct ac_llvm_context *ctx,
				       LLVMValueRef src0)
{
	LLVMValueRef result;
	unsigned bitsize;

	bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));

	switch (bitsize) {
	case 64:
		result = ac_build_intrinsic(ctx, "llvm.bitreverse.i64", ctx->i64,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);

		result = LLVMBuildTrunc(ctx->builder, result, ctx->i32, "");
		break;
	case 32:
		result = ac_build_intrinsic(ctx, "llvm.bitreverse.i32", ctx->i32,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);
		break;
	case 16:
		result = ac_build_intrinsic(ctx, "llvm.bitreverse.i16", ctx->i16,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);

		result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
		break;
	case 8:
		result = ac_build_intrinsic(ctx, "llvm.bitreverse.i8", ctx->i8,
					    (LLVMValueRef []) { src0 }, 1,
					    AC_FUNC_ATTR_READNONE);

		result = LLVMBuildZExt(ctx->builder, result, ctx->i32, "");
		break;
	default:
		unreachable(!"invalid bitsize");
		break;
	}

	return result;
}

#define AC_EXP_TARGET		0
#define AC_EXP_ENABLED_CHANNELS 1
#define AC_EXP_OUT0		2

enum ac_ir_type {
	AC_IR_UNDEF,
	AC_IR_CONST,
	AC_IR_VALUE,
};

struct ac_vs_exp_chan
{
	LLVMValueRef value;
	float const_float;
	enum ac_ir_type type;
};

struct ac_vs_exp_inst {
	unsigned offset;
	LLVMValueRef inst;
	struct ac_vs_exp_chan chan[4];
};

struct ac_vs_exports {
	unsigned num;
	struct ac_vs_exp_inst exp[VARYING_SLOT_MAX];
};

/* Return true if the PARAM export has been eliminated. */
static bool ac_eliminate_const_output(uint8_t *vs_output_param_offset,
				      uint32_t num_outputs,
				      struct ac_vs_exp_inst *exp)
{
	unsigned i, default_val; /* SPI_PS_INPUT_CNTL_i.DEFAULT_VAL */
	bool is_zero[4] = {}, is_one[4] = {};

	for (i = 0; i < 4; i++) {
		/* It's a constant expression. Undef outputs are eliminated too. */
		if (exp->chan[i].type == AC_IR_UNDEF) {
			is_zero[i] = true;
			is_one[i] = true;
		} else if (exp->chan[i].type == AC_IR_CONST) {
			if (exp->chan[i].const_float == 0)
				is_zero[i] = true;
			else if (exp->chan[i].const_float == 1)
				is_one[i] = true;
			else
				return false; /* other constant */
		} else
			return false;
	}

	/* Only certain combinations of 0 and 1 can be eliminated. */
	if (is_zero[0] && is_zero[1] && is_zero[2])
		default_val = is_zero[3] ? 0 : 1;
	else if (is_one[0] && is_one[1] && is_one[2])
		default_val = is_zero[3] ? 2 : 3;
	else
		return false;

	/* The PARAM export can be represented as DEFAULT_VAL. Kill it. */
	LLVMInstructionEraseFromParent(exp->inst);

	/* Change OFFSET to DEFAULT_VAL. */
	for (i = 0; i < num_outputs; i++) {
		if (vs_output_param_offset[i] == exp->offset) {
			vs_output_param_offset[i] =
				AC_EXP_PARAM_DEFAULT_VAL_0000 + default_val;
			break;
		}
	}
	return true;
}

static bool ac_eliminate_duplicated_output(struct ac_llvm_context *ctx,
					   uint8_t *vs_output_param_offset,
					   uint32_t num_outputs,
					   struct ac_vs_exports *processed,
				           struct ac_vs_exp_inst *exp)
{
	unsigned p, copy_back_channels = 0;

	/* See if the output is already in the list of processed outputs.
	 * The LLVMValueRef comparison relies on SSA.
	 */
	for (p = 0; p < processed->num; p++) {
		bool different = false;

		for (unsigned j = 0; j < 4; j++) {
			struct ac_vs_exp_chan *c1 = &processed->exp[p].chan[j];
			struct ac_vs_exp_chan *c2 = &exp->chan[j];

			/* Treat undef as a match. */
			if (c2->type == AC_IR_UNDEF)
				continue;

			/* If c1 is undef but c2 isn't, we can copy c2 to c1
			 * and consider the instruction duplicated.
			 */
			if (c1->type == AC_IR_UNDEF) {
				copy_back_channels |= 1 << j;
				continue;
			}

			/* Test whether the channels are not equal. */
			if (c1->type != c2->type ||
			    (c1->type == AC_IR_CONST &&
			     c1->const_float != c2->const_float) ||
			    (c1->type == AC_IR_VALUE &&
			     c1->value != c2->value)) {
				different = true;
				break;
			}
		}
		if (!different)
			break;

		copy_back_channels = 0;
	}
	if (p == processed->num)
		return false;

	/* If a match was found, but the matching export has undef where the new
	 * one has a normal value, copy the normal value to the undef channel.
	 */
	struct ac_vs_exp_inst *match = &processed->exp[p];

	/* Get current enabled channels mask. */
	LLVMValueRef arg = LLVMGetOperand(match->inst, AC_EXP_ENABLED_CHANNELS);
	unsigned enabled_channels = LLVMConstIntGetZExtValue(arg);

	while (copy_back_channels) {
		unsigned chan = u_bit_scan(&copy_back_channels);

		assert(match->chan[chan].type == AC_IR_UNDEF);
		LLVMSetOperand(match->inst, AC_EXP_OUT0 + chan,
			       exp->chan[chan].value);
		match->chan[chan] = exp->chan[chan];

		/* Update number of enabled channels because the original mask
		 * is not always 0xf.
		 */
		enabled_channels |= (1 << chan);
		LLVMSetOperand(match->inst, AC_EXP_ENABLED_CHANNELS,
			       LLVMConstInt(ctx->i32, enabled_channels, 0));
	}

	/* The PARAM export is duplicated. Kill it. */
	LLVMInstructionEraseFromParent(exp->inst);

	/* Change OFFSET to the matching export. */
	for (unsigned i = 0; i < num_outputs; i++) {
		if (vs_output_param_offset[i] == exp->offset) {
			vs_output_param_offset[i] = match->offset;
			break;
		}
	}
	return true;
}

void ac_optimize_vs_outputs(struct ac_llvm_context *ctx,
			    LLVMValueRef main_fn,
			    uint8_t *vs_output_param_offset,
			    uint32_t num_outputs,
			    uint8_t *num_param_exports)
{
	LLVMBasicBlockRef bb;
	bool removed_any = false;
	struct ac_vs_exports exports;

	exports.num = 0;

	/* Process all LLVM instructions. */
	bb = LLVMGetFirstBasicBlock(main_fn);
	while (bb) {
		LLVMValueRef inst = LLVMGetFirstInstruction(bb);

		while (inst) {
			LLVMValueRef cur = inst;
			inst = LLVMGetNextInstruction(inst);
			struct ac_vs_exp_inst exp;

			if (LLVMGetInstructionOpcode(cur) != LLVMCall)
				continue;

			LLVMValueRef callee = ac_llvm_get_called_value(cur);

			if (!ac_llvm_is_function(callee))
				continue;

			const char *name = LLVMGetValueName(callee);
			unsigned num_args = LLVMCountParams(callee);

			/* Check if this is an export instruction. */
			if ((num_args != 9 && num_args != 8) ||
			    (strcmp(name, "llvm.SI.export") &&
			     strcmp(name, "llvm.amdgcn.exp.f32")))
				continue;

			LLVMValueRef arg = LLVMGetOperand(cur, AC_EXP_TARGET);
			unsigned target = LLVMConstIntGetZExtValue(arg);

			if (target < V_008DFC_SQ_EXP_PARAM)
				continue;

			target -= V_008DFC_SQ_EXP_PARAM;

			/* Parse the instruction. */
			memset(&exp, 0, sizeof(exp));
			exp.offset = target;
			exp.inst = cur;

			for (unsigned i = 0; i < 4; i++) {
				LLVMValueRef v = LLVMGetOperand(cur, AC_EXP_OUT0 + i);

				exp.chan[i].value = v;

				if (LLVMIsUndef(v)) {
					exp.chan[i].type = AC_IR_UNDEF;
				} else if (LLVMIsAConstantFP(v)) {
					LLVMBool loses_info;
					exp.chan[i].type = AC_IR_CONST;
					exp.chan[i].const_float =
						LLVMConstRealGetDouble(v, &loses_info);
				} else {
					exp.chan[i].type = AC_IR_VALUE;
				}
			}

			/* Eliminate constant and duplicated PARAM exports. */
			if (ac_eliminate_const_output(vs_output_param_offset,
						      num_outputs, &exp) ||
			    ac_eliminate_duplicated_output(ctx,
							   vs_output_param_offset,
							   num_outputs, &exports,
							   &exp)) {
				removed_any = true;
			} else {
				exports.exp[exports.num++] = exp;
			}
		}
		bb = LLVMGetNextBasicBlock(bb);
	}

	/* Remove holes in export memory due to removed PARAM exports.
	 * This is done by renumbering all PARAM exports.
	 */
	if (removed_any) {
		uint8_t old_offset[VARYING_SLOT_MAX];
		unsigned out, i;

		/* Make a copy of the offsets. We need the old version while
		 * we are modifying some of them. */
		memcpy(old_offset, vs_output_param_offset,
		       sizeof(old_offset));

		for (i = 0; i < exports.num; i++) {
			unsigned offset = exports.exp[i].offset;

			/* Update vs_output_param_offset. Multiple outputs can
			 * have the same offset.
			 */
			for (out = 0; out < num_outputs; out++) {
				if (old_offset[out] == offset)
					vs_output_param_offset[out] = i;
			}

			/* Change the PARAM offset in the instruction. */
			LLVMSetOperand(exports.exp[i].inst, AC_EXP_TARGET,
				       LLVMConstInt(ctx->i32,
						    V_008DFC_SQ_EXP_PARAM + i, 0));
		}
		*num_param_exports = exports.num;
	}
}

void ac_init_exec_full_mask(struct ac_llvm_context *ctx)
{
	LLVMValueRef full_mask = LLVMConstInt(ctx->i64, ~0ull, 0);
	ac_build_intrinsic(ctx,
			   "llvm.amdgcn.init.exec", ctx->voidt,
			   &full_mask, 1, AC_FUNC_ATTR_CONVERGENT);
}

void ac_declare_lds_as_pointer(struct ac_llvm_context *ctx)
{
	unsigned lds_size = ctx->chip_class >= CIK ? 65536 : 32768;
	ctx->lds = LLVMBuildIntToPtr(ctx->builder, ctx->i32_0,
				     LLVMPointerType(LLVMArrayType(ctx->i32, lds_size / 4), AC_ADDR_SPACE_LDS),
				     "lds");
}

LLVMValueRef ac_lds_load(struct ac_llvm_context *ctx,
			 LLVMValueRef dw_addr)
{
	return ac_build_load(ctx, ctx->lds, dw_addr);
}

void ac_lds_store(struct ac_llvm_context *ctx,
		  LLVMValueRef dw_addr,
		  LLVMValueRef value)
{
	value = ac_to_integer(ctx, value);
	ac_build_indexed_store(ctx, ctx->lds,
			       dw_addr, value);
}

LLVMValueRef ac_find_lsb(struct ac_llvm_context *ctx,
			 LLVMTypeRef dst_type,
			 LLVMValueRef src0)
{
	unsigned src0_bitsize = ac_get_elem_bits(ctx, LLVMTypeOf(src0));
	const char *intrin_name;
	LLVMTypeRef type;
	LLVMValueRef zero;

	switch (src0_bitsize) {
	case 64:
		intrin_name = "llvm.cttz.i64";
		type = ctx->i64;
		zero = ctx->i64_0;
		break;
	case 32:
		intrin_name = "llvm.cttz.i32";
		type = ctx->i32;
		zero = ctx->i32_0;
		break;
	case 16:
		intrin_name = "llvm.cttz.i16";
		type = ctx->i16;
		zero = ctx->i16_0;
		break;
	case 8:
		intrin_name = "llvm.cttz.i8";
		type = ctx->i8;
		zero = ctx->i8_0;
		break;
	default:
		unreachable(!"invalid bitsize");
	}

	LLVMValueRef params[2] = {
		src0,

		/* The value of 1 means that ffs(x=0) = undef, so LLVM won't
		 * add special code to check for x=0. The reason is that
		 * the LLVM behavior for x=0 is different from what we
		 * need here. However, LLVM also assumes that ffs(x) is
		 * in [0, 31], but GLSL expects that ffs(0) = -1, so
		 * a conditional assignment to handle 0 is still required.
		 *
		 * The hardware already implements the correct behavior.
		 */
		ctx->i1true,
	};

	LLVMValueRef lsb = ac_build_intrinsic(ctx, intrin_name, type,
					      params, 2,
					      AC_FUNC_ATTR_READNONE);

	if (src0_bitsize == 64) {
		lsb = LLVMBuildTrunc(ctx->builder, lsb, ctx->i32, "");
	} else if (src0_bitsize < 32) {
		lsb = LLVMBuildSExt(ctx->builder, lsb, ctx->i32, "");
	}

	/* TODO: We need an intrinsic to skip this conditional. */
	/* Check for zero: */
	return LLVMBuildSelect(ctx->builder, LLVMBuildICmp(ctx->builder,
							   LLVMIntEQ, src0,
							   zero, ""),
			       LLVMConstInt(ctx->i32, -1, 0), lsb, "");
}

LLVMTypeRef ac_array_in_const_addr_space(LLVMTypeRef elem_type)
{
	return LLVMPointerType(LLVMArrayType(elem_type, 0),
			       AC_ADDR_SPACE_CONST);
}

LLVMTypeRef ac_array_in_const32_addr_space(LLVMTypeRef elem_type)
{
	return LLVMPointerType(LLVMArrayType(elem_type, 0),
			       AC_ADDR_SPACE_CONST_32BIT);
}

static struct ac_llvm_flow *
get_current_flow(struct ac_llvm_context *ctx)
{
	if (ctx->flow_depth > 0)
		return &ctx->flow[ctx->flow_depth - 1];
	return NULL;
}

static struct ac_llvm_flow *
get_innermost_loop(struct ac_llvm_context *ctx)
{
	for (unsigned i = ctx->flow_depth; i > 0; --i) {
		if (ctx->flow[i - 1].loop_entry_block)
			return &ctx->flow[i - 1];
	}
	return NULL;
}

static struct ac_llvm_flow *
push_flow(struct ac_llvm_context *ctx)
{
	struct ac_llvm_flow *flow;

	if (ctx->flow_depth >= ctx->flow_depth_max) {
		unsigned new_max = MAX2(ctx->flow_depth << 1,
					AC_LLVM_INITIAL_CF_DEPTH);

		ctx->flow = realloc(ctx->flow, new_max * sizeof(*ctx->flow));
		ctx->flow_depth_max = new_max;
	}

	flow = &ctx->flow[ctx->flow_depth];
	ctx->flow_depth++;

	flow->next_block = NULL;
	flow->loop_entry_block = NULL;
	return flow;
}

static void set_basicblock_name(LLVMBasicBlockRef bb, const char *base,
				int label_id)
{
	char buf[32];
	snprintf(buf, sizeof(buf), "%s%d", base, label_id);
	LLVMSetValueName(LLVMBasicBlockAsValue(bb), buf);
}

/* Append a basic block at the level of the parent flow.
 */
static LLVMBasicBlockRef append_basic_block(struct ac_llvm_context *ctx,
					    const char *name)
{
	assert(ctx->flow_depth >= 1);

	if (ctx->flow_depth >= 2) {
		struct ac_llvm_flow *flow = &ctx->flow[ctx->flow_depth - 2];

		return LLVMInsertBasicBlockInContext(ctx->context,
						     flow->next_block, name);
	}

	LLVMValueRef main_fn =
		LLVMGetBasicBlockParent(LLVMGetInsertBlock(ctx->builder));
	return LLVMAppendBasicBlockInContext(ctx->context, main_fn, name);
}

/* Emit a branch to the given default target for the current block if
 * applicable -- that is, if the current block does not already contain a
 * branch from a break or continue.
 */
static void emit_default_branch(LLVMBuilderRef builder,
				LLVMBasicBlockRef target)
{
	if (!LLVMGetBasicBlockTerminator(LLVMGetInsertBlock(builder)))
		 LLVMBuildBr(builder, target);
}

void ac_build_bgnloop(struct ac_llvm_context *ctx, int label_id)
{
	struct ac_llvm_flow *flow = push_flow(ctx);
	flow->loop_entry_block = append_basic_block(ctx, "LOOP");
	flow->next_block = append_basic_block(ctx, "ENDLOOP");
	set_basicblock_name(flow->loop_entry_block, "loop", label_id);
	LLVMBuildBr(ctx->builder, flow->loop_entry_block);
	LLVMPositionBuilderAtEnd(ctx->builder, flow->loop_entry_block);
}

void ac_build_break(struct ac_llvm_context *ctx)
{
	struct ac_llvm_flow *flow = get_innermost_loop(ctx);
	LLVMBuildBr(ctx->builder, flow->next_block);
}

void ac_build_continue(struct ac_llvm_context *ctx)
{
	struct ac_llvm_flow *flow = get_innermost_loop(ctx);
	LLVMBuildBr(ctx->builder, flow->loop_entry_block);
}

void ac_build_else(struct ac_llvm_context *ctx, int label_id)
{
	struct ac_llvm_flow *current_branch = get_current_flow(ctx);
	LLVMBasicBlockRef endif_block;

	assert(!current_branch->loop_entry_block);

	endif_block = append_basic_block(ctx, "ENDIF");
	emit_default_branch(ctx->builder, endif_block);

	LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
	set_basicblock_name(current_branch->next_block, "else", label_id);

	current_branch->next_block = endif_block;
}

void ac_build_endif(struct ac_llvm_context *ctx, int label_id)
{
	struct ac_llvm_flow *current_branch = get_current_flow(ctx);

	assert(!current_branch->loop_entry_block);

	emit_default_branch(ctx->builder, current_branch->next_block);
	LLVMPositionBuilderAtEnd(ctx->builder, current_branch->next_block);
	set_basicblock_name(current_branch->next_block, "endif", label_id);

	ctx->flow_depth--;
}

void ac_build_endloop(struct ac_llvm_context *ctx, int label_id)
{
	struct ac_llvm_flow *current_loop = get_current_flow(ctx);

	assert(current_loop->loop_entry_block);

	emit_default_branch(ctx->builder, current_loop->loop_entry_block);

	LLVMPositionBuilderAtEnd(ctx->builder, current_loop->next_block);
	set_basicblock_name(current_loop->next_block, "endloop", label_id);
	ctx->flow_depth--;
}

void ac_build_ifcc(struct ac_llvm_context *ctx, LLVMValueRef cond, int label_id)
{
	struct ac_llvm_flow *flow = push_flow(ctx);
	LLVMBasicBlockRef if_block;

	if_block = append_basic_block(ctx, "IF");
	flow->next_block = append_basic_block(ctx, "ELSE");
	set_basicblock_name(if_block, "if", label_id);
	LLVMBuildCondBr(ctx->builder, cond, if_block, flow->next_block);
	LLVMPositionBuilderAtEnd(ctx->builder, if_block);
}

void ac_build_if(struct ac_llvm_context *ctx, LLVMValueRef value,
		 int label_id)
{
	LLVMValueRef cond = LLVMBuildFCmp(ctx->builder, LLVMRealUNE,
					  value, ctx->f32_0, "");
	ac_build_ifcc(ctx, cond, label_id);
}

void ac_build_uif(struct ac_llvm_context *ctx, LLVMValueRef value,
		  int label_id)
{
	LLVMValueRef cond = LLVMBuildICmp(ctx->builder, LLVMIntNE,
					  ac_to_integer(ctx, value),
					  ctx->i32_0, "");
	ac_build_ifcc(ctx, cond, label_id);
}

LLVMValueRef ac_build_alloca_undef(struct ac_llvm_context *ac, LLVMTypeRef type,
			     const char *name)
{
	LLVMBuilderRef builder = ac->builder;
	LLVMBasicBlockRef current_block = LLVMGetInsertBlock(builder);
	LLVMValueRef function = LLVMGetBasicBlockParent(current_block);
	LLVMBasicBlockRef first_block = LLVMGetEntryBasicBlock(function);
	LLVMValueRef first_instr = LLVMGetFirstInstruction(first_block);
	LLVMBuilderRef first_builder = LLVMCreateBuilderInContext(ac->context);
	LLVMValueRef res;

	if (first_instr) {
		LLVMPositionBuilderBefore(first_builder, first_instr);
	} else {
		LLVMPositionBuilderAtEnd(first_builder, first_block);
	}

	res = LLVMBuildAlloca(first_builder, type, name);
	LLVMDisposeBuilder(first_builder);
	return res;
}

LLVMValueRef ac_build_alloca(struct ac_llvm_context *ac,
				   LLVMTypeRef type, const char *name)
{
	LLVMValueRef ptr = ac_build_alloca_undef(ac, type, name);
	LLVMBuildStore(ac->builder, LLVMConstNull(type), ptr);
	return ptr;
}

LLVMValueRef ac_cast_ptr(struct ac_llvm_context *ctx, LLVMValueRef ptr,
                         LLVMTypeRef type)
{
	int addr_space = LLVMGetPointerAddressSpace(LLVMTypeOf(ptr));
	return LLVMBuildBitCast(ctx->builder, ptr,
	                        LLVMPointerType(type, addr_space), "");
}

LLVMValueRef ac_trim_vector(struct ac_llvm_context *ctx, LLVMValueRef value,
			    unsigned count)
{
	unsigned num_components = ac_get_llvm_num_components(value);
	if (count == num_components)
		return value;

	LLVMValueRef masks[MAX2(count, 2)];
	masks[0] = ctx->i32_0;
	masks[1] = ctx->i32_1;
	for (unsigned i = 2; i < count; i++)
		masks[i] = LLVMConstInt(ctx->i32, i, false);

	if (count == 1)
		return LLVMBuildExtractElement(ctx->builder, value, masks[0],
		                               "");

	LLVMValueRef swizzle = LLVMConstVector(masks, count);
	return LLVMBuildShuffleVector(ctx->builder, value, value, swizzle, "");
}

LLVMValueRef ac_unpack_param(struct ac_llvm_context *ctx, LLVMValueRef param,
			     unsigned rshift, unsigned bitwidth)
{
	LLVMValueRef value = param;
	if (rshift)
		value = LLVMBuildLShr(ctx->builder, value,
				      LLVMConstInt(ctx->i32, rshift, false), "");

	if (rshift + bitwidth < 32) {
		unsigned mask = (1 << bitwidth) - 1;
		value = LLVMBuildAnd(ctx->builder, value,
				     LLVMConstInt(ctx->i32, mask, false), "");
	}
	return value;
}

/* Adjust the sample index according to FMASK.
 *
 * For uncompressed MSAA surfaces, FMASK should return 0x76543210,
 * which is the identity mapping. Each nibble says which physical sample
 * should be fetched to get that sample.
 *
 * For example, 0x11111100 means there are only 2 samples stored and
 * the second sample covers 3/4 of the pixel. When reading samples 0
 * and 1, return physical sample 0 (determined by the first two 0s
 * in FMASK), otherwise return physical sample 1.
 *
 * The sample index should be adjusted as follows:
 *   addr[sample_index] = (fmask >> (addr[sample_index] * 4)) & 0xF;
 */
void ac_apply_fmask_to_sample(struct ac_llvm_context *ac, LLVMValueRef fmask,
			      LLVMValueRef *addr, bool is_array_tex)
{
	struct ac_image_args fmask_load = {};
	fmask_load.opcode = ac_image_load;
	fmask_load.resource = fmask;
	fmask_load.dmask = 0xf;
	fmask_load.dim = is_array_tex ? ac_image_2darray : ac_image_2d;

	fmask_load.coords[0] = addr[0];
	fmask_load.coords[1] = addr[1];
	if (is_array_tex)
		fmask_load.coords[2] = addr[2];

	LLVMValueRef fmask_value = ac_build_image_opcode(ac, &fmask_load);
	fmask_value = LLVMBuildExtractElement(ac->builder, fmask_value,
					      ac->i32_0, "");

	/* Apply the formula. */
	unsigned sample_chan = is_array_tex ? 3 : 2;
	LLVMValueRef final_sample;
	final_sample = LLVMBuildMul(ac->builder, addr[sample_chan],
				    LLVMConstInt(ac->i32, 4, 0), "");
	final_sample = LLVMBuildLShr(ac->builder, fmask_value, final_sample, "");
	/* Mask the sample index by 0x7, because 0x8 means an unknown value
	 * with EQAA, so those will map to 0. */
	final_sample = LLVMBuildAnd(ac->builder, final_sample,
				    LLVMConstInt(ac->i32, 0x7, 0), "");

	/* Don't rewrite the sample index if WORD1.DATA_FORMAT of the FMASK
	 * resource descriptor is 0 (invalid).
	 */
	LLVMValueRef tmp;
	tmp = LLVMBuildBitCast(ac->builder, fmask, ac->v8i32, "");
	tmp = LLVMBuildExtractElement(ac->builder, tmp, ac->i32_1, "");
	tmp = LLVMBuildICmp(ac->builder, LLVMIntNE, tmp, ac->i32_0, "");

	/* Replace the MSAA sample index. */
	addr[sample_chan] = LLVMBuildSelect(ac->builder, tmp, final_sample,
					    addr[sample_chan], "");
}

static LLVMValueRef
_ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
{
	ac_build_optimization_barrier(ctx, &src);
	return ac_build_intrinsic(ctx,
			lane == NULL ? "llvm.amdgcn.readfirstlane" : "llvm.amdgcn.readlane",
			LLVMTypeOf(src), (LLVMValueRef []) {
			src, lane },
			lane == NULL ? 1 : 2,
			AC_FUNC_ATTR_READNONE |
			AC_FUNC_ATTR_CONVERGENT);
}

/**
 * Builds the "llvm.amdgcn.readlane" or "llvm.amdgcn.readfirstlane" intrinsic.
 * @param ctx
 * @param src
 * @param lane - id of the lane or NULL for the first active lane
 * @return value of the lane
 */
LLVMValueRef
ac_build_readlane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef lane)
{
	LLVMTypeRef src_type = LLVMTypeOf(src);
	src = ac_to_integer(ctx, src);
	unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
	LLVMValueRef ret;

	if (bits == 32) {
		ret = _ac_build_readlane(ctx, src, lane);
	} else {
		assert(bits % 32 == 0);
		LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
		LLVMValueRef src_vector =
			LLVMBuildBitCast(ctx->builder, src, vec_type, "");
		ret = LLVMGetUndef(vec_type);
		for (unsigned i = 0; i < bits / 32; i++) {
			src = LLVMBuildExtractElement(ctx->builder, src_vector,
						LLVMConstInt(ctx->i32, i, 0), "");
			LLVMValueRef ret_comp = _ac_build_readlane(ctx, src, lane);
			ret = LLVMBuildInsertElement(ctx->builder, ret, ret_comp,
						LLVMConstInt(ctx->i32, i, 0), "");
		}
	}
	return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
}

LLVMValueRef
ac_build_writelane(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef value, LLVMValueRef lane)
{
	/* TODO: Use the actual instruction when LLVM adds an intrinsic for it.
	 */
	LLVMValueRef pred = LLVMBuildICmp(ctx->builder, LLVMIntEQ, lane,
					  ac_get_thread_id(ctx), "");
	return LLVMBuildSelect(ctx->builder, pred, value, src, "");
}

LLVMValueRef
ac_build_mbcnt(struct ac_llvm_context *ctx, LLVMValueRef mask)
{
	LLVMValueRef mask_vec = LLVMBuildBitCast(ctx->builder, mask,
						 LLVMVectorType(ctx->i32, 2),
						 "");
	LLVMValueRef mask_lo = LLVMBuildExtractElement(ctx->builder, mask_vec,
						       ctx->i32_0, "");
	LLVMValueRef mask_hi = LLVMBuildExtractElement(ctx->builder, mask_vec,
						       ctx->i32_1, "");
	LLVMValueRef val =
		ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.lo", ctx->i32,
				   (LLVMValueRef []) { mask_lo, ctx->i32_0 },
				   2, AC_FUNC_ATTR_READNONE);
	val = ac_build_intrinsic(ctx, "llvm.amdgcn.mbcnt.hi", ctx->i32,
				 (LLVMValueRef []) { mask_hi, val },
				 2, AC_FUNC_ATTR_READNONE);
	return val;
}

enum dpp_ctrl {
	_dpp_quad_perm = 0x000,
	_dpp_row_sl = 0x100,
	_dpp_row_sr = 0x110,
	_dpp_row_rr = 0x120,
	dpp_wf_sl1 = 0x130,
	dpp_wf_rl1 = 0x134,
	dpp_wf_sr1 = 0x138,
	dpp_wf_rr1 = 0x13C,
	dpp_row_mirror = 0x140,
	dpp_row_half_mirror = 0x141,
	dpp_row_bcast15 = 0x142,
	dpp_row_bcast31 = 0x143
};

static inline enum dpp_ctrl
dpp_quad_perm(unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
{
	assert(lane0 < 4 && lane1 < 4 && lane2 < 4 && lane3 < 4);
	return _dpp_quad_perm | lane0 | (lane1 << 2) | (lane2 << 4) | (lane3 << 6);
}

static inline enum dpp_ctrl
dpp_row_sl(unsigned amount)
{
	assert(amount > 0 && amount < 16);
	return _dpp_row_sl | amount;
}

static inline enum dpp_ctrl
dpp_row_sr(unsigned amount)
{
	assert(amount > 0 && amount < 16);
	return _dpp_row_sr | amount;
}

static LLVMValueRef
_ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
	      enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
	      bool bound_ctrl)
{
	return ac_build_intrinsic(ctx, "llvm.amdgcn.update.dpp.i32",
					LLVMTypeOf(old),
					(LLVMValueRef[]) {
						old, src,
						LLVMConstInt(ctx->i32, dpp_ctrl, 0),
						LLVMConstInt(ctx->i32, row_mask, 0),
						LLVMConstInt(ctx->i32, bank_mask, 0),
						LLVMConstInt(ctx->i1, bound_ctrl, 0) },
					6, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
}

static LLVMValueRef
ac_build_dpp(struct ac_llvm_context *ctx, LLVMValueRef old, LLVMValueRef src,
	     enum dpp_ctrl dpp_ctrl, unsigned row_mask, unsigned bank_mask,
	     bool bound_ctrl)
{
	LLVMTypeRef src_type = LLVMTypeOf(src);
	src = ac_to_integer(ctx, src);
	old = ac_to_integer(ctx, old);
	unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
	LLVMValueRef ret;
	if (bits == 32) {
		ret = _ac_build_dpp(ctx, old, src, dpp_ctrl, row_mask,
				    bank_mask, bound_ctrl);
	} else {
		assert(bits % 32 == 0);
		LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
		LLVMValueRef src_vector =
			LLVMBuildBitCast(ctx->builder, src, vec_type, "");
		LLVMValueRef old_vector =
			LLVMBuildBitCast(ctx->builder, old, vec_type, "");
		ret = LLVMGetUndef(vec_type);
		for (unsigned i = 0; i < bits / 32; i++) {
			src = LLVMBuildExtractElement(ctx->builder, src_vector,
						      LLVMConstInt(ctx->i32, i,
								   0), "");
			old = LLVMBuildExtractElement(ctx->builder, old_vector,
						      LLVMConstInt(ctx->i32, i,
								   0), "");
			LLVMValueRef ret_comp = _ac_build_dpp(ctx, old, src,
							      dpp_ctrl,
							      row_mask,
							      bank_mask,
							      bound_ctrl);
			ret = LLVMBuildInsertElement(ctx->builder, ret,
						     ret_comp,
						     LLVMConstInt(ctx->i32, i,
								  0), "");
		}
	}
	return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
}

static inline unsigned
ds_pattern_bitmode(unsigned and_mask, unsigned or_mask, unsigned xor_mask)
{
	assert(and_mask < 32 && or_mask < 32 && xor_mask < 32);
	return and_mask | (or_mask << 5) | (xor_mask << 10);
}

static LLVMValueRef
_ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
{
	return ac_build_intrinsic(ctx, "llvm.amdgcn.ds.swizzle",
				   LLVMTypeOf(src), (LLVMValueRef []) {
					src, LLVMConstInt(ctx->i32, mask, 0) },
				   2, AC_FUNC_ATTR_READNONE | AC_FUNC_ATTR_CONVERGENT);
}

LLVMValueRef
ac_build_ds_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src, unsigned mask)
{
	LLVMTypeRef src_type = LLVMTypeOf(src);
	src = ac_to_integer(ctx, src);
	unsigned bits = LLVMGetIntTypeWidth(LLVMTypeOf(src));
	LLVMValueRef ret;
	if (bits == 32) {
		ret = _ac_build_ds_swizzle(ctx, src, mask);
	} else {
		assert(bits % 32 == 0);
		LLVMTypeRef vec_type = LLVMVectorType(ctx->i32, bits / 32);
		LLVMValueRef src_vector =
			LLVMBuildBitCast(ctx->builder, src, vec_type, "");
		ret = LLVMGetUndef(vec_type);
		for (unsigned i = 0; i < bits / 32; i++) {
			src = LLVMBuildExtractElement(ctx->builder, src_vector,
						      LLVMConstInt(ctx->i32, i,
								   0), "");
			LLVMValueRef ret_comp = _ac_build_ds_swizzle(ctx, src,
								     mask);
			ret = LLVMBuildInsertElement(ctx->builder, ret,
						     ret_comp,
						     LLVMConstInt(ctx->i32, i,
								  0), "");
		}
	}
	return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
}

static LLVMValueRef
ac_build_wwm(struct ac_llvm_context *ctx, LLVMValueRef src)
{
	char name[32], type[8];
	ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
	snprintf(name, sizeof(name), "llvm.amdgcn.wwm.%s", type);
	return ac_build_intrinsic(ctx, name, LLVMTypeOf(src),
				  (LLVMValueRef []) { src }, 1,
				  AC_FUNC_ATTR_READNONE);
}

static LLVMValueRef
ac_build_set_inactive(struct ac_llvm_context *ctx, LLVMValueRef src,
		      LLVMValueRef inactive)
{
	char name[33], type[8];
	LLVMTypeRef src_type = LLVMTypeOf(src);
	src = ac_to_integer(ctx, src);
	inactive = ac_to_integer(ctx, inactive);
	ac_build_type_name_for_intr(LLVMTypeOf(src), type, sizeof(type));
	snprintf(name, sizeof(name), "llvm.amdgcn.set.inactive.%s", type);
	LLVMValueRef ret =
		ac_build_intrinsic(ctx, name,
					LLVMTypeOf(src), (LLVMValueRef []) {
					src, inactive }, 2,
					AC_FUNC_ATTR_READNONE |
					AC_FUNC_ATTR_CONVERGENT);
	return LLVMBuildBitCast(ctx->builder, ret, src_type, "");
}

static LLVMValueRef
get_reduction_identity(struct ac_llvm_context *ctx, nir_op op, unsigned type_size)
{
	if (type_size == 4) {
		switch (op) {
		case nir_op_iadd: return ctx->i32_0;
		case nir_op_fadd: return ctx->f32_0;
		case nir_op_imul: return ctx->i32_1;
		case nir_op_fmul: return ctx->f32_1;
		case nir_op_imin: return LLVMConstInt(ctx->i32, INT32_MAX, 0);
		case nir_op_umin: return LLVMConstInt(ctx->i32, UINT32_MAX, 0);
		case nir_op_fmin: return LLVMConstReal(ctx->f32, INFINITY);
		case nir_op_imax: return LLVMConstInt(ctx->i32, INT32_MIN, 0);
		case nir_op_umax: return ctx->i32_0;
		case nir_op_fmax: return LLVMConstReal(ctx->f32, -INFINITY);
		case nir_op_iand: return LLVMConstInt(ctx->i32, -1, 0);
		case nir_op_ior: return ctx->i32_0;
		case nir_op_ixor: return ctx->i32_0;
		default:
			unreachable("bad reduction intrinsic");
		}
	} else { /* type_size == 64bit */
		switch (op) {
		case nir_op_iadd: return ctx->i64_0;
		case nir_op_fadd: return ctx->f64_0;
		case nir_op_imul: return ctx->i64_1;
		case nir_op_fmul: return ctx->f64_1;
		case nir_op_imin: return LLVMConstInt(ctx->i64, INT64_MAX, 0);
		case nir_op_umin: return LLVMConstInt(ctx->i64, UINT64_MAX, 0);
		case nir_op_fmin: return LLVMConstReal(ctx->f64, INFINITY);
		case nir_op_imax: return LLVMConstInt(ctx->i64, INT64_MIN, 0);
		case nir_op_umax: return ctx->i64_0;
		case nir_op_fmax: return LLVMConstReal(ctx->f64, -INFINITY);
		case nir_op_iand: return LLVMConstInt(ctx->i64, -1, 0);
		case nir_op_ior: return ctx->i64_0;
		case nir_op_ixor: return ctx->i64_0;
		default:
			unreachable("bad reduction intrinsic");
		}
	}
}

static LLVMValueRef
ac_build_alu_op(struct ac_llvm_context *ctx, LLVMValueRef lhs, LLVMValueRef rhs, nir_op op)
{
	bool _64bit = ac_get_type_size(LLVMTypeOf(lhs)) == 8;
	switch (op) {
	case nir_op_iadd: return LLVMBuildAdd(ctx->builder, lhs, rhs, "");
	case nir_op_fadd: return LLVMBuildFAdd(ctx->builder, lhs, rhs, "");
	case nir_op_imul: return LLVMBuildMul(ctx->builder, lhs, rhs, "");
	case nir_op_fmul: return LLVMBuildFMul(ctx->builder, lhs, rhs, "");
	case nir_op_imin: return LLVMBuildSelect(ctx->builder,
					LLVMBuildICmp(ctx->builder, LLVMIntSLT, lhs, rhs, ""),
					lhs, rhs, "");
	case nir_op_umin: return LLVMBuildSelect(ctx->builder,
					LLVMBuildICmp(ctx->builder, LLVMIntULT, lhs, rhs, ""),
					lhs, rhs, "");
	case nir_op_fmin: return ac_build_intrinsic(ctx,
					_64bit ? "llvm.minnum.f64" : "llvm.minnum.f32",
					_64bit ? ctx->f64 : ctx->f32,
					(LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
	case nir_op_imax: return LLVMBuildSelect(ctx->builder,
					LLVMBuildICmp(ctx->builder, LLVMIntSGT, lhs, rhs, ""),
					lhs, rhs, "");
	case nir_op_umax: return LLVMBuildSelect(ctx->builder,
					LLVMBuildICmp(ctx->builder, LLVMIntUGT, lhs, rhs, ""),
					lhs, rhs, "");
	case nir_op_fmax: return ac_build_intrinsic(ctx,
					_64bit ? "llvm.maxnum.f64" : "llvm.maxnum.f32",
					_64bit ? ctx->f64 : ctx->f32,
					(LLVMValueRef[]){lhs, rhs}, 2, AC_FUNC_ATTR_READNONE);
	case nir_op_iand: return LLVMBuildAnd(ctx->builder, lhs, rhs, "");
	case nir_op_ior: return LLVMBuildOr(ctx->builder, lhs, rhs, "");
	case nir_op_ixor: return LLVMBuildXor(ctx->builder, lhs, rhs, "");
	default:
		unreachable("bad reduction intrinsic");
	}
}

/**
 * \param maxprefix specifies that the result only needs to be correct for a
 *     prefix of this many threads
 *
 * TODO: add inclusive and excluse scan functions for SI chip class.
 */
static LLVMValueRef
ac_build_scan(struct ac_llvm_context *ctx, nir_op op, LLVMValueRef src, LLVMValueRef identity,
	      unsigned maxprefix)
{
	LLVMValueRef result, tmp;
	result = src;
	if (maxprefix <= 1)
		return result;
	tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(1), 0xf, 0xf, false);
	result = ac_build_alu_op(ctx, result, tmp, op);
	if (maxprefix <= 2)
		return result;
	tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(2), 0xf, 0xf, false);
	result = ac_build_alu_op(ctx, result, tmp, op);
	if (maxprefix <= 3)
		return result;
	tmp = ac_build_dpp(ctx, identity, src, dpp_row_sr(3), 0xf, 0xf, false);
	result = ac_build_alu_op(ctx, result, tmp, op);
	if (maxprefix <= 4)
		return result;
	tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(4), 0xf, 0xe, false);
	result = ac_build_alu_op(ctx, result, tmp, op);
	if (maxprefix <= 8)
		return result;
	tmp = ac_build_dpp(ctx, identity, result, dpp_row_sr(8), 0xf, 0xc, false);
	result = ac_build_alu_op(ctx, result, tmp, op);
	if (maxprefix <= 16)
		return result;
	tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
	result = ac_build_alu_op(ctx, result, tmp, op);
	if (maxprefix <= 32)
		return result;
	tmp = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
	result = ac_build_alu_op(ctx, result, tmp, op);
	return result;
}

LLVMValueRef
ac_build_inclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
{
	LLVMValueRef result;

	if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
		LLVMBuilderRef builder = ctx->builder;
		src = LLVMBuildZExt(builder, src, ctx->i32, "");
		result = ac_build_ballot(ctx, src);
		result = ac_build_mbcnt(ctx, result);
		result = LLVMBuildAdd(builder, result, src, "");
		return result;
	}

	ac_build_optimization_barrier(ctx, &src);

	LLVMValueRef identity =
		get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
	result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
				  LLVMTypeOf(identity), "");
	result = ac_build_scan(ctx, op, result, identity, 64);

	return ac_build_wwm(ctx, result);
}

LLVMValueRef
ac_build_exclusive_scan(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op)
{
	LLVMValueRef result;

	if (LLVMTypeOf(src) == ctx->i1 && op == nir_op_iadd) {
		LLVMBuilderRef builder = ctx->builder;
		src = LLVMBuildZExt(builder, src, ctx->i32, "");
		result = ac_build_ballot(ctx, src);
		result = ac_build_mbcnt(ctx, result);
		return result;
	}

	ac_build_optimization_barrier(ctx, &src);

	LLVMValueRef identity =
		get_reduction_identity(ctx, op, ac_get_type_size(LLVMTypeOf(src)));
	result = LLVMBuildBitCast(ctx->builder, ac_build_set_inactive(ctx, src, identity),
				  LLVMTypeOf(identity), "");
	result = ac_build_dpp(ctx, identity, result, dpp_wf_sr1, 0xf, 0xf, false);
	result = ac_build_scan(ctx, op, result, identity, 64);

	return ac_build_wwm(ctx, result);
}

LLVMValueRef
ac_build_reduce(struct ac_llvm_context *ctx, LLVMValueRef src, nir_op op, unsigned cluster_size)
{
	if (cluster_size == 1) return src;
	ac_build_optimization_barrier(ctx, &src);
	LLVMValueRef result, swap;
	LLVMValueRef identity = get_reduction_identity(ctx, op,
								ac_get_type_size(LLVMTypeOf(src)));
	result = LLVMBuildBitCast(ctx->builder,
								ac_build_set_inactive(ctx, src, identity),
								LLVMTypeOf(identity), "");
	swap = ac_build_quad_swizzle(ctx, result, 1, 0, 3, 2);
	result = ac_build_alu_op(ctx, result, swap, op);
	if (cluster_size == 2) return ac_build_wwm(ctx, result);

	swap = ac_build_quad_swizzle(ctx, result, 2, 3, 0, 1);
	result = ac_build_alu_op(ctx, result, swap, op);
	if (cluster_size == 4) return ac_build_wwm(ctx, result);

	if (ctx->chip_class >= VI)
		swap = ac_build_dpp(ctx, identity, result, dpp_row_half_mirror, 0xf, 0xf, false);
	else
		swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x04));
	result = ac_build_alu_op(ctx, result, swap, op);
	if (cluster_size == 8) return ac_build_wwm(ctx, result);

	if (ctx->chip_class >= VI)
		swap = ac_build_dpp(ctx, identity, result, dpp_row_mirror, 0xf, 0xf, false);
	else
		swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x08));
	result = ac_build_alu_op(ctx, result, swap, op);
	if (cluster_size == 16) return ac_build_wwm(ctx, result);

	if (ctx->chip_class >= VI && cluster_size != 32)
		swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast15, 0xa, 0xf, false);
	else
		swap = ac_build_ds_swizzle(ctx, result, ds_pattern_bitmode(0x1f, 0, 0x10));
	result = ac_build_alu_op(ctx, result, swap, op);
	if (cluster_size == 32) return ac_build_wwm(ctx, result);

	if (ctx->chip_class >= VI) {
		swap = ac_build_dpp(ctx, identity, result, dpp_row_bcast31, 0xc, 0xf, false);
		result = ac_build_alu_op(ctx, result, swap, op);
		result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 63, 0));
		return ac_build_wwm(ctx, result);
	} else {
		swap = ac_build_readlane(ctx, result, ctx->i32_0);
		result = ac_build_readlane(ctx, result, LLVMConstInt(ctx->i32, 32, 0));
		result = ac_build_alu_op(ctx, result, swap, op);
		return ac_build_wwm(ctx, result);
	}
}

/**
 * "Top half" of a scan that reduces per-wave values across an entire
 * workgroup.
 *
 * The source value must be present in the highest lane of the wave, and the
 * highest lane must be live.
 */
void
ac_build_wg_wavescan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
{
	if (ws->maxwaves <= 1)
		return;

	const LLVMValueRef i32_63 = LLVMConstInt(ctx->i32, 63, false);
	LLVMBuilderRef builder = ctx->builder;
	LLVMValueRef tid = ac_get_thread_id(ctx);
	LLVMValueRef tmp;

	tmp = LLVMBuildICmp(builder, LLVMIntEQ, tid, i32_63, "");
	ac_build_ifcc(ctx, tmp, 1000);
	LLVMBuildStore(builder, ws->src, LLVMBuildGEP(builder, ws->scratch, &ws->waveidx, 1, ""));
	ac_build_endif(ctx, 1000);
}

/**
 * "Bottom half" of a scan that reduces per-wave values across an entire
 * workgroup.
 *
 * The caller must place a barrier between the top and bottom halves.
 */
void
ac_build_wg_wavescan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
{
	const LLVMTypeRef type = LLVMTypeOf(ws->src);
	const LLVMValueRef identity =
		get_reduction_identity(ctx, ws->op, ac_get_type_size(type));

	if (ws->maxwaves <= 1) {
		ws->result_reduce = ws->src;
		ws->result_inclusive = ws->src;
		ws->result_exclusive = identity;
		return;
	}
	assert(ws->maxwaves <= 32);

	LLVMBuilderRef builder = ctx->builder;
	LLVMValueRef tid = ac_get_thread_id(ctx);
	LLVMBasicBlockRef bbs[2];
	LLVMValueRef phivalues_scan[2];
	LLVMValueRef tmp, tmp2;

	bbs[0] = LLVMGetInsertBlock(builder);
	phivalues_scan[0] = LLVMGetUndef(type);

	if (ws->enable_reduce)
		tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->numwaves, "");
	else if (ws->enable_inclusive)
		tmp = LLVMBuildICmp(builder, LLVMIntULE, tid, ws->waveidx, "");
	else
		tmp = LLVMBuildICmp(builder, LLVMIntULT, tid, ws->waveidx, "");
	ac_build_ifcc(ctx, tmp, 1001);
	{
		tmp = LLVMBuildLoad(builder, LLVMBuildGEP(builder, ws->scratch, &tid, 1, ""), "");

		ac_build_optimization_barrier(ctx, &tmp);

		bbs[1] = LLVMGetInsertBlock(builder);
		phivalues_scan[1] = ac_build_scan(ctx, ws->op, tmp, identity, ws->maxwaves);
	}
	ac_build_endif(ctx, 1001);

	const LLVMValueRef scan = ac_build_phi(ctx, type, 2, phivalues_scan, bbs);

	if (ws->enable_reduce) {
		tmp = LLVMBuildSub(builder, ws->numwaves, ctx->i32_1, "");
		ws->result_reduce = ac_build_readlane(ctx, scan, tmp);
	}
	if (ws->enable_inclusive)
		ws->result_inclusive = ac_build_readlane(ctx, scan, ws->waveidx);
	if (ws->enable_exclusive) {
		tmp = LLVMBuildSub(builder, ws->waveidx, ctx->i32_1, "");
		tmp = ac_build_readlane(ctx, scan, tmp);
		tmp2 = LLVMBuildICmp(builder, LLVMIntEQ, ws->waveidx, ctx->i32_0, "");
		ws->result_exclusive = LLVMBuildSelect(builder, tmp2, identity, tmp, "");
	}
}

/**
 * Inclusive scan of a per-wave value across an entire workgroup.
 *
 * This implies an s_barrier instruction.
 *
 * Unlike ac_build_inclusive_scan, the caller \em must ensure that all threads
 * of the workgroup are live. (This requirement cannot easily be relaxed in a
 * useful manner because of the barrier in the algorithm.)
 */
void
ac_build_wg_wavescan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
{
	ac_build_wg_wavescan_top(ctx, ws);
	ac_build_s_barrier(ctx);
	ac_build_wg_wavescan_bottom(ctx, ws);
}

/**
 * "Top half" of a scan that reduces per-thread values across an entire
 * workgroup.
 *
 * All lanes must be active when this code runs.
 */
void
ac_build_wg_scan_top(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
{
	if (ws->enable_exclusive) {
		ws->extra = ac_build_exclusive_scan(ctx, ws->src, ws->op);
		if (LLVMTypeOf(ws->src) == ctx->i1 && ws->op == nir_op_iadd)
			ws->src = LLVMBuildZExt(ctx->builder, ws->src, ctx->i32, "");
		ws->src = ac_build_alu_op(ctx, ws->extra, ws->src, ws->op);
	} else {
		ws->src = ac_build_inclusive_scan(ctx, ws->src, ws->op);
	}

	bool enable_inclusive = ws->enable_inclusive;
	bool enable_exclusive = ws->enable_exclusive;
	ws->enable_inclusive = false;
	ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
	ac_build_wg_wavescan_top(ctx, ws);
	ws->enable_inclusive = enable_inclusive;
	ws->enable_exclusive = enable_exclusive;
}

/**
 * "Bottom half" of a scan that reduces per-thread values across an entire
 * workgroup.
 *
 * The caller must place a barrier between the top and bottom halves.
 */
void
ac_build_wg_scan_bottom(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
{
	bool enable_inclusive = ws->enable_inclusive;
	bool enable_exclusive = ws->enable_exclusive;
	ws->enable_inclusive = false;
	ws->enable_exclusive = ws->enable_exclusive || enable_inclusive;
	ac_build_wg_wavescan_bottom(ctx, ws);
	ws->enable_inclusive = enable_inclusive;
	ws->enable_exclusive = enable_exclusive;

	/* ws->result_reduce is already the correct value */
	if (ws->enable_inclusive)
		ws->result_inclusive = ac_build_alu_op(ctx, ws->result_exclusive, ws->src, ws->op);
	if (ws->enable_exclusive)
		ws->result_exclusive = ac_build_alu_op(ctx, ws->result_exclusive, ws->extra, ws->op);
}

/**
 * A scan that reduces per-thread values across an entire workgroup.
 *
 * The caller must ensure that all lanes are active when this code runs
 * (WWM is insufficient!), because there is an implied barrier.
 */
void
ac_build_wg_scan(struct ac_llvm_context *ctx, struct ac_wg_scan *ws)
{
	ac_build_wg_scan_top(ctx, ws);
	ac_build_s_barrier(ctx);
	ac_build_wg_scan_bottom(ctx, ws);
}

LLVMValueRef
ac_build_quad_swizzle(struct ac_llvm_context *ctx, LLVMValueRef src,
		unsigned lane0, unsigned lane1, unsigned lane2, unsigned lane3)
{
	unsigned mask = dpp_quad_perm(lane0, lane1, lane2, lane3);
	if (ctx->chip_class >= VI) {
		return ac_build_dpp(ctx, src, src, mask, 0xf, 0xf, false);
	} else {
		return ac_build_ds_swizzle(ctx, src, (1 << 15) | mask);
	}
}

LLVMValueRef
ac_build_shuffle(struct ac_llvm_context *ctx, LLVMValueRef src, LLVMValueRef index)
{
	index = LLVMBuildMul(ctx->builder, index, LLVMConstInt(ctx->i32, 4, 0), "");
	return ac_build_intrinsic(ctx,
		  "llvm.amdgcn.ds.bpermute", ctx->i32,
		  (LLVMValueRef []) {index, src}, 2,
		  AC_FUNC_ATTR_READNONE |
		  AC_FUNC_ATTR_CONVERGENT);
}

LLVMValueRef
ac_build_frexp_exp(struct ac_llvm_context *ctx, LLVMValueRef src0,
		   unsigned bitsize)
{
	LLVMTypeRef type;
	char *intr;

	if (bitsize == 16) {
		intr = "llvm.amdgcn.frexp.exp.i16.f16";
		type = ctx->i16;
	} else if (bitsize == 32) {
		intr = "llvm.amdgcn.frexp.exp.i32.f32";
		type = ctx->i32;
	} else {
		intr = "llvm.amdgcn.frexp.exp.i32.f64";
		type = ctx->i32;
	}

	LLVMValueRef params[] = {
		src0,
	};
	return ac_build_intrinsic(ctx, intr, type, params, 1,
				  AC_FUNC_ATTR_READNONE);
}
LLVMValueRef
ac_build_frexp_mant(struct ac_llvm_context *ctx, LLVMValueRef src0,
		    unsigned bitsize)
{
	LLVMTypeRef type;
	char *intr;

	if (bitsize == 16) {
		intr = "llvm.amdgcn.frexp.mant.f16";
		type = ctx->f16;
	} else if (bitsize == 32) {
		intr = "llvm.amdgcn.frexp.mant.f32";
		type = ctx->f32;
	} else {
		intr = "llvm.amdgcn.frexp.mant.f64";
		type = ctx->f64;
	}

	LLVMValueRef params[] = {
		src0,
	};
	return ac_build_intrinsic(ctx, intr, type, params, 1,
				  AC_FUNC_ATTR_READNONE);
}