cranelift-codegen 0.112.2

Low-level code generator library
Documentation
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
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
;; Extern type definitions and constructors for the x64 `MachInst` type.

;;;; `MInst` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Don't build `MInst` variants directly, in general. Instead, use the
;; instruction-emitting helpers defined further down.

(type MInst nodebug
      (enum
       ;; Nops of various sizes, including zero.
       (Nop (len u8))

       ;; =========================================
       ;; Integer instructions.

       ;; Integer arithmetic/bit-twiddling.
       (AluRmiR (size OperandSize) ;; 1, 2, 4 or 8
                (op AluRmiROpcode)
                (src1 Gpr)
                (src2 GprMemImm)
                (dst WritableGpr))

       ;; Integer arithmetic read-modify-write on memory.
       (AluRM (size OperandSize) ;; 1, 2, 4 or 8
              (op AluRmiROpcode)
              (src1_dst SyntheticAmode)
              (src2 Gpr))

       ;; Integer arithmetic binary op that relies on the VEX prefix.
       ;; NOTE: we don't currently support emitting VEX instructions with memory
       ;; arguments, so `src2` is artificially constrained to be a Gpr.
       (AluRmRVex (size OperandSize)
                  (op AluRmROpcode)
                  (src1 Gpr)
                  (src2 GprMem)
                  (dst WritableGpr))

       ;; Production of a zero value into a register of the specified size.
       (AluConstOp (op AluRmiROpcode)
                   (size OperandSize)
                   (dst WritableGpr))

       ;; Instructions on general-purpose registers that only read src and
       ;; defines dst (dst is not modified). `bsr`, etc.
       (UnaryRmR (size OperandSize) ;; 2, 4, or 8
                 (op UnaryRmROpcode)
                 (src GprMem)
                 (dst WritableGpr))

       ;; Same as `UnaryRmR` but with the VEX prefix for BMI1 instructions.
       (UnaryRmRVex (size OperandSize)
                    (op UnaryRmRVexOpcode)
                    (src GprMem)
                    (dst WritableGpr))

       ;; Same as `UnaryRmRVex` but with an immediate
       (UnaryRmRImmVex (size OperandSize)
                       (op UnaryRmRImmVexOpcode)
                       (src GprMem)
                       (dst WritableGpr)
                       (imm u8))

       ;; Bitwise not.
       (Not (size OperandSize) ;; 1, 2, 4, or 8
            (src Gpr)
            (dst WritableGpr))

       ;; Integer negation.
       (Neg (size OperandSize) ;; 1, 2, 4, or 8
            (src Gpr)
            (dst WritableGpr))

       ;; Integer quotient and remainder: (div idiv) $rax $rdx (reg addr)
       ;;
       ;; Note that this isn't used for 8-bit division which has its own `Div8`
       ;; instruction.
       (Div (size OperandSize) ;; 2, 4, or 8
            (sign DivSignedness)
            (trap TrapCode)
            (divisor GprMem)
            (dividend_lo Gpr)
            (dividend_hi Gpr)
            (dst_quotient WritableGpr)
            (dst_remainder WritableGpr))

       ;; Same as `Div`, but for 8-bits where the regalloc behavior is different
       (Div8 (sign DivSignedness)
             (trap TrapCode)
             (divisor GprMem)
             (dividend Gpr)
             (dst WritableGpr))

       ;; Unsigned multiplication producing the high bits of the result in one
       ;; register and the low bits in another register.
       (Mul (size OperandSize)
            (signed bool)
            (src1 Gpr)
            (src2 GprMem)
            (dst_lo WritableGpr)
            (dst_hi WritableGpr))

       ;; Same as `Mul` but the 16-bit multiplication result is stored in `AX`.
       (Mul8 (signed bool)
             (src1 Gpr)
             (src2 GprMem)
             (dst WritableGpr))

       ;; The two-operand form of `imul` which produces a truncated same-size
       ;; result as the operands.
       (IMul (size OperandSize)
             (src1 Gpr)
             (src2 GprMem)
             (dst WritableGpr))

       ;; The three-operand form of `imul` where the third operand must be
       ;; a constant.
       (IMulImm (size OperandSize)
                (src1 GprMem)
                (src2 i32)
                (dst WritableGpr))

       ;; A synthetic instruction sequence used as part of the lowering of the
       ;; `srem` instruction which returns 0 if the divisor is -1 and
       ;; otherwise executes an `idiv` instruction.
       ;;
       ;; Note that this does not check for 0 as that's expected to be done
       ;; separately. Also note that 8-bit types don't use this and use
       ;; `CheckedSRemSeq8` instead.
       (CheckedSRemSeq (size OperandSize)
                       (dividend_lo Gpr)
                       (dividend_hi Gpr)
                       (divisor Gpr)
                       (dst_quotient WritableGpr)
                       (dst_remainder WritableGpr))

       ;; Same as above but for 8-bit types.
       (CheckedSRemSeq8 (dividend Gpr)
                        (divisor Gpr)
                        (dst WritableGpr))

       ;; Do a sign-extend based on the sign of the value in rax into rdx: (cwd
       ;; cdq cqo) or al into ah: (cbw)
       (SignExtendData (size OperandSize) ;; 1, 2, 4, or 8
                       (src Gpr)
                       (dst WritableGpr))

       ;; Constant materialization: (imm32 imm64) reg.
       ;;
       ;; Either: movl $imm32, %reg32 or movabsq $imm64, %reg32.
       (Imm (dst_size OperandSize) ;; 4 or 8
            (simm64 u64)
            (dst WritableGpr))

       ;; GPR to GPR move: mov (64 32) reg reg.
       (MovRR (size OperandSize) ;; 4 or 8
              (src Gpr)
              (dst WritableGpr))

       ;; Like `MovRR` but with a physical register source (for implementing
       ;; CLIF instructions like `get_stack_pointer`).
       (MovFromPReg (src PReg)
                    (dst WritableGpr))

       ;; Like `MovRR` but with a physical register destination (for
       ;; implementing CLIF instructions like `set_pinned_reg`).
       (MovToPReg (src Gpr)
                  (dst PReg))

       ;; Zero-extended loads, except for 64 bits: movz (bl bq wl wq lq) addr
       ;; reg.
       ;;
       ;; Note that the lq variant doesn't really exist since the default
       ;; zero-extend rule makes it unnecessary. For that case we emit the
       ;; equivalent "movl AM, reg32".
       (MovzxRmR (ext_mode ExtMode)
                 (src GprMem)
                 (dst WritableGpr))

       ;; A plain 64-bit integer load, since MovZX_RM_R can't represent that.
       (Mov64MR (src SyntheticAmode)
                (dst WritableGpr))

       ;; Loads the memory address of addr into dst.
       (LoadEffectiveAddress (addr SyntheticAmode)
                             (dst WritableGpr)
                             (size OperandSize))

       ;; Sign-extended loads and moves: movs (bl bq wl wq lq) addr reg.
       (MovsxRmR (ext_mode ExtMode)
                 (src GprMem)
                 (dst WritableGpr))

       ;; Immediate store.
       (MovImmM (size OperandSize)
		(simm32 i32)
		(dst SyntheticAmode))

       ;; Integer stores: mov (b w l q) reg addr.
       (MovRM (size OperandSize) ;; 1, 2, 4, or 8
              (src Gpr)
              (dst SyntheticAmode))

       ;; Arithmetic shifts: (shl shr sar) (b w l q) imm reg.
       (ShiftR (size OperandSize) ;; 1, 2, 4, or 8
               (kind ShiftKind)
               (src Gpr)
               ;; shift count: `Imm8Gpr::Imm8(0 .. #bits-in-type - 1)` or
               ;; `Imm8Reg::Gpr(r)` where `r` gets move mitosis'd into `%cl`.
               (num_bits Imm8Gpr)
               (dst WritableGpr))

       ;; Arithmetic SIMD shifts.
       (XmmRmiReg (opcode SseOpcode)
                  (src1 Xmm)
                  (src2 XmmMemAlignedImm)
                  (dst WritableXmm))

       ;; Integer comparisons/tests: cmp or test (b w l q) (reg addr imm) reg.
       (CmpRmiR (size OperandSize) ;; 1, 2, 4, or 8
                (opcode CmpOpcode)
                (src1 Gpr)
                (src2 GprMemImm))

       ;; Materializes the requested condition code in the destinaton reg.
       (Setcc (cc CC)
              (dst WritableGpr))

       ;; Swaps byte order in register
       (Bswap (size OperandSize) ;; 4 or 8
              (src Gpr)
              (dst WritableGpr))

       ;; =========================================
       ;; Conditional moves.

       ;; GPR conditional move; overwrites the destination register.
       (Cmove (size OperandSize)
              (cc CC)
              (consequent GprMem)
              (alternative Gpr)
              (dst WritableGpr))

       ;; XMM conditional move; overwrites the destination register.
       (XmmCmove (ty Type)
                 (cc CC)
                 (consequent Xmm)
                 (alternative Xmm)
                 (dst WritableXmm))

       ;; =========================================
       ;; Stack manipulation.

       ;; pushq (reg addr imm)
       (Push64 (src GprMemImm))

       ;; popq reg
       (Pop64 (dst WritableGpr))

      ;; Emits a inline stack probe loop.
      (StackProbeLoop (tmp WritableReg)
                      (frame_size u32)
                      (guard_size u32))

       ;; =========================================
       ;; Floating-point operations.

       ;; XMM (scalar or vector) binary op: (add sub and or xor mul adc? sbb?)
       ;; (32 64) (reg addr) reg
       (XmmRmR (op SseOpcode)
               (src1 Xmm)
               (src2 XmmMemAligned)
               (dst WritableXmm))

       ;; Same as `XmmRmR` except the memory operand can be unaligned
       (XmmRmRUnaligned (op SseOpcode)
                        (src1 Xmm)
                        (src2 XmmMem)
                        (dst WritableXmm))

       ;; XMM (scalar or vector) blend op. The mask is used to blend between
       ;; src1 and src2. This differs from a use of `XmmRmR` as the mask is
       ;; implicitly in register xmm0; this special case exists to allow us to
       ;; communicate the constraint on the `mask` register to regalloc2.
       (XmmRmRBlend
         (op SseOpcode)
         (src1 Xmm)
         (src2 XmmMemAligned)
         (mask Xmm)
         (dst WritableXmm))

       ;; XMM (scalar or vector) binary op that relies on the VEX prefix and
       ;; has two inputs.
       (XmmRmiRVex (op AvxOpcode)
                   (src1 Xmm)
                   (src2 XmmMemImm)
                   (dst WritableXmm))

       ;; XMM (scalar or vector) ternary op that relies on the VEX prefix and
       ;; has two dynamic inputs plus one immediate input.
       (XmmRmRImmVex (op AvxOpcode)
                     (src1 Xmm)
                     (src2 XmmMem)
                     (dst WritableXmm)
                     (imm u8))

       ;; XMM instruction for `vpinsr{b,w,d,q}` which is separate from
       ;; `XmmRmRImmVex` because `src2` is a gpr, not xmm register.
       (XmmVexPinsr (op AvxOpcode)
                   (src1 Xmm)
                   (src2 GprMem)
                   (dst WritableXmm)
                   (imm u8))

       ;; XMM (scalar or vector) ternary op that relies on the VEX prefix and
       ;; has three dynamic inputs.
       (XmmRmRVex3 (op AvxOpcode)
                   (src1 Xmm)
                   (src2 Xmm)
                   (src3 XmmMem)
                   (dst WritableXmm))

       ;; XMM blend operation using the VEX encoding.
       (XmmRmRBlendVex (op AvxOpcode)
                       (src1 Xmm)
                       (src2 XmmMem)
                       (mask Xmm)
                       (dst WritableXmm))

       ;; XMM unary op using a VEX encoding (aka AVX).
       (XmmUnaryRmRVex (op AvxOpcode)
                       (src XmmMem)
                       (dst WritableXmm))

       ;; XMM unary op using a VEX encoding (aka AVX) with an immediate.
       (XmmUnaryRmRImmVex (op AvxOpcode)
                          (src XmmMem)
                          (dst WritableXmm)
                          (imm u8))

       ;; XMM (scalar or vector) unary op (from xmm to reg/mem) using the
       ;; VEX prefix
       (XmmMovRMVex (op AvxOpcode)
                    (src Xmm)
                    (dst SyntheticAmode))
       (XmmMovRMImmVex (op AvxOpcode)
                       (src Xmm)
                       (dst SyntheticAmode)
                       (imm u8))

       ;; XMM (scalar) unary op (from xmm to integer reg): vpextr{w,b,d,q}
       (XmmToGprImmVex (op AvxOpcode)
                       (src Xmm)
                       (dst WritableGpr)
                       (imm u8))

       ;; XMM (scalar) unary op (from integer to float reg): vmovd, vmovq,
       ;; vcvtsi2s{s,d}
       (GprToXmmVex (op AvxOpcode)
                    (src GprMem)
                    (dst WritableXmm)
                    (src_size OperandSize))

       ;; XMM (scalar) unary op (from xmm to integer reg): vmovd, vmovq,
       ;; vcvtts{s,d}2si
       (XmmToGprVex (op AvxOpcode)
                    (src Xmm)
                    (dst WritableGpr)
                    (dst_size OperandSize))

       ;; Float comparisons/tests: cmp (b w l q) (reg addr imm) reg.
       (XmmCmpRmRVex (op AvxOpcode)
                     (src1 Xmm)
                     (src2 XmmMem))

       ;; XMM (scalar or vector) binary op that relies on the EVEX
       ;; prefix. Takes two inputs.
       (XmmRmREvex (op Avx512Opcode)
                   (src1 Xmm)
                   (src2 XmmMem)
                   (dst WritableXmm))

       ;; Same as `XmmRmREvex` but for unary operations.
       (XmmUnaryRmRImmEvex (op Avx512Opcode)
                           (src XmmMem)
                           (dst WritableXmm)
                           (imm u8))

       ;; XMM (scalar or vector) binary op that relies on the EVEX
       ;; prefix. Takes three inputs.
       (XmmRmREvex3 (op Avx512Opcode)
                    (src1 Xmm)
                    (src2 Xmm)
                    (src3 XmmMem)
                    (dst WritableXmm))

       ;; XMM (scalar or vector) unary op: mov between XMM registers (32 64)
       ;; (reg addr) reg, sqrt, etc.
       ;;
       ;; This differs from XMM_RM_R in that the dst register of XmmUnaryRmR is
       ;; not used in the computation of the instruction dst value and so does
       ;; not have to be a previously valid value. This is characteristic of mov
       ;; instructions.
       (XmmUnaryRmR (op SseOpcode)
                    (src XmmMemAligned)
                    (dst WritableXmm))

       ;; Same as `XmmUnaryRmR` but used for opcodes where the memory address
       ;; can be unaligned.
       (XmmUnaryRmRUnaligned (op SseOpcode)
                             (src XmmMem)
                             (dst WritableXmm))

       ;; XMM (scalar or vector) unary op with immediate: roundss, roundsd, etc.
       ;;
       ;; This differs from XMM_RM_R_IMM in that the dst register of
       ;; XmmUnaryRmRImm is not used in the computation of the instruction dst
       ;; value and so does not have to be a previously valid value.
       (XmmUnaryRmRImm (op SseOpcode)
                       (src XmmMemAligned)
                       (imm u8)
                       (dst WritableXmm))

       ;; XMM (scalar or vector) unary op that relies on the EVEX prefix.
       (XmmUnaryRmREvex (op Avx512Opcode)
                        (src XmmMem)
                        (dst WritableXmm))

       ;; XMM (scalar or vector) unary op (from xmm to reg/mem): stores, movd,
       ;; movq
       (XmmMovRM (op SseOpcode)
                 (src Xmm)
                 (dst SyntheticAmode))
       (XmmMovRMImm (op SseOpcode)
                    (src Xmm)
                    (dst SyntheticAmode)
                    (imm u8))

       ;; XMM (scalar) unary op (from xmm to integer reg): movd, movq,
       ;; cvtts{s,d}2si
       (XmmToGpr (op SseOpcode)
                 (src Xmm)
                 (dst WritableGpr)
                 (dst_size OperandSize))

       ;; XMM (scalar) unary op (from xmm to integer reg): pextr{w,b,d,q}
       (XmmToGprImm (op SseOpcode)
                    (src Xmm)
                    (dst WritableGpr)
                    (imm u8))

       ;; XMM (scalar) unary op (from integer to float reg): movd, movq,
       ;; cvtsi2s{s,d}
       (GprToXmm (op SseOpcode)
                 (src GprMem)
                 (dst WritableXmm)
                 (src_size OperandSize))

       ;; Conversion from signed integers to floats, the `{v,}`cvtsi2s{s,d}`
       ;; instructions.
       ;;
       ;; Note that this is special in that `src1` is an xmm/float register
       ;; while `src2` is a general purpose register as this is converting an
       ;; integer in a gpr to an equivalent float in an xmm reg.
       (CvtIntToFloat (op SseOpcode)
                      (src1 Xmm)
                      (src2 GprMem)
                      (dst WritableXmm)
                      (src2_size OperandSize))
       (CvtIntToFloatVex (op AvxOpcode)
                         (src1 Xmm)
                         (src2 GprMem)
                         (dst WritableXmm)
                         (src2_size OperandSize))

       ;; Converts an unsigned int64 to a float32/float64.
       (CvtUint64ToFloatSeq (dst_size OperandSize) ;; 4 or 8
                            (src Gpr)
                            (dst WritableXmm)
                            (tmp_gpr1 WritableGpr)
                            (tmp_gpr2 WritableGpr))

       ;; Converts a scalar xmm to a signed int32/int64.
       (CvtFloatToSintSeq (dst_size OperandSize)
                          (src_size OperandSize)
                          (is_saturating bool)
                          (src Xmm)
                          (dst WritableGpr)
                          (tmp_gpr WritableGpr)
                          (tmp_xmm WritableXmm))

       ;; Converts a scalar xmm to an unsigned int32/int64.
       (CvtFloatToUintSeq (dst_size OperandSize)
                          (src_size OperandSize)
                          (is_saturating bool)
                          (src Xmm)
                          (dst WritableGpr)
                          (tmp_gpr WritableGpr)
                          (tmp_xmm WritableXmm)
                          (tmp_xmm2 WritableXmm))

       ;; A sequence to compute min/max with the proper NaN semantics for xmm
       ;; registers.
       (XmmMinMaxSeq (size OperandSize)
                     (is_min bool)
                     (lhs Xmm)
                     (rhs Xmm)
                     (dst WritableXmm))

       ;; Float comparisons/tests
       ;;
       ;; Compares `src1` against `src2` with `op`. Note that if you're testing
       ;; `a < b` then `src1 == a` and `src2 == b`.
       (XmmCmpRmR (op SseOpcode)
                  (src1 Xmm)
                  (src2 XmmMemAligned))

       ;; A binary XMM instruction with an 8-bit immediate: e.g. cmp (ps pd) imm
       ;; (reg addr) reg
       ;;
       ;; Note: this has to use `Reg*`, not `Xmm*`, operands because it is used
       ;; in various lane insertion and extraction instructions that move
       ;; between XMMs and GPRs.
       (XmmRmRImm (op SseOpcode)
                  (src1 Reg)
                  (src2 RegMem)
                  (dst WritableReg)
                  (imm u8)
                  (size OperandSize))

       ;; =========================================
       ;; Control flow instructions.

       ;; Direct call: call simm32.
       (CallKnown (info BoxCallInfo))

       ;; Indirect call: callq (reg mem)
       (CallUnknown (info BoxCallIndInfo))

       ;; Tail call to a direct destination.
       (ReturnCallKnown (info BoxReturnCallInfo))

       ;; Tail call to an indirect destination.
       (ReturnCallUnknown (info BoxReturnCallIndInfo))

       ;; A pseudo-instruction that captures register arguments in vregs.
       (Args
        (args VecArgPair))

       ;; A pseudo-instruction that moves vregs to return registers.
       (Rets
        (rets VecRetPair))

       ;; Return.
       (Ret (stack_bytes_to_pop u32))

       ;; Stack switching
       (StackSwitchBasic (store_context_ptr Gpr)
                         (load_context_ptr Gpr)
                         (in_payload0 Gpr)
                         (out_payload0 WritableGpr))

       ;; Jump to a known target: jmp simm32.
       (JmpKnown (dst MachLabel))

       ;; One-way conditional branch: jcond cond target.
       ;;
       ;; This instruction is useful when we have conditional jumps depending on
       ;; more than two conditions, see for instance the lowering of Brif
       ;; with Fcmp inputs.
       ;;
       ;; A note of caution: in contexts where the branch target is another
       ;; block, this has to be the same successor as the one specified in the
       ;; terminator branch of the current block.  Otherwise, this might confuse
       ;; register allocation by creating new invisible edges.
       (JmpIf (cc CC)
              (taken MachLabel))

       ;; Two-way conditional branch: jcond cond target target.
       ;;
       ;; Emitted as a compound sequence; the MachBuffer will shrink it as
       ;; appropriate.
       (JmpCond (cc CC)
                (taken MachLabel)
                (not_taken MachLabel))

       ;; Jump-table sequence, as one compound instruction (see note in lower.rs
       ;; for rationale).
       ;;
       ;; The generated code sequence is described in the emit's function match
       ;; arm for this instruction.
       ;;
       ;; See comment on jmp_table_seq below about the temporaries signedness.
       (JmpTableSeq (idx Reg)
                    (tmp1 WritableReg)
                    (tmp2 WritableReg)
                    (default_target MachLabel)
                    (targets BoxVecMachLabel))

       ;; Indirect jump: jmpq (reg mem).
       (JmpUnknown (target RegMem))

       ;; Traps if the condition code is set.
       (TrapIf (cc CC)
               (trap_code TrapCode))

       ;; Traps if both of the condition codes are set.
       (TrapIfAnd (cc1 CC)
                  (cc2 CC)
                  (trap_code TrapCode))

       ;; Traps if either of the condition codes are set.
       (TrapIfOr (cc1 CC)
                 (cc2 CC)
                 (trap_code TrapCode))

       ;; A debug trap.
       (Hlt)

       ;; An instruction that will always trigger the illegal instruction
       ;; exception.
       (Ud2 (trap_code TrapCode))

       ;; Loads an external symbol in a register, with a relocation:
       ;;
       ;; movq $name@GOTPCREL(%rip), dst    if PIC is enabled, or
       ;; lea $name($rip), dst              if distance is near, or
       ;; movabsq $name, dst                otherwise.
       (LoadExtName (dst WritableReg)
                    (name BoxExternalName)
                    (offset i64)
                    (distance RelocDistance))

       ;; =========================================
       ;; Instructions pertaining to atomic memory accesses.

       ;; A standard (native) `lock cmpxchg src, (amode)`, with register
       ;; conventions:
       ;;
       ;; `mem`          (read) address
       ;; `replacement`  (read) replacement value
       ;; %rax           (modified) in: expected value, out: value that was actually at `dst`
       ;; %rflags is written.  Do not assume anything about it after the instruction.
       ;;
       ;; The instruction "succeeded" iff the lowest `ty` bits of %rax
       ;; afterwards are the same as they were before.
       (LockCmpxchg (ty Type) ;; I8, I16, I32, or I64
                    (replacement Reg)
                    (expected Reg)
                    (mem SyntheticAmode)
                    (dst_old WritableReg))

       ;; A synthetic instruction, based on a loop around a native `lock
       ;; cmpxchg` instruction.
       ;;
       ;; This atomically modifies a value in memory and returns the old value.
       ;; The sequence consists of an initial "normal" load from `dst`, followed
       ;; by a loop which computes the new value and tries to compare-and-swap
       ;; ("CAS") it into `dst`, using the native instruction `lock
       ;; cmpxchg{b,w,l,q}`.  The loop iterates until the CAS is successful. If
       ;; there is no contention, there will be only one pass through the loop
       ;; body.  The sequence does *not* perform any explicit memory fence
       ;; instructions (`mfence`/`sfence`/`lfence`).
       ;;
       ;; Note that the transaction is atomic in the sense that, as observed by
       ;; some other thread, `dst` either has the initial or final value, but no
       ;; other.  It isn't atomic in the sense of guaranteeing that no other
       ;; thread writes to `dst` in between the initial load and the CAS -- but
       ;; that would cause the CAS to fail unless the other thread's last write
       ;; before the CAS wrote the same value that was already there.  In other
       ;; words, this implementation suffers (unavoidably) from the A-B-A
       ;; problem.
       ;;
       ;; This instruction sequence has fixed register uses as follows:
       ;; - %rax  (written) the old value at `mem`
       ;; - %rflags is written.  Do not assume anything about it after the
       ;;   instruction.
       (AtomicRmwSeq (ty Type) ;; I8, I16, I32, or I64
                     (op MachAtomicRmwOp)
                     (mem SyntheticAmode)
                     (operand Reg)
                     (temp WritableReg)
                     (dst_old WritableReg))

       ;; A memory fence (mfence, lfence or sfence).
       (Fence (kind FenceKind))

       ;; =========================================
       ;; Meta-instructions generating no code.

       ;; Provides a way to tell the register allocator that the upcoming
       ;; sequence of instructions will overwrite `dst` so it should be
       ;; considered as a `def`; use this with care.
       ;;
       ;; This is useful when we have a sequence of instructions whose register
       ;; usages are nominally `mod`s, but such that the combination of
       ;; operations creates a result that is independent of the initial
       ;; register value. It's thus semantically a `def`, not a `mod`, when all
       ;; the instructions are taken together, so we want to ensure the register
       ;; is defined (its live-range starts) prior to the sequence to keep
       ;; analyses happy.
       ;;
       ;; One alternative would be a compound instruction that somehow
       ;; encapsulates the others and reports its own `def`s/`use`s/`mod`s; this
       ;; adds complexity (the instruction list is no longer flat) and requires
       ;; knowledge about semantics and initial-value independence anyway.
       (XmmUninitializedValue (dst WritableXmm))

       ;; A call to the `ElfTlsGetAddr` libcall. Returns address of TLS symbol
       ;; `dst`, which is constrained to `rax`.
       (ElfTlsGetAddr (symbol ExternalName)
                      (dst WritableGpr))

       ;; A Mach-O TLS symbol access. Returns address of the TLS symbol in
       ;; `dst`, which is constrained to `rax`.
       (MachOTlsGetAddr (symbol ExternalName)
                        (dst WritableGpr))

       ;; A Coff TLS symbol access. Returns address of the TLS symbol in
       ;; `dst`, which is constrained to `rax`.
       (CoffTlsGetAddr (symbol ExternalName)
                       (dst WritableGpr)
                       (tmp WritableGpr))

       ;; An unwind pseudoinstruction describing the state of the machine at
       ;; this program point.
       (Unwind (inst UnwindInst))

       ;; A pseudoinstruction that just keeps a value alive.
       (DummyUse (reg Reg))))

(type OperandSize extern
      (enum Size8
            Size16
            Size32
            Size64))

(type DivSignedness
      (enum Signed
            Unsigned))

(type FenceKind extern
      (enum MFence
            LFence
            SFence))

(type BoxCallInfo extern (enum))
(type BoxCallIndInfo extern (enum))
(type BoxReturnCallInfo extern (enum))
(type BoxReturnCallIndInfo extern (enum))

;; Get the `OperandSize` for a given `Type`, rounding smaller types up to 32 bits.
(decl operand_size_of_type_32_64 (Type) OperandSize)
(extern constructor operand_size_of_type_32_64 operand_size_of_type_32_64)

;; Get the true `OperandSize` for a given `Type`, with no rounding.
(decl raw_operand_size_of_type (Type) OperandSize)
(extern constructor raw_operand_size_of_type raw_operand_size_of_type)

;; Get the bit width of an `OperandSize`.
(decl operand_size_bits (OperandSize) u16)
(rule (operand_size_bits (OperandSize.Size8)) 8)
(rule (operand_size_bits (OperandSize.Size16)) 16)
(rule (operand_size_bits (OperandSize.Size32)) 32)
(rule (operand_size_bits (OperandSize.Size64)) 64)

(type AluRmiROpcode extern
      (enum Add
            Adc
            Sub
            Sbb
            And
            Or
            Xor))

(type AluRmROpcode
      (enum Andn
            Sarx
            Shrx
            Shlx
            Bzhi))

(type UnaryRmROpcode extern
      (enum Bsr
            Bsf
            Lzcnt
            Tzcnt
            Popcnt))

(type UnaryRmRVexOpcode
      (enum Blsi
            Blsmsk
            Blsr))

(type UnaryRmRImmVexOpcode
      (enum Rorx))

(type SseOpcode extern
      (enum Addps
            Addpd
            Addss
            Addsd
            Andps
            Andpd
            Andnps
            Andnpd
            Blendvpd
            Blendvps
            Comiss
            Comisd
            Cmpps
            Cmppd
            Cmpss
            Cmpsd
            Cvtdq2ps
            Cvtdq2pd
            Cvtpd2ps
            Cvtps2pd
            Cvtsd2ss
            Cvtsd2si
            Cvtsi2ss
            Cvtsi2sd
            Cvtss2si
            Cvtss2sd
            Cvttpd2dq
            Cvttps2dq
            Cvttss2si
            Cvttsd2si
            Divps
            Divpd
            Divss
            Divsd
            Insertps
            Maxps
            Maxpd
            Maxss
            Maxsd
            Minps
            Minpd
            Minss
            Minsd
            Movaps
            Movapd
            Movd
            Movdqa
            Movdqu
            Movlhps
            Movmskps
            Movmskpd
            Movq
            Movss
            Movsd
            Movups
            Movupd
            Mulps
            Mulpd
            Mulss
            Mulsd
            Orps
            Orpd
            Pabsb
            Pabsw
            Pabsd
            Packssdw
            Packsswb
            Packusdw
            Packuswb
            Paddb
            Paddd
            Paddq
            Paddw
            Paddsb
            Paddsw
            Paddusb
            Paddusw
            Palignr
            Pand
            Pandn
            Pavgb
            Pavgw
            Pblendvb
            Pcmpeqb
            Pcmpeqw
            Pcmpeqd
            Pcmpeqq
            Pcmpgtb
            Pcmpgtw
            Pcmpgtd
            Pcmpgtq
            Pextrb
            Pextrw
            Pextrd
            Pextrq
            Pinsrb
            Pinsrw
            Pinsrd
            Pmaddubsw
            Pmaddwd
            Pmaxsb
            Pmaxsw
            Pmaxsd
            Pmaxub
            Pmaxuw
            Pmaxud
            Pminsb
            Pminsw
            Pminsd
            Pminub
            Pminuw
            Pminud
            Pmovmskb
            Pmovsxbd
            Pmovsxbw
            Pmovsxbq
            Pmovsxwd
            Pmovsxwq
            Pmovsxdq
            Pmovzxbd
            Pmovzxbw
            Pmovzxbq
            Pmovzxwd
            Pmovzxwq
            Pmovzxdq
            Pmuldq
            Pmulhw
            Pmulhuw
            Pmulhrsw
            Pmulld
            Pmullw
            Pmuludq
            Por
            Pshufb
            Pshufd
            Psllw
            Pslld
            Psllq
            Psraw
            Psrad
            Psrlw
            Psrld
            Psrlq
            Psubb
            Psubd
            Psubq
            Psubw
            Psubsb
            Psubsw
            Psubusb
            Psubusw
            Ptest
            Punpckhbw
            Punpckhwd
            Punpcklbw
            Punpcklwd
            Pxor
            Rcpss
            Roundps
            Roundpd
            Roundss
            Roundsd
            Rsqrtss
            Shufps
            Sqrtps
            Sqrtpd
            Sqrtss
            Sqrtsd
            Subps
            Subpd
            Subss
            Subsd
            Ucomiss
            Ucomisd
            Unpcklps
            Unpcklpd
            Unpckhps
            Xorps
            Xorpd
            Phaddw
            Phaddd
            Punpckhdq
            Punpckldq
            Punpckhqdq
            Punpcklqdq
            Pshuflw
            Pshufhw
            Pblendw
            Movddup
          ))

(type CmpOpcode extern
      (enum Cmp
            Test))

(type RegMemImm extern
      (enum
       (Reg (reg Reg))
       (Mem (addr SyntheticAmode))
       (Imm (simm32 u32))))

;; Put the given clif value into a `RegMemImm` operand.
;;
;; Asserts that the value fits into a single register, and doesn't require
;; multiple registers for its representation (like `i128` for example).
;;
;; As a side effect, this marks the value as used.
(decl put_in_reg_mem_imm (Value) RegMemImm)
(extern constructor put_in_reg_mem_imm put_in_reg_mem_imm)

(type RegMem extern
      (enum
       (Reg (reg Reg))
       (Mem (addr SyntheticAmode))))

;; Convert a RegMem to a RegMemImm.
(decl reg_mem_to_reg_mem_imm (RegMem) RegMemImm)
(rule (reg_mem_to_reg_mem_imm (RegMem.Reg reg))
      (RegMemImm.Reg reg))
(rule (reg_mem_to_reg_mem_imm (RegMem.Mem addr))
      (RegMemImm.Mem addr))

;; Put the given clif value into a `RegMem` operand.
;;
;; Asserts that the value fits into a single register, and doesn't require
;; multiple registers for its representation (like `i128` for example).
;;
;; As a side effect, this marks the value as used.
(decl put_in_reg_mem (Value) RegMem)
(extern constructor put_in_reg_mem put_in_reg_mem)

;; Addressing modes.

(type SyntheticAmode extern (enum))

(decl synthetic_amode_to_reg_mem (SyntheticAmode) RegMem)
(extern constructor synthetic_amode_to_reg_mem synthetic_amode_to_reg_mem)

(decl amode_to_synthetic_amode (Amode) SyntheticAmode)
(extern constructor amode_to_synthetic_amode amode_to_synthetic_amode)

;; An `Amode` represents a possible addressing mode that can be used
;; in instructions. These denote a 64-bit value only.
(type Amode (enum
             ;; Immediate sign-extended and a register
             (ImmReg (simm32 i32)
                     (base Reg)
                     (flags MemFlags))

             ;; Sign-extend-32-to-64(simm32) + base + (index << shift)
             (ImmRegRegShift (simm32 i32)
                             (base Gpr)
                             (index Gpr)
                             (shift u8)
                             (flags MemFlags))

             ;; Sign-extend-32-to-64(immediate) + RIP (instruction
             ;; pointer). The appropriate relocation is emitted so
             ;; that the resulting immediate makes this Amode refer to
             ;; the given MachLabel.
             (RipRelative (target MachLabel))))

;; A helper to both check that the `Imm64` and `Offset32` values sum to less
;; than 32-bits AND return this summed `u32` value. Also, the `Imm64` will be
;; zero-extended from `Type` up to 64 bits. This is useful for `to_amode`.
(decl pure partial sum_extend_fits_in_32_bits (Type Imm64 Offset32) u32)
(extern constructor sum_extend_fits_in_32_bits sum_extend_fits_in_32_bits)

;;;; Amode lowering ;;;;

;; Converts a `Value` and a static offset into an `Amode` for x64, attempting
;; to be as fancy as possible with offsets/registers/shifts/etc to make maximal
;; use of the x64 addressing modes.
;;
;; This is a bit subtle unfortunately due to a few constraints. This function
;; was originally written recursively but that can lead to stack overflow
;; for certain inputs due to the recursion being defined by user-controlled
;; input. This means that nowadays this function is not recursive and has a
;; specific structure to handle that.
;;
;; Additionally currently in CLIF all loads/stores have an `Offset32` immediate
;; to go with them, but the wasm lowering to CLIF doesn't use this meaning that
;; it's frequently 0. Additionally mid-end optimizations do not fold `iconst`
;; values into this `Offset32`, meaning that it's left up to backends to hunt
;; for constants for good codegen. That means that one important aspect of this
;; function is that it searches for constants to fold into the `Offset32` to
;; avoid unnecessary instructions.
;;
;; Note, though, that the "optimal addressing modes" are only guaranteed to be
;; generated if egraph-based optimizations have run. For example this will only
;; attempt to find one constant as opposed to many, and that'll only happen
;; with constant folding from optimizations.
;;
;; Finally there's two primary entry points for this function. One is this
;; function here, `to_amode,` and another is `to_amode_add`. The latter is used
;; by the lowering of `iadd` in the x64 backend to use the `lea` instruction
;; where the input is two `Value` operands instead of just one. Most of the
;; logic here is then deferred through `to_amode_add`.
;;
;; In the future if mid-end optimizations fold constants into `Offset32` then
;; this in theory can "simply" delegate to the `amode_imm_reg` helper, and
;; below can delegate to `amode_imm_reg_reg_shift`, or something like that.
(decl to_amode (MemFlags Value Offset32) Amode)
(rule 0 (to_amode flags base offset)
        (amode_imm_reg flags base offset))
(rule 1 (to_amode flags (iadd x y) offset)
        (to_amode_add flags x y offset))

;; Same as `to_amode`, except that the base address is computed via the addition
;; of the two `Value` arguments provided.
;;
;; The primary purpose of this is to hunt for constants within the two `Value`
;; operands provided. Failing that this will defer to `amode_imm_reg` or
;; `amode_imm_reg_reg_shift` which is the final step in amode lowering and
;; performs final pattern matches related to shifts to see if that can be
;; peeled out into the amode.
;;
;; In other words this function's job is to find constants and then defer to
;; `amode_imm_reg*`.
(decl to_amode_add (MemFlags Value Value Offset32) Amode)

(rule 0 (to_amode_add flags x y offset)
        (amode_imm_reg_reg_shift flags x y offset))
(rule 1 (to_amode_add flags x (i32_from_iconst c) offset)
        (if-let sum (s32_add_fallible offset c))
        (amode_imm_reg flags x sum))
(rule 2 (to_amode_add flags (i32_from_iconst c) x offset)
        (if-let sum (s32_add_fallible offset c))
        (amode_imm_reg flags x sum))
(rule 3 (to_amode_add flags (iadd x (i32_from_iconst c)) y offset)
        (if-let sum (s32_add_fallible offset c))
        (amode_imm_reg_reg_shift flags x y sum))
(rule 4 (to_amode_add flags (iadd (i32_from_iconst c) x) y offset)
        (if-let sum (s32_add_fallible offset c))
        (amode_imm_reg_reg_shift flags x y sum))
(rule 5 (to_amode_add flags x (iadd y (i32_from_iconst c)) offset)
        (if-let sum (s32_add_fallible offset c))
        (amode_imm_reg_reg_shift flags x y sum))
(rule 6 (to_amode_add flags x (iadd (i32_from_iconst c) y) offset)
        (if-let sum (s32_add_fallible offset c))
        (amode_imm_reg_reg_shift flags x y sum))

;; Final cases of amode lowering. Does not hunt for constants and only attempts
;; to pattern match add-of-shifts to generate fancier `ImmRegRegShift` modes,
;; otherwise falls back on `ImmReg`.
(decl amode_imm_reg (MemFlags Value Offset32) Amode)
(rule 0 (amode_imm_reg flags base offset)
        (Amode.ImmReg offset base flags))
(rule 1 (amode_imm_reg flags (iadd x y) offset)
        (amode_imm_reg_reg_shift flags x y offset))

(decl amode_imm_reg_reg_shift (MemFlags Value Value Offset32) Amode)
(rule 0 (amode_imm_reg_reg_shift flags x y offset)
        (Amode.ImmRegRegShift offset x y 0 flags)) ;; 0 == y<<0 == "no shift"
(rule 1 (amode_imm_reg_reg_shift flags x (ishl y (iconst (uimm8 shift))) offset)
        (if (u32_lteq (u8_as_u32 shift) 3))
        (Amode.ImmRegRegShift offset x y shift flags))
(rule 2 (amode_imm_reg_reg_shift flags (ishl y (iconst (uimm8 shift))) x offset)
        (if (u32_lteq (u8_as_u32 shift) 3))
        (Amode.ImmRegRegShift offset x y shift flags))

;; Offsetting an Amode. Used when we need to do consecutive
;; loads/stores to adjacent addresses.
(decl amode_offset (Amode i32) Amode)
(extern constructor amode_offset amode_offset)

;; Return a zero offset as an `Offset32`.
(decl zero_offset () Offset32)
(extern constructor zero_offset zero_offset)

;; Shift kinds.

(type ShiftKind extern
      (enum ShiftLeft
            ShiftRightLogical
            ShiftRightArithmetic
            RotateLeft
            RotateRight))

(type Imm8Reg extern
      (enum (Imm8 (imm u8))
            (Reg (reg Reg))))

;; Put the given clif value into a `Imm8Reg` operand, masked to the bit width of
;; the given type.
;;
;; Asserts that the value fits into a single register, and doesn't require
;; multiple registers for its representation (like `i128` for example).
;;
;; As a side effect, this marks the value as used.
;;
;; This is used when lowering various shifts and rotates.
(decl put_masked_in_imm8_gpr (Value Type) Imm8Gpr)
(rule 2 (put_masked_in_imm8_gpr (u64_from_iconst amt) ty)
      (const_to_type_masked_imm8 amt ty))
(rule 1 (put_masked_in_imm8_gpr amt (fits_in_16 ty))
      (x64_and $I64 (value_regs_get_gpr amt 0) (RegMemImm.Imm (shift_mask ty))))
(rule (put_masked_in_imm8_gpr amt ty)
      (value_regs_get_gpr amt 0))

;; Condition codes
(type CC extern
      (enum O
            NO
            B
            NB
            Z
            NZ
            BE
            NBE
            S
            NS
            L
            NL
            LE
            NLE
            P
            NP))

(decl intcc_to_cc (IntCC) CC)
(extern constructor intcc_to_cc intcc_to_cc)

(decl cc_invert (CC) CC)
(extern constructor cc_invert cc_invert)

;; Fails if the argument is not either CC.NZ or CC.Z.
(decl cc_nz_or_z (CC) CC)
(extern extractor cc_nz_or_z cc_nz_or_z)

(type AvxOpcode
      (enum Vfmadd213ss
            Vfmadd213sd
            Vfmadd213ps
            Vfmadd213pd
            Vfmadd132ss
            Vfmadd132sd
            Vfmadd132ps
            Vfmadd132pd
            Vfnmadd213ss
            Vfnmadd213sd
            Vfnmadd213ps
            Vfnmadd213pd
            Vfnmadd132ss
            Vfnmadd132sd
            Vfnmadd132ps
            Vfnmadd132pd
            Vfmsub213ss
            Vfmsub213sd
            Vfmsub213ps
            Vfmsub213pd
            Vfmsub132ss
            Vfmsub132sd
            Vfmsub132ps
            Vfmsub132pd
            Vfnmsub213ss
            Vfnmsub213sd
            Vfnmsub213ps
            Vfnmsub213pd
            Vfnmsub132ss
            Vfnmsub132sd
            Vfnmsub132ps
            Vfnmsub132pd
            Vcmpps
            Vcmppd
            Vpsrlw
            Vpsrld
            Vpsrlq
            Vpaddb
            Vpaddw
            Vpaddd
            Vpaddq
            Vpaddsb
            Vpaddsw
            Vpaddusb
            Vpaddusw
            Vpsubb
            Vpsubw
            Vpsubd
            Vpsubq
            Vpsubsb
            Vpsubsw
            Vpsubusb
            Vpsubusw
            Vpavgb
            Vpavgw
            Vpand
            Vandps
            Vandpd
            Vpor
            Vorps
            Vorpd
            Vpxor
            Vxorps
            Vxorpd
            Vpmullw
            Vpmulld
            Vpmulhw
            Vpmulhd
            Vpmulhrsw
            Vpmulhuw
            Vpmuldq
            Vpmuludq
            Vpunpckhwd
            Vpunpcklwd
            Vunpcklps
            Vunpcklpd
            Vunpckhps
            Vandnps
            Vandnpd
            Vpandn
            Vaddps
            Vaddpd
            Vsubps
            Vsubpd
            Vmulps
            Vmulpd
            Vdivps
            Vdivpd
            Vpcmpeqb
            Vpcmpeqw
            Vpcmpeqd
            Vpcmpeqq
            Vpcmpgtb
            Vpcmpgtw
            Vpcmpgtd
            Vpcmpgtq
            Vminps
            Vminpd
            Vmaxps
            Vmaxpd
            Vblendvpd
            Vblendvps
            Vpblendvb
            Vmovlhps
            Vpmaxsb
            Vpmaxsw
            Vpmaxsd
            Vpminsb
            Vpminsw
            Vpminsd
            Vpmaxub
            Vpmaxuw
            Vpmaxud
            Vpminub
            Vpminuw
            Vpminud
            Vpunpcklbw
            Vpunpckhbw
            Vpacksswb
            Vpackssdw
            Vpackuswb
            Vpackusdw
            Vpalignr
            Vpinsrb
            Vpinsrw
            Vpinsrd
            Vpinsrq
            Vpmaddwd
            Vpmaddubsw
            Vinsertps
            Vpshufb
            Vshufps
            Vpsllw
            Vpslld
            Vpsllq
            Vpsraw
            Vpsrad
            Vpmovsxbw
            Vpmovzxbw
            Vpmovsxwd
            Vpmovzxwd
            Vpmovsxdq
            Vpmovzxdq
            Vaddss
            Vaddsd
            Vmulss
            Vmulsd
            Vsubss
            Vsubsd
            Vdivss
            Vdivsd
            Vpabsb
            Vpabsw
            Vpabsd
            Vminss
            Vminsd
            Vmaxss
            Vmaxsd
            Vsqrtps
            Vsqrtpd
            Vroundps
            Vroundpd
            Vcvtdq2pd
            Vcvtdq2ps
            Vcvtpd2ps
            Vcvtps2pd
            Vcvttpd2dq
            Vcvttps2dq
            Vphaddw
            Vphaddd
            Vpunpckhdq
            Vpunpckldq
            Vpunpckhqdq
            Vpunpcklqdq
            Vpshuflw
            Vpshufhw
            Vpshufd
            Vmovss
            Vmovsd
            Vmovups
            Vmovupd
            Vmovdqu
            Vpextrb
            Vpextrw
            Vpextrd
            Vpextrq
            Vpblendw
            Vmovddup
            Vpbroadcastb
            Vpbroadcastw
            Vpbroadcastd
            Vbroadcastss
            Vmovd
            Vmovq
            Vmovmskps
            Vmovmskpd
            Vpmovmskb
            Vcvtsi2ss
            Vcvtsi2sd
            Vcvtss2sd
            Vcvtsd2ss
            Vsqrtss
            Vsqrtsd
            Vroundss
            Vroundsd
            Vucomiss
            Vucomisd
            Vptest
          ))

(type Avx512Opcode
      (enum Vcvtudq2ps
            Vpabsq
            Vpermi2b
            Vpmullq
            Vpopcntb
            Vpsraq
            VpsraqImm))

(type FcmpImm extern
      (enum Equal
            LessThan
            LessThanOrEqual
            Unordered
            NotEqual
            UnorderedOrGreaterThanOrEqual
            UnorderedOrGreaterThan
            Ordered))

(decl encode_fcmp_imm (FcmpImm) u8)
(extern constructor encode_fcmp_imm encode_fcmp_imm)

(type RoundImm extern
      (enum RoundNearest
            RoundDown
            RoundUp
            RoundZero))

(decl encode_round_imm (RoundImm) u8)
(extern constructor encode_round_imm encode_round_imm)

;;;; Newtypes for Different Register Classes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(type Gpr (primitive Gpr))
(type WritableGpr (primitive WritableGpr))
(type OptionWritableGpr (primitive OptionWritableGpr))
(type GprMem extern (enum))
(type GprMemImm extern (enum))
(type Imm8Gpr extern (enum))

(type Xmm (primitive Xmm))
(type WritableXmm (primitive WritableXmm))
(type OptionWritableXmm (primitive OptionWritableXmm))
(type XmmMem extern (enum))
(type XmmMemAligned extern (enum))
(type XmmMemImm extern (enum))
(type XmmMemAlignedImm extern (enum))

;; Convert an `Imm8Reg` into an `Imm8Gpr`.
(decl imm8_reg_to_imm8_gpr (Imm8Reg) Imm8Gpr)
(extern constructor imm8_reg_to_imm8_gpr imm8_reg_to_imm8_gpr)

;; Convert an `Imm8Gpr` into a `Gpr`.
(decl gpr_from_imm8_gpr (Gpr) Imm8Gpr)
(extern extractor gpr_from_imm8_gpr gpr_from_imm8_gpr)

;; Convert an `Imm8Gpr` into an `Imm8`.
(decl imm8_from_imm8_gpr (u8) Imm8Gpr)
(extern extractor imm8_from_imm8_gpr imm8_from_imm8_gpr)

;; Convert a `WritableGpr` to a `WritableReg`.
(decl writable_gpr_to_reg (WritableGpr) WritableReg)
(extern constructor writable_gpr_to_reg writable_gpr_to_reg)

;; Convert a `WritableXmm` to a `WritableReg`.
(decl writable_xmm_to_reg (WritableXmm) WritableReg)
(extern constructor writable_xmm_to_reg writable_xmm_to_reg)

;; Convert a `WritableReg` to a `WritableXmm`.
(decl writable_reg_to_xmm (WritableReg) WritableXmm)
(extern constructor writable_reg_to_xmm writable_reg_to_xmm)

;; Convert a `WritableXmm` to an `Xmm`.
(decl writable_xmm_to_xmm (WritableXmm) Xmm)
(extern constructor writable_xmm_to_xmm writable_xmm_to_xmm)

;; Convert a `WritableGpr` to an `Gpr`.
(decl writable_gpr_to_gpr (WritableGpr) Gpr)
(extern constructor writable_gpr_to_gpr writable_gpr_to_gpr)

;; Convert an `Gpr` to a `Reg`.
(decl gpr_to_reg (Gpr) Reg)
(extern constructor gpr_to_reg gpr_to_reg)

;; Convert an `Gpr` to a `GprMem`.
(decl gpr_to_gpr_mem (Gpr) GprMem)
(extern constructor gpr_to_gpr_mem gpr_to_gpr_mem)

;; Convert an `Gpr` to a `GprMemImm`.
(decl gpr_to_gpr_mem_imm (Gpr) GprMemImm)
(extern constructor gpr_to_gpr_mem_imm gpr_to_gpr_mem_imm)

;; Convert an `Xmm` to a `Reg`.
(decl xmm_to_reg (Xmm) Reg)
(extern constructor xmm_to_reg xmm_to_reg)

;; Convert an `Xmm` into an `XmmMemImm`.
(decl xmm_to_xmm_mem_imm (Xmm) XmmMemImm)
(extern constructor xmm_to_xmm_mem_imm xmm_to_xmm_mem_imm)

;; Convert an `XmmMem` into an `XmmMemImm`.
(decl xmm_mem_to_xmm_mem_imm (XmmMem) XmmMemImm)
(extern constructor xmm_mem_to_xmm_mem_imm xmm_mem_to_xmm_mem_imm)

;; Convert an `XmmMem` into an `XmmMemAligned`.
;;
;; Note that this is an infallible conversion, not a fallible one. If the
;; original `XmmMem` source is a register, then it's passed through directly.
;; If it's `Mem` and refers to aligned memory, it's also passed through
;; directly. Otherwise, though, it's a memory source which is not aligned to
;; 16 bytes so a load is performed and the temporary register which is the
;; result of the load is passed through. The end-result is that the return value
;; here is guaranteed to be a register or an aligned memory location.
(decl xmm_mem_to_xmm_mem_aligned (XmmMem) XmmMemAligned)
(extern constructor xmm_mem_to_xmm_mem_aligned xmm_mem_to_xmm_mem_aligned)

;; Convert an `XmmMemImm` into an `XmmMemImmAligned`.
;;
;; Note that this is the same as `xmm_mem_to_xmm_mem_aligned` except it handles
;; an immediate case as well.
(decl xmm_mem_imm_to_xmm_mem_aligned_imm (XmmMemImm) XmmMemAlignedImm)
(extern constructor xmm_mem_imm_to_xmm_mem_aligned_imm xmm_mem_imm_to_xmm_mem_aligned_imm)

;; Allocate a new temporary GPR register.
(decl temp_writable_gpr () WritableGpr)
(extern constructor temp_writable_gpr temp_writable_gpr)

;; Allocate a new temporary XMM register.
(decl temp_writable_xmm () WritableXmm)
(extern constructor temp_writable_xmm temp_writable_xmm)

;; Construct a new `XmmMem` from the given `RegMem`.
;;
;; Asserts that the `RegMem`'s register, if any, is an XMM register.
(decl reg_mem_to_xmm_mem (RegMem) XmmMem)
(extern constructor reg_mem_to_xmm_mem reg_mem_to_xmm_mem)

;; Construct a new `RegMemImm` from the given `Reg`.
(decl reg_to_reg_mem_imm (Reg) RegMemImm)
(extern constructor reg_to_reg_mem_imm reg_to_reg_mem_imm)

;; Construct a new `GprMemImm` from the given `RegMemImm`.
;;
;; Asserts that the `RegMemImm`'s register, if any, is an GPR register.
(decl gpr_mem_imm_new (RegMemImm) GprMemImm)
(extern constructor gpr_mem_imm_new gpr_mem_imm_new)

;; Construct a new `XmmMemImm` from the given `RegMemImm`.
;;
;; Asserts that the `RegMemImm`'s register, if any, is an XMM register.
(decl xmm_mem_imm_new (RegMemImm) XmmMemImm)
(extern constructor xmm_mem_imm_new xmm_mem_imm_new)

;; Construct a new `XmmMem` from an `Xmm`.
(decl xmm_to_xmm_mem (Xmm) XmmMem)
(extern constructor xmm_to_xmm_mem xmm_to_xmm_mem)

;; Construct a new `XmmMem` from an `RegMem`.
(decl pure xmm_mem_to_reg_mem (XmmMem) RegMem)
(extern constructor xmm_mem_to_reg_mem xmm_mem_to_reg_mem)

;; Convert a `GprMem` to a `RegMem`.
(decl gpr_mem_to_reg_mem (GprMem) RegMem)
(extern constructor gpr_mem_to_reg_mem gpr_mem_to_reg_mem)

;; Construct a new `Xmm` from a `Reg`.
;;
;; Asserts that the register is a XMM.
(decl xmm_new (Reg) Xmm)
(extern constructor xmm_new xmm_new)

;; Construct a new `Gpr` from a `Reg`.
;;
;; Asserts that the register is a GPR.
(decl gpr_new (Reg) Gpr)
(extern constructor gpr_new gpr_new)

;; Construct a new `GprMem` from a `RegMem`.
;;
;; Asserts that the `RegMem`'s register, if any, is a GPR.
(decl reg_mem_to_gpr_mem (RegMem) GprMem)
(extern constructor reg_mem_to_gpr_mem reg_mem_to_gpr_mem)

;; Construct a `GprMem` from a `Reg`.
;;
;; Asserts that the `Reg` is a GPR.
(decl reg_to_gpr_mem (Reg) GprMem)
(extern constructor reg_to_gpr_mem reg_to_gpr_mem)

;; Construct a `GprMemImm` from a `Reg`.
;;
;; Asserts that the `Reg` is a GPR.
(decl reg_to_gpr_mem_imm (Reg) GprMemImm)
(rule (reg_to_gpr_mem_imm r)
      (gpr_to_gpr_mem_imm (gpr_new r)))

;; Put a value into a GPR.
;;
;; Moves the value into a GPR if it is a type that would naturally go into an
;; XMM register.
(decl put_in_gpr (Value) Gpr)

;; Case for when the value naturally lives in a GPR.
(rule (put_in_gpr val)
      (if-let (value_type ty) val)
      (if-let (type_register_class (RegisterClass.Gpr _)) ty)
      (gpr_new (put_in_reg val)))

;; Case for when the value naturally lives in an XMM register and we must
;; bitcast it from an XMM into a GPR.
(rule (put_in_gpr val)
      (if-let (value_type ty) val)
      (if-let (type_register_class (RegisterClass.Xmm)) ty)
      (bitcast_xmm_to_gpr (ty_bits ty) (xmm_new (put_in_reg val))))

;; Put a value into a `GprMem`.
;;
;; Asserts that the value goes into a GPR.
(decl put_in_gpr_mem (Value) GprMem)
(rule (put_in_gpr_mem val)
      (reg_mem_to_gpr_mem (put_in_reg_mem val)))

;; Put a value into a `GprMemImm`.
;;
;; Asserts that the value goes into a GPR.
(decl put_in_gpr_mem_imm (Value) GprMemImm)
(rule (put_in_gpr_mem_imm val)
      (gpr_mem_imm_new (put_in_reg_mem_imm val)))

;; Put a value into a XMM.
;;
;; Asserts that the value goes into a XMM.
(decl put_in_xmm (Value) Xmm)
(rule (put_in_xmm val)
      (xmm_new (put_in_reg val)))

;; Put a value into a `XmmMem`.
;;
;; Asserts that the value goes into a XMM.
(decl put_in_xmm_mem (Value) XmmMem)
(extern constructor put_in_xmm_mem put_in_xmm_mem)

;; Put a value into a `XmmMemImm`.
;;
;; Asserts that the value goes into a XMM.
(decl put_in_xmm_mem_imm (Value) XmmMemImm)
(extern constructor put_in_xmm_mem_imm put_in_xmm_mem_imm)

;; Construct an `InstOutput` out of a single GPR register.
(decl output_gpr (Gpr) InstOutput)
(rule (output_gpr x)
      (output_reg (gpr_to_reg x)))

;; Construct a `ValueRegs` out of two GPR registers.
(decl value_gprs (Gpr Gpr) ValueRegs)
(rule (value_gprs x y)
      (value_regs (gpr_to_reg x) (gpr_to_reg y)))

;; Construct an `InstOutput` out of a single XMM register.
(decl output_xmm (Xmm) InstOutput)
(rule (output_xmm x)
      (output_reg (xmm_to_reg x)))

;; Get the `n`th reg in a `ValueRegs` and construct a GPR from it.
;;
;; Asserts that the register is a GPR.
(decl value_regs_get_gpr (ValueRegs usize) Gpr)
(rule (value_regs_get_gpr regs n)
      (gpr_new (value_regs_get regs n)))

;; Convert a `Gpr` to an `Imm8Gpr`.
(decl gpr_to_imm8_gpr (Gpr) Imm8Gpr)
(extern constructor gpr_to_imm8_gpr gpr_to_imm8_gpr)

;; Convert an 8-bit immediate into an `Imm8Gpr`.
(decl imm8_to_imm8_gpr (u8) Imm8Gpr)
(extern constructor imm8_to_imm8_gpr imm8_to_imm8_gpr)

;; Get the low half of the given `Value` as a GPR.
(decl lo_gpr (Value) Gpr)
(rule (lo_gpr regs) (gpr_new (lo_reg regs)))

;; Construct a new `XmmMemImm` from a 32-bit immediate.
(decl xmi_imm (u32) XmmMemImm)
(extern constructor xmi_imm xmi_imm)

;;;; Helpers for determining the register class of a value type ;;;;;;;;;;;;;;;;

(type RegisterClass
      (enum
        (Gpr (single_register bool))
        (Xmm)))

(decl type_register_class (RegisterClass) Type)
(extern extractor type_register_class type_register_class)

(decl is_xmm_type (Type) Type)
(extractor (is_xmm_type ty) (and (type_register_class (RegisterClass.Xmm)) ty))

(decl is_gpr_type (Type) Type)
(extractor (is_gpr_type ty) (and (type_register_class (RegisterClass.Gpr _)) ty))

(decl is_single_register_gpr_type (Type) Type)
(extractor (is_single_register_gpr_type ty)
           (and (type_register_class (RegisterClass.Gpr $true)) ty))

(decl is_multi_register_gpr_type (Type) Type)
(extractor (is_multi_register_gpr_type ty)
           (and (type_register_class (RegisterClass.Gpr $false)) ty))

;;;; Helpers for Querying Enabled ISA Extensions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(decl pure use_avx512vl () bool)
(extern constructor use_avx512vl use_avx512vl)

(decl pure use_avx512dq () bool)
(extern constructor use_avx512dq use_avx512dq)

(decl pure use_avx512f () bool)
(extern constructor use_avx512f use_avx512f)

(decl pure use_avx512bitalg () bool)
(extern constructor use_avx512bitalg use_avx512bitalg)

(decl pure use_avx512vbmi () bool)
(extern constructor use_avx512vbmi use_avx512vbmi)

(decl pure use_lzcnt () bool)
(extern constructor use_lzcnt use_lzcnt)

(decl pure use_bmi1 () bool)
(extern constructor use_bmi1 use_bmi1)

(decl pure use_bmi2 () bool)
(extern constructor use_bmi2 use_bmi2)

(decl pure use_popcnt () bool)
(extern constructor use_popcnt use_popcnt)

(decl pure use_fma () bool)
(extern constructor use_fma use_fma)

(decl pure use_ssse3 () bool)
(extern constructor use_ssse3 use_ssse3)

(decl pure use_sse41 () bool)
(extern constructor use_sse41 use_sse41)

(decl pure use_sse42 () bool)
(extern constructor use_sse42 use_sse42)

(decl pure use_avx () bool)
(extern constructor use_avx use_avx)

(decl pure use_avx2 () bool)
(extern constructor use_avx2 use_avx2)

;;;; Helpers for Merging and Sinking Immediates/Loads  ;;;;;;;;;;;;;;;;;;;;;;;;;

;; Extract a constant `Imm8Reg.Imm8` from a value operand.
(decl imm8_from_value (Imm8Reg) Value)
(extern extractor imm8_from_value imm8_from_value)

;; Mask a constant to the bit-width of the given type and package it into an
;; `Imm8Reg.Imm8`. This is used for shifts and rotates, so that we don't try and
;; shift/rotate more bits than the type has available, per Cranelift's
;; semantics.
(decl const_to_type_masked_imm8 (u64 Type) Imm8Gpr)
(extern constructor const_to_type_masked_imm8 const_to_type_masked_imm8)

;; Generate a mask for the bit-width of the given type
(decl shift_mask (Type) u8)
(extern constructor shift_mask shift_mask)

;; Mask a constant with the type's shift mask
(decl shift_amount_masked (Type Imm64) u8)
(extern constructor shift_amount_masked shift_amount_masked)

;; Extract a constant `GprMemImm.Imm` from a value operand.
(decl simm32_from_value (GprMemImm) Value)
(extern extractor simm32_from_value simm32_from_value)

;; A load that can be sunk into another operation.
(type SinkableLoad extern (enum))

;; Extract a `SinkableLoad` that works with `RegMemImm.Mem` from a value
;; operand.
;;
;; Note that this will only work for 32-bit-types-or-larger since this is
;; pervasively used with operations that load a minimum of 32-bits. For
;; instructions which load exactly the type width necessary use
;; `sinkable_load_exact`.
(decl sinkable_load (SinkableLoad) Value)
(extern extractor sinkable_load sinkable_load)

;; Same as `sinkable_load` except that all type widths of loads are supported.
;;
;; Only use this when the instruction which performs the load is guaranteed to
;; load the precisely correct size.
(decl sinkable_load_exact (SinkableLoad) Value)
(extern extractor sinkable_load_exact sinkable_load_exact)

;; Sink a `SinkableLoad` into a `SyntheticAmode`.
;;
;; This is a side-effectful operation that notifies the context that the
;; instruction that produced the `SinkableImm` has been sunk into another
;; instruction, and no longer needs to be lowered.
(decl sink_load (SinkableLoad) SyntheticAmode)
(extern constructor sink_load sink_load)

(decl sink_load_to_gpr_mem_imm (SinkableLoad) GprMemImm)
(rule (sink_load_to_gpr_mem_imm load)
      (gpr_mem_imm_new load))

(decl sink_load_to_xmm_mem (SinkableLoad) XmmMem)
(rule (sink_load_to_xmm_mem load)
      (reg_mem_to_xmm_mem load))

(decl sink_load_to_reg_mem (SinkableLoad) RegMem)
(rule (sink_load_to_reg_mem load) (RegMem.Mem load))

(decl sink_load_to_gpr_mem (SinkableLoad) GprMem)
(rule (sink_load_to_gpr_mem load) (RegMem.Mem load))

(decl sink_load_to_reg_mem_imm (SinkableLoad) RegMemImm)
(rule (sink_load_to_reg_mem_imm load) (RegMemImm.Mem load))

;;;; Helpers for constructing and emitting an `MInst` ;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; These helpers are intended to assist in emitting instructions by taking
;; source operands and automatically creating output operands which are then
;; returned. These are additionally designed to assist with SSA-like
;; construction where the writable version of a register is only present in
;; an `MInst` and every other reference to it is a readonly version.

;; Helper for creating XmmUninitializedValue instructions.
(decl xmm_uninit_value () Xmm)
(rule (xmm_uninit_value)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUninitializedValue dst))))
        dst))

;; Helper for constructing a LoadExtName instruction.
(decl load_ext_name (ExternalName i64 RelocDistance) Reg)
(rule (load_ext_name extname offset distance)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.LoadExtName dst extname offset distance))))
        dst))

;; Helper for constructing a Mov64MR instruction.
(decl mov64_mr (SyntheticAmode) Reg)
(rule (mov64_mr addr)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.Mov64MR addr dst))))
        dst))

;; Helper for emitting `MInst.AluRmiR` instructions.
(decl alu_rmi_r (Type AluRmiROpcode Gpr GprMemImm) Gpr)
(rule (alu_rmi_r ty opcode src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (_ Unit (emit (MInst.AluRmiR size opcode src1 src2 dst))))
        dst))

;; Helper for emitting `MInst.AluRmRVex` instructions.
(decl alu_rm_r_vex (Type AluRmROpcode Gpr GprMem) Gpr)
(rule (alu_rm_r_vex ty opcode src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (_ Unit (emit (MInst.AluRmRVex size opcode src1 src2 dst))))
        dst))

;; Helper for creating `MInst.XmmRmR` instructions.
(decl xmm_rm_r (SseOpcode Xmm XmmMemAligned) Xmm)
(rule (xmm_rm_r op src1 src2)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmR op src1 src2 dst))))
        dst))

;; Helper for creating `MInst.XmmRmRUnaligned` instructions.
(decl xmm_rm_r_unaligned (SseOpcode Xmm XmmMem) Xmm)
(rule (xmm_rm_r_unaligned op src1 src2)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmRUnaligned op src1 src2 dst))))
        dst))

;; Helper for creating `XmmRmRBlend` instructions
(decl xmm_rm_r_blend (SseOpcode Xmm XmmMemAligned Xmm) Xmm)
(rule (xmm_rm_r_blend op src1 src2 mask)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmRBlend op src1 src2 mask dst))))
        dst))

;; Helper for creating `XmmRmRBlendVex` instructions
(decl xmm_rmr_blend_vex (AvxOpcode Xmm XmmMem Xmm) Xmm)
(rule (xmm_rmr_blend_vex op src1 src2 mask)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmRBlendVex op src1 src2 mask dst))))
        dst))

;; Helper for creating `XmmUnaryRmRVex` instructions
(decl xmm_unary_rm_r_vex (AvxOpcode XmmMem) Xmm)
(rule (xmm_unary_rm_r_vex op src)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUnaryRmRVex op src dst))))
        dst))

;; Helper for creating `XmmUnaryRmRImmVex` instructions
(decl xmm_unary_rm_r_imm_vex (AvxOpcode XmmMem u8) Xmm)
(rule (xmm_unary_rm_r_imm_vex op src imm)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUnaryRmRImmVex op src dst imm))))
        dst))

;; Helper for creating `MInst.XmmRmRImm` instructions.
(decl xmm_rm_r_imm (SseOpcode Reg RegMem u8 OperandSize) Xmm)
(rule (xmm_rm_r_imm op src1 src2 imm size)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmRImm op
                                           src1
                                           src2
                                           dst
                                           imm
                                           size))))
        dst))

;; Helper for constructing `XmmVexPinsr` instructions.
(decl xmm_vex_pinsr (AvxOpcode Xmm GprMem u8) Xmm)
(rule (xmm_vex_pinsr op src1 src2 imm)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmVexPinsr op src1 src2 dst imm))))
        dst))

;; Helper for constructing `XmmUnaryRmRImm` instructions.
(decl xmm_unary_rm_r_imm (SseOpcode XmmMemAligned u8) Xmm)
(rule (xmm_unary_rm_r_imm op src1 imm)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUnaryRmRImm op src1 imm dst))))
        dst))

;; Helper for creating `MInst.XmmUnaryRmR` instructions.
(decl xmm_unary_rm_r (SseOpcode XmmMemAligned) Xmm)
(rule (xmm_unary_rm_r op src)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUnaryRmR op src dst))))
        dst))

;; Helper for creating `MInst.XmmUnaryRmRUnaligned` instructions.
(decl xmm_unary_rm_r_unaligned (SseOpcode XmmMem) Xmm)
(rule (xmm_unary_rm_r_unaligned op src)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUnaryRmRUnaligned op src dst))))
        dst))

;; Helper for creating `MInst.XmmUnaryRmREvex` instructions.
(decl xmm_unary_rm_r_evex (Avx512Opcode XmmMem) Xmm)
(rule (xmm_unary_rm_r_evex op src)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUnaryRmREvex op src dst))))
        dst))

;; Helper for creating `MInst.XmmRmREvex` instructions.
(decl xmm_rm_r_evex (Avx512Opcode Xmm XmmMem) Xmm)
(rule (xmm_rm_r_evex op src1 src2)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmREvex op
                                            src1
                                            src2
                                            dst))))
        dst))

;; Helper for creating `MInst.XmmUnaryRmRImmEvex` instructions.
(decl xmm_unary_rm_r_imm_evex (Avx512Opcode XmmMem u8) Xmm)
(rule (xmm_unary_rm_r_imm_evex op src imm)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmUnaryRmRImmEvex op src dst imm))))
        dst))

;; Helper for creating `MInst.XmmRmiXmm` instructions.
(decl xmm_rmi_xmm (SseOpcode Xmm XmmMemAlignedImm) Xmm)
(rule (xmm_rmi_xmm op src1 src2)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmiReg op
                                           src1
                                           src2
                                           dst))))
        dst))

;; Helper for creating `MInst.XmmToGprImm` instructions.
(decl xmm_to_gpr_imm (SseOpcode Xmm u8) Gpr)
(rule (xmm_to_gpr_imm op src imm)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.XmmToGprImm op src dst imm))))
        dst))

;; Helper for creating `MInst.XmmToGprImmVex` instructions.
(decl xmm_to_gpr_imm_vex (AvxOpcode Xmm u8) Gpr)
(rule (xmm_to_gpr_imm_vex op src imm)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.XmmToGprImmVex op src dst imm))))
        dst))

;; Helper for creating `MInst.GprToXmm` instructions.
(decl gpr_to_xmm (SseOpcode GprMem OperandSize) Xmm)
(rule (gpr_to_xmm op src size)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.GprToXmm op src dst size))))
        dst))

;; Helper for creating `MInst.GprToXmmVex` instructions.
(decl gpr_to_xmm_vex (AvxOpcode GprMem OperandSize) Xmm)
(rule (gpr_to_xmm_vex op src size)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.GprToXmmVex op src dst size))))
        dst))

;; Helper for creating `MInst.XmmToGpr` instructions.
(decl xmm_to_gpr (SseOpcode Xmm OperandSize) Gpr)
(rule (xmm_to_gpr op src size)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.XmmToGpr op src dst size))))
        dst))

;; Helper for creating `MInst.XmmToGprVex` instructions.
(decl xmm_to_gpr_vex (AvxOpcode Xmm OperandSize) Gpr)
(rule (xmm_to_gpr_vex op src size)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.XmmToGprVex op src dst size))))
        dst))

;; Helper for creating `xmm_min_max_seq` psuedo-instructions.
(decl xmm_min_max_seq (Type bool Xmm Xmm) Xmm)
(rule (xmm_min_max_seq ty is_min lhs rhs)
      (let ((dst WritableXmm (temp_writable_xmm))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (_ Unit (emit (MInst.XmmMinMaxSeq size is_min lhs rhs dst))))
        dst))

;; Helper for creating `MInst.XmmRmiRVex` instructions.
(decl xmm_rmir_vex (AvxOpcode Xmm XmmMemImm) Xmm)
(rule (xmm_rmir_vex op src1 src2)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmiRVex op src1 src2 dst))))
        dst))

;; Helper for creating `MInst.XmmRmRImmVex` instructions.
(decl xmm_rmr_imm_vex (AvxOpcode Xmm XmmMem u8) Xmm)
(rule (xmm_rmr_imm_vex op src1 src2 imm)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmRImmVex op src1 src2 dst imm))))
        dst))

;; Helper for creating `MInst.XmmRmRVex3` instructions.
(decl xmm_rmr_vex3 (AvxOpcode Xmm Xmm XmmMem) Xmm)
(rule (xmm_rmr_vex3 op src1 src2 src3)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmRVex3 op src1 src2 src3 dst))))
        dst))

;; Helper for creating `MInst.UnaryRmR` instructions.
(decl unary_rm_r (UnaryRmROpcode Gpr OperandSize) Gpr)
(rule (unary_rm_r op src size)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.UnaryRmR size op src dst))))
        dst))

;; Helper for creating `MInst.UnaryRmRVex` instructions.
(decl unary_rm_r_vex (UnaryRmRVexOpcode GprMem OperandSize) Gpr)
(rule (unary_rm_r_vex op src size)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.UnaryRmRVex size op src dst))))
        dst))

;; Helper for creating `MInst.UnaryRmRImmVex` instructions.
(decl unary_rm_r_imm_vex (UnaryRmRImmVexOpcode GprMem OperandSize u8) Gpr)
(rule (unary_rm_r_imm_vex op src size imm)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.UnaryRmRImmVex size op src dst imm))))
        dst))

(decl cvt_int_to_float (SseOpcode Xmm GprMem OperandSize) Xmm)
(rule (cvt_int_to_float op src1 src2 size)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.CvtIntToFloat op src1 src2 dst size))))
        dst))

(decl cvt_int_to_float_vex (AvxOpcode Xmm GprMem OperandSize) Xmm)
(rule (cvt_int_to_float_vex op src1 src2 size)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.CvtIntToFloatVex op src1 src2 dst size))))
        dst))

(decl cvt_u64_to_float_seq (Type Gpr) Xmm)
(rule (cvt_u64_to_float_seq ty src)
      (let ((size OperandSize (raw_operand_size_of_type ty))
            (dst WritableXmm (temp_writable_xmm))
            (tmp_gpr1 WritableGpr (temp_writable_gpr))
            (tmp_gpr2 WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.CvtUint64ToFloatSeq size src dst tmp_gpr1 tmp_gpr2))))
        dst))

(decl cvt_float_to_uint_seq (Type Value bool) Gpr)
(rule (cvt_float_to_uint_seq out_ty src @ (value_type src_ty) is_saturating)
      (let ((out_size OperandSize (raw_operand_size_of_type out_ty))
            (src_size OperandSize (raw_operand_size_of_type src_ty))

            (dst WritableGpr (temp_writable_gpr))
            (tmp_xmm WritableXmm (temp_writable_xmm))
            (tmp_xmm2 WritableXmm (temp_writable_xmm))
            (tmp_gpr WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.CvtFloatToUintSeq out_size src_size is_saturating src dst tmp_gpr tmp_xmm tmp_xmm2))))
        dst))

(decl cvt_float_to_sint_seq (Type Value bool) Gpr)
(rule (cvt_float_to_sint_seq out_ty src @ (value_type src_ty) is_saturating)
      (let ((out_size OperandSize (raw_operand_size_of_type out_ty))
            (src_size OperandSize (raw_operand_size_of_type src_ty))

            (dst WritableGpr (temp_writable_gpr))
            (tmp_xmm WritableXmm (temp_writable_xmm))
            (tmp_gpr WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.CvtFloatToSintSeq out_size src_size is_saturating src dst tmp_gpr tmp_xmm))))
        dst))

;; Helper for creating `MovFromPReg` instructions.
(decl mov_from_preg (PReg) Reg)
(rule (mov_from_preg preg)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.MovFromPReg preg dst))))
        dst))

;;;; Helpers for Sign/Zero Extending ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(type ExtKind extern
      (enum None
            SignExtend
            ZeroExtend))

(type ExtendKind (enum Sign Zero))

(type ExtMode extern (enum BL BQ WL WQ LQ))

;; `ExtMode::new`
(decl ext_mode (u16 u16) ExtMode)
(extern constructor ext_mode ext_mode)

;; Put the given value into a register, but extended as the given type.
(decl extend_to_gpr (Value Type ExtendKind) Gpr)

;; If the value is already of the requested type, no extending is necessary.
(rule 3 (extend_to_gpr val @ (value_type ty) ty _kind)
      val)

;; I32 -> I64 with op that produces a zero-extended value in a register.
;;
;; As a particular x64 extra-pattern matching opportunity, all the ALU
;; opcodes on 32-bits will zero-extend the upper 32-bits, so we can
;; even not generate a zero-extended move in this case.
(rule 2 (extend_to_gpr src @ (value_type $I32) $I64 (ExtendKind.Zero))
        (if-let $true (value32_zeros_upper32 src))
        (add_range_fact src 64 0 0xffff_ffff))

;; Both extend instructions are guaranteed to load exactly the source type's size.
;; So we can use `sinkable_load_exact` here to sink loads for small types (<= 16 bits).
(rule 1 (extend_to_gpr (and (sinkable_load_exact val) (value_type from_ty)) to_ty kind)
      (extend_to_gpr_types val from_ty to_ty kind))

;; Otherwise emit the extend from a Gpr to a Gpr.
(rule (extend_to_gpr (and val (value_type from_ty)) to_ty kind)
      (extend_to_gpr_types val from_ty to_ty kind))

;; Calculates the correct extension mode for an extend between `from_ty` and `to_ty`.
(decl extend_to_gpr_types (GprMem Type Type ExtendKind) Gpr)
(rule (extend_to_gpr_types val from_ty to_ty kind)
      (let ((from_bits u16 (ty_bits_u16 from_ty))
            ;; Use `operand_size_of_type` so that the we clamp the output to 32-
            ;; or 64-bit width types.
            (to_bits u16 (operand_size_bits (operand_size_of_type_32_64 to_ty))))
        (extend kind
                to_ty
                (ext_mode from_bits to_bits)
                val)))


;; Do a sign or zero extension of the given `GprMem`.
(decl extend (ExtendKind Type ExtMode GprMem) Gpr)

;; Zero extending uses `movzx`.
(rule (extend (ExtendKind.Zero) ty mode src)
      (x64_movzx mode src))

;; Sign extending uses `movsx`.
(rule (extend (ExtendKind.Sign) ty mode src)
      (x64_movsx mode src))

;; Tests whether the operation used to produce the input `Value`, which must
;; be a 32-bit operation, will automatically zero the upper 32-bits of the
;; destination register that `Value` is placed in.
(decl pure value32_zeros_upper32 (Value) bool)
(rule (value32_zeros_upper32 (iadd _ _)) $true)
(rule (value32_zeros_upper32 (isub _ _)) $true)
(rule (value32_zeros_upper32 (imul _ _)) $true)
(rule (value32_zeros_upper32 (band _ _)) $true)
(rule (value32_zeros_upper32 (bor _ _)) $true)
(rule (value32_zeros_upper32 (bxor _ _)) $true)
(rule (value32_zeros_upper32 (ishl _ _)) $true)
(rule (value32_zeros_upper32 (ushr _ _)) $true)
(rule (value32_zeros_upper32 (uload32 _ _ _)) $true)
(rule -1 (value32_zeros_upper32 _) $false)

;;;; Helpers for Working SSE tidbits ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Turn a vector type into its integer-typed vector equivalent.
(decl vec_int_type (Type) Type)
(rule (vec_int_type (multi_lane 8 16)) $I8X16)
(rule (vec_int_type (multi_lane 16 8)) $I16X8)
(rule (vec_int_type (multi_lane 32 4)) $I32X4)
(rule (vec_int_type (multi_lane 64 2)) $I64X2)

;; Performs an xor operation of the two operands specified.
(decl x64_xor_vector (Type Xmm XmmMem) Xmm)
(rule 1 (x64_xor_vector $F16 x y) (x64_xorps x y))
(rule 1 (x64_xor_vector $F32 x y) (x64_xorps x y))
(rule 1 (x64_xor_vector $F64 x y) (x64_xorpd x y))
(rule 1 (x64_xor_vector $F128 x y) (x64_xorps x y))
(rule 1 (x64_xor_vector $F32X4 x y) (x64_xorps x y))
(rule 1 (x64_xor_vector $F64X2 x y) (x64_xorpd x y))
(rule 0 (x64_xor_vector (multi_lane _ _) x y) (x64_pxor x y))

;; Generates a register value which has an all-ones pattern.
;;
;; Note that this is accomplished by comparing a fresh register with itself,
;; which for integers is always true. Also note that the comparison is always
;; done for integers. This is because we're comparing a fresh register to itself
;; and we don't know the previous contents of the register. If a floating-point
;; comparison is used then it runs the risk of comparing NaN against NaN and not
;; actually producing an all-ones mask. By using integer comparison operations
;; we're guaranteeed that everything is equal to itself.
(decl vector_all_ones () Xmm)
(rule (vector_all_ones)
      (let ((tmp Xmm (xmm_uninit_value)))
        (x64_pcmpeqd tmp tmp)))

;; Move a `RegMemImm.Reg` operand to an XMM register, if necessary.
(decl mov_rmi_to_xmm (RegMemImm) XmmMemImm)
(rule (mov_rmi_to_xmm rmi @ (RegMemImm.Mem _)) (xmm_mem_imm_new rmi))
(rule (mov_rmi_to_xmm rmi @ (RegMemImm.Imm _)) (xmm_mem_imm_new rmi))
(rule (mov_rmi_to_xmm (RegMemImm.Reg r)) (x64_movd_to_xmm r))

;;;; Helpers for Emitting Calls ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(decl gen_call (SigRef ExternalName RelocDistance ValueSlice) InstOutput)
(extern constructor gen_call gen_call)

(decl gen_call_indirect (SigRef Value ValueSlice) InstOutput)
(extern constructor gen_call_indirect gen_call_indirect)

;;;; Helpers for emitting stack switches ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(decl x64_stack_switch_basic (Gpr Gpr Gpr) Gpr)
(rule (x64_stack_switch_basic store_context_ptr load_context_ptr in_payload0)
      (let ((out_payload0 WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.StackSwitchBasic store_context_ptr
                                                  load_context_ptr
                                                  in_payload0
                                                  out_payload0))))
        out_payload0))

;;;; Helpers for Emitting Loads ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Load a value into a register.
(decl x64_load (Type SyntheticAmode ExtKind) Reg)

(rule 1 (x64_load (fits_in_32 ty) addr (ExtKind.SignExtend))
      (x64_movsx (ext_mode (ty_bytes ty) 8)
             addr))

(rule 2 (x64_load $I64 addr _ext_kind)
      (mov64_mr addr))

(rule 2 (x64_load $F32 addr _ext_kind)
      (x64_movss_load addr))

(rule 2 (x64_load $F64 addr _ext_kind)
      (x64_movsd_load addr))

(rule 2 (x64_load $F128 addr _ext_kind)
      (x64_movdqu_load addr))

(rule 2 (x64_load $F32X4 addr _ext_kind)
      (x64_movups_load addr))

(rule 2 (x64_load $F64X2 addr _ext_kind)
      (x64_movupd_load addr))

(rule 0 (x64_load (multi_lane _bits _lanes) addr _ext_kind)
      (x64_movdqu_load addr))

(decl x64_mov (Amode) Reg)
(rule (x64_mov addr)
      (mov64_mr addr))

(decl x64_movzx (ExtMode GprMem) Gpr)
(rule (x64_movzx mode src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.MovzxRmR mode src dst))))
        dst))

(decl x64_movsx (ExtMode GprMem) Gpr)
(rule (x64_movsx mode src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.MovsxRmR mode src dst))))
        dst))

(decl x64_movss_load (SyntheticAmode) Xmm)
(rule (x64_movss_load from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Movss) from))
(rule 1 (x64_movss_load from)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vmovss) from))

(decl x64_movss_store (SyntheticAmode Xmm) SideEffectNoResult)
(rule (x64_movss_store addr data)
      (xmm_movrm (SseOpcode.Movss) addr data))
(rule 1 (x64_movss_store addr data)
        (if-let $true (use_avx))
        (xmm_movrm_vex (AvxOpcode.Vmovss) addr data))

(decl x64_movsd_load (SyntheticAmode) Xmm)
(rule (x64_movsd_load from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Movsd) from))
(rule 1 (x64_movsd_load from)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vmovsd) from))

(decl x64_movsd_store (SyntheticAmode Xmm) SideEffectNoResult)
(rule (x64_movsd_store addr data)
      (xmm_movrm (SseOpcode.Movsd) addr data))
(rule 1 (x64_movsd_store addr data)
        (if-let $true (use_avx))
        (xmm_movrm_vex (AvxOpcode.Vmovsd) addr data))

(decl x64_movups_load (SyntheticAmode) Xmm)
(rule (x64_movups_load from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Movups) from))
(rule 1 (x64_movups_load from)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vmovups) from))

(decl x64_movups_store (SyntheticAmode Xmm) SideEffectNoResult)
(rule (x64_movups_store addr data)
      (xmm_movrm (SseOpcode.Movups) addr data))
(rule 1 (x64_movups_store addr data)
        (if-let $true (use_avx))
        (xmm_movrm_vex (AvxOpcode.Vmovups) addr data))

(decl x64_movupd_load (SyntheticAmode) Xmm)
(rule (x64_movupd_load from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Movupd) from))
(rule 1 (x64_movupd_load from)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vmovupd) from))

(decl x64_movupd_store (SyntheticAmode Xmm) SideEffectNoResult)
(rule (x64_movupd_store addr data)
      (xmm_movrm (SseOpcode.Movupd) addr data))
(rule 1 (x64_movupd_store addr data)
        (if-let $true (use_avx))
        (xmm_movrm_vex (AvxOpcode.Vmovupd) addr data))

;; Helper for creating `movd` instructions.
(decl x64_movd_to_gpr (Xmm) Gpr)
(rule (x64_movd_to_gpr from)
      (xmm_to_gpr (SseOpcode.Movd) from (OperandSize.Size32)))
(rule 1 (x64_movd_to_gpr from)
        (if-let $true (use_avx))
        (xmm_to_gpr_vex (AvxOpcode.Vmovd) from (OperandSize.Size32)))

;; Helper for creating `movd` instructions.
(decl x64_movd_to_xmm (GprMem) Xmm)
(rule (x64_movd_to_xmm from)
      (gpr_to_xmm (SseOpcode.Movd) from (OperandSize.Size32)))
(rule 1 (x64_movd_to_xmm from)
        (if-let $true (use_avx))
        (gpr_to_xmm_vex (AvxOpcode.Vmovd) from (OperandSize.Size32)))

;; Helper for creating `movq` instructions.
(decl x64_movq_to_xmm (GprMem) Xmm)
(rule (x64_movq_to_xmm src)
      (gpr_to_xmm (SseOpcode.Movq) src (OperandSize.Size64)))
(rule 1 (x64_movq_to_xmm from)
        (if-let $true (use_avx))
        (gpr_to_xmm_vex (AvxOpcode.Vmovq) from (OperandSize.Size64)))

;; Helper for creating `movq` instructions.
(decl x64_movq_to_gpr (Xmm) Gpr)
(rule (x64_movq_to_gpr src)
      (xmm_to_gpr (SseOpcode.Movq) src (OperandSize.Size64)))
(rule 1 (x64_movq_to_gpr from)
        (if-let $true (use_avx))
        (xmm_to_gpr_vex (AvxOpcode.Vmovq) from (OperandSize.Size64)))

(decl x64_movdqu_load (XmmMem) Xmm)
(rule (x64_movdqu_load from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Movdqu) from))
(rule 1 (x64_movdqu_load from)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vmovdqu) from))

(decl x64_movdqu_store (SyntheticAmode Xmm) SideEffectNoResult)
(rule (x64_movdqu_store addr data)
      (xmm_movrm (SseOpcode.Movdqu) addr data))
(rule 1 (x64_movdqu_store addr data)
        (if-let $true (use_avx))
        (xmm_movrm_vex (AvxOpcode.Vmovdqu) addr data))

(decl x64_pmovsxbw (XmmMem) Xmm)
(rule (x64_pmovsxbw from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Pmovsxbw) from))
(rule 1 (x64_pmovsxbw from)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpmovsxbw) from))

(decl x64_pmovzxbw (XmmMem) Xmm)
(rule (x64_pmovzxbw from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Pmovzxbw) from))
(rule 1 (x64_pmovzxbw from)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpmovzxbw) from))

(decl x64_pmovsxwd (XmmMem) Xmm)
(rule (x64_pmovsxwd from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Pmovsxwd) from))
(rule 1 (x64_pmovsxwd from)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpmovsxwd) from))

(decl x64_pmovzxwd (XmmMem) Xmm)
(rule (x64_pmovzxwd from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Pmovzxwd) from))
(rule 1 (x64_pmovzxwd from)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpmovzxwd) from))

(decl x64_pmovsxdq (XmmMem) Xmm)
(rule (x64_pmovsxdq from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Pmovsxdq) from))
(rule 1 (x64_pmovsxdq from)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpmovsxdq) from))

(decl x64_pmovzxdq (XmmMem) Xmm)
(rule (x64_pmovzxdq from)
      (xmm_unary_rm_r_unaligned (SseOpcode.Pmovzxdq) from))
(rule 1 (x64_pmovzxdq from)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpmovzxdq) from))

(decl x64_movrm (Type SyntheticAmode Gpr) SideEffectNoResult)
(rule (x64_movrm ty addr data)
      (let ((size OperandSize (raw_operand_size_of_type ty)))
        (SideEffectNoResult.Inst (MInst.MovRM size data addr))))

(decl x64_movimm_m (Type SyntheticAmode i32) SideEffectNoResult)
(rule (x64_movimm_m ty addr imm)
      (let ((size OperandSize (raw_operand_size_of_type ty)))
        (SideEffectNoResult.Inst (MInst.MovImmM size imm addr))))

(decl xmm_movrm (SseOpcode SyntheticAmode Xmm) SideEffectNoResult)
(rule (xmm_movrm op addr data)
      (SideEffectNoResult.Inst (MInst.XmmMovRM op data addr)))

(decl xmm_movrm_imm (SseOpcode SyntheticAmode Xmm u8) SideEffectNoResult)
(rule (xmm_movrm_imm op addr data imm)
      (SideEffectNoResult.Inst (MInst.XmmMovRMImm op data addr imm)))

(decl xmm_movrm_vex (AvxOpcode SyntheticAmode Xmm) SideEffectNoResult)
(rule (xmm_movrm_vex op addr data)
      (SideEffectNoResult.Inst (MInst.XmmMovRMVex op data addr)))

(decl xmm_movrm_imm_vex (AvxOpcode SyntheticAmode Xmm u8) SideEffectNoResult)
(rule (xmm_movrm_imm_vex op addr data imm)
      (SideEffectNoResult.Inst (MInst.XmmMovRMImmVex op data addr imm)))

;; Load a constant into an XMM register.
(decl x64_xmm_load_const (Type VCodeConstant) Xmm)
(rule (x64_xmm_load_const ty const)
      (x64_load ty (const_to_synthetic_amode const) (ExtKind.None)))

;;;; Instruction Constructors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; These constructors create SSA-style `MInst`s. It is their responsibility to
;; maintain the invariant that each temporary register they allocate and define
;; only gets defined the once.

;; Helper for emitting `add` instructions.
(decl x64_add (Type Gpr GprMemImm) Gpr)
(rule (x64_add ty src1 src2)
      (alu_rmi_r ty
                 (AluRmiROpcode.Add)
                 src1
                 src2))

;; Helper for creating `add` instructions whose flags are also used.
(decl x64_add_with_flags_paired (Type Gpr GprMemImm) ProducesFlags)
(rule (x64_add_with_flags_paired ty src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ProducesFlags.ProducesFlagsReturnsResultWithConsumer
         (MInst.AluRmiR (operand_size_of_type_32_64 ty)
                        (AluRmiROpcode.Add)
                        src1
                        src2
                        dst)
         dst)))

(decl x64_alurmi_with_flags_paired (AluRmiROpcode Type Gpr GprMemImm) ProducesFlags)
(rule (x64_alurmi_with_flags_paired opc (fits_in_64 ty) src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ProducesFlags.ProducesFlagsReturnsResultWithConsumer
         (MInst.AluRmiR (raw_operand_size_of_type ty)
                        opc
                        src1
                        src2
                        dst)
         dst)))

(decl x64_alurmi_flags_side_effect (AluRmiROpcode Type Gpr GprMemImm) ProducesFlags)
(rule (x64_alurmi_flags_side_effect opc (fits_in_64 ty) src1 src2)
      (ProducesFlags.ProducesFlagsSideEffect
       (MInst.AluRmiR (raw_operand_size_of_type ty)
                      opc
                      src1
                      src2
                      (temp_writable_gpr))))

;; Should only be used for Adc and Sbb
(decl x64_alurmi_with_flags_chained (AluRmiROpcode Type Gpr GprMemImm) ConsumesAndProducesFlags)
(rule (x64_alurmi_with_flags_chained opc (fits_in_64 ty) src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ConsumesAndProducesFlags.ReturnsReg
         (MInst.AluRmiR (raw_operand_size_of_type ty)
                        opc
                        src1
                        src2
                        dst)
         dst)))

;; Helper for creating `adc` instructions.
(decl x64_adc_paired (Type Gpr GprMemImm) ConsumesFlags)
(rule (x64_adc_paired ty src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ConsumesFlags.ConsumesFlagsReturnsResultWithProducer
         (MInst.AluRmiR (operand_size_of_type_32_64 ty)
                        (AluRmiROpcode.Adc)
                        src1
                        src2
                        dst)
         dst)))

;; Helper for emitting `sub` instructions.
(decl x64_sub (Type Gpr GprMemImm) Gpr)
(rule (x64_sub ty src1 src2)
      (alu_rmi_r ty
                 (AluRmiROpcode.Sub)
                 src1
                 src2))

;; Helper for creating `sub` instructions whose flags are also used.
(decl x64_sub_with_flags_paired (Type Gpr GprMemImm) ProducesFlags)
(rule (x64_sub_with_flags_paired ty src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ProducesFlags.ProducesFlagsReturnsResultWithConsumer
         (MInst.AluRmiR (operand_size_of_type_32_64 ty)
                        (AluRmiROpcode.Sub)
                        src1
                        src2
                        dst)
         dst)))

;; Helper for creating `sbb` instructions.
(decl x64_sbb_paired (Type Gpr GprMemImm) ConsumesFlags)
(rule (x64_sbb_paired ty src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ConsumesFlags.ConsumesFlagsReturnsResultWithProducer
         (MInst.AluRmiR (operand_size_of_type_32_64 ty)
                        (AluRmiROpcode.Sbb)
                        src1
                        src2
                        dst)
         dst)))

;; Helper for creating `mul` instructions or `imul` instructions (depending
;; on `signed`)
(decl x64_mul (Type bool Gpr GprMem) ValueRegs)
(rule (x64_mul ty signed src1 src2)
      (let ((dst_lo WritableGpr (temp_writable_gpr))
            (dst_hi WritableGpr (temp_writable_gpr))
            (size OperandSize (raw_operand_size_of_type ty))
            (_ Unit (emit (MInst.Mul size signed src1 src2 dst_lo dst_hi))))
        (value_gprs dst_lo dst_hi)))

;; Helper for creating `mul` instructions or `imul` instructions (depending
;; on `signed`) for 8-bit operands.
(decl x64_mul8 (bool Gpr GprMem) Gpr)
(rule (x64_mul8 signed src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.Mul8 signed src1 src2 dst))))
        dst))

;; Helper for creating `imul` instructions.
(decl x64_imul (Type Gpr GprMem) Gpr)
(rule (x64_imul ty src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (raw_operand_size_of_type ty))
            (_ Unit (emit (MInst.IMul size src1 src2 dst))))
        dst))

;; Helper for creating `imul` instructions with an immediate operand.
(decl x64_imul_imm (Type GprMem i32) Gpr)
(rule (x64_imul_imm ty src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (raw_operand_size_of_type ty))
            (_ Unit (emit (MInst.IMulImm size src1 src2 dst))))
        dst))

(decl x64_mul8_with_flags_paired (bool Gpr GprMem) ProducesFlags)
(rule (x64_mul8_with_flags_paired signed src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
           (ProducesFlags.ProducesFlagsReturnsResultWithConsumer
                 (MInst.Mul8 signed src1 src2 dst)
                 dst)))

(decl x64_mul_lo_with_flags_paired (Type bool Gpr GprMem) ProducesFlags)
(rule (x64_mul_lo_with_flags_paired ty signed src1 src2)
      (let ((dst_lo WritableGpr (temp_writable_gpr))
            (dst_hi WritableGpr (temp_writable_gpr))
            (size OperandSize (raw_operand_size_of_type ty)))
           (ProducesFlags.ProducesFlagsReturnsResultWithConsumer
                 (MInst.Mul size signed src1 src2 dst_lo dst_hi)
                 dst_lo)))

;; Helper for emitting `and` instructions.
(decl x64_and (Type Gpr GprMemImm) Gpr)
(rule (x64_and ty src1 src2)
      (alu_rmi_r ty
                 (AluRmiROpcode.And)
                 src1
                 src2))

(decl x64_and_with_flags_paired (Type Gpr GprMemImm) ProducesFlags)
(rule (x64_and_with_flags_paired ty src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr)))
           (ProducesFlags.ProducesFlagsSideEffect
                 (MInst.AluRmiR (operand_size_of_type_32_64 ty)
                       (AluRmiROpcode.And)
                       src1
                       src2
                       dst))))

;; Helper for emitting `or` instructions.
(decl x64_or (Type Gpr GprMemImm) Gpr)
(rule (x64_or ty src1 src2)
      (alu_rmi_r ty
                 (AluRmiROpcode.Or)
                 src1
                 src2))

;; Helper for emitting `xor` instructions.
(decl x64_xor (Type Gpr GprMemImm) Gpr)
(rule (x64_xor ty src1 src2)
      (alu_rmi_r ty
                 (AluRmiROpcode.Xor)
                 src1
                 src2))

(decl x64_andn (Type Gpr GprMem) Gpr)
(rule (x64_andn ty src1 src2)
      (alu_rm_r_vex ty (AluRmROpcode.Andn) src1 src2))

;; Helper for emitting immediates with an `i64` value. Note that
;; integer constants in ISLE are always parsed as `i128`s; this enables
;; negative numbers to be used as immediates.
(decl imm_i64 (Type i64) Reg)
(rule (imm_i64 ty value)
      (imm ty (i64_as_u64 value)))

(decl nonzero_u64_fits_in_u32 (u64) u64)
(extern extractor nonzero_u64_fits_in_u32 nonzero_u64_fits_in_u32)

;; Helper for emitting immediates.
;;
;; There are three priorities in use in this rule:
;; 2 - rules that match on an explicit type
;; 1 - rules that match on types that fit in 64 bits
;; 0 - rules that match on vectors
(decl imm (Type u64) Reg)

;; Integer immediates.
(rule 1 (imm (fits_in_64 ty) (u64_nonzero simm64))
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (_ Unit (emit (MInst.Imm size simm64 dst))))
        dst))

;; `f16` immediates.
(rule 2 (imm $F16 (u64_nonzero bits))
        (bitcast_gpr_to_xmm 16 (imm $I16 bits)))

;; `f32` immediates.
(rule 2 (imm $F32 (u64_nonzero bits))
        (x64_movd_to_xmm (imm $I32 bits)))

;; `f64` immediates.
(rule 2 (imm $F64 (u64_nonzero bits))
        (x64_movq_to_xmm (imm $I64 bits)))

;; Special case for when a 64-bit immediate fits into 32-bits. We can use a
;; 32-bit move that zero-extends the value, which has a smaller encoding.
(rule 2 (imm $I64 (nonzero_u64_fits_in_u32 x))
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.Imm (OperandSize.Size32) x dst))))
        dst))

;; Special case for integer zero immediates: turn them into an `xor r, r`.
(rule 1 (imm (fits_in_64 ty) (u64_zero))
      (let ((wgpr WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (_ Unit (emit (MInst.AluConstOp (AluRmiROpcode.Xor) size wgpr))))
        (gpr_to_reg wgpr)))

;; Special case for zero immediates with vector types, they turn into an xor
;; specific to the vector type.
(rule 0 (imm ty @ (multi_lane _bits _lanes) 0)
      (xmm_to_reg (xmm_zero ty)))

;; Special case for `f16` zero immediates
(rule 2 (imm ty @ $F16 (u64_zero)) (xmm_zero ty))

;; Special case for `f32` zero immediates
(rule 2 (imm ty @ $F32 (u64_zero)) (xmm_zero ty))

;; TODO: use cmpeqps for all 1s

;; Special case for `f64` zero immediates to use `xorpd`.
(rule 2 (imm ty @ $F64 (u64_zero)) (xmm_zero ty))

;; TODO: use cmpeqpd for all 1s

(decl xmm_zero (Type) Xmm)
(rule (xmm_zero ty)
      (let ((tmp Xmm (xmm_uninit_value)))
        (x64_xor_vector ty tmp tmp)))

;; Helper for creating `MInst.ShiftR` instructions.
(decl shift_r (Type ShiftKind Gpr Imm8Gpr) Gpr)
(rule (shift_r ty kind src1 src2)
      (let ((dst WritableGpr (temp_writable_gpr))
            ;; Use actual 8/16-bit instructions when appropriate: we
            ;; rely on their shift-amount-masking semantics.
            (size OperandSize (raw_operand_size_of_type ty))
            (_ Unit (emit (MInst.ShiftR size kind src1 src2 dst))))
        dst))

;; Helper for creating `rotl` instructions.
(decl x64_rotl (Type Gpr Imm8Gpr) Gpr)
(rule (x64_rotl ty src1 src2)
      (shift_r ty (ShiftKind.RotateLeft) src1 src2))
(rule 1 (x64_rotl (ty_32_or_64 ty) src (imm8_from_imm8_gpr imm))
        (if-let $true (use_bmi2))
        (x64_rorx ty src (u8_sub (ty_bits ty) imm)))

;; Helper for creating `rotr` instructions.
(decl x64_rotr (Type Gpr Imm8Gpr) Gpr)
(rule (x64_rotr ty src1 src2)
      (shift_r ty (ShiftKind.RotateRight) src1 src2))
(rule 1 (x64_rotr (ty_32_or_64 ty) src (imm8_from_imm8_gpr imm))
        (if-let $true (use_bmi2))
        (x64_rorx ty src imm))

;; Helper for creating `shl` instructions.
(decl x64_shl (Type Gpr Imm8Gpr) Gpr)
(rule (x64_shl ty src1 src2)
      (shift_r ty (ShiftKind.ShiftLeft) src1 src2))
;; With BMI2 the `shlx` instruction is also available, and it's unconditionally
;; used for registers shifted by registers since it provides more freedom
;; in regalloc since nothing is constrained. Note that the `shlx` instruction
;; doesn't encode an immediate so any immediate-based shift still uses `shl`.
(rule 1 (x64_shl (ty_32_or_64 ty) src1 (gpr_from_imm8_gpr src2))
        (if-let $true (use_bmi2))
        (x64_shlx ty src1 src2))

;; Helper for creating logical shift-right instructions.
(decl x64_shr (Type Gpr Imm8Gpr) Gpr)
(rule (x64_shr ty src1 src2)
      (shift_r ty (ShiftKind.ShiftRightLogical) src1 src2))
;; see `x64_shl` for more info about this rule
(rule 1 (x64_shr (ty_32_or_64 ty) src1 (gpr_from_imm8_gpr src2))
        (if-let $true (use_bmi2))
        (x64_shrx ty src1 src2))

;; Helper for creating arithmetic shift-right instructions.
(decl x64_sar (Type Gpr Imm8Gpr) Gpr)
(rule (x64_sar ty src1 src2)
      (shift_r ty (ShiftKind.ShiftRightArithmetic) src1 src2))
;; see `x64_shl` for more info about this rule
(rule 1 (x64_sar (ty_32_or_64 ty) src1 (gpr_from_imm8_gpr src2))
        (if-let $true (use_bmi2))
        (x64_sarx ty src1 src2))

;; Helper for creating zeroing-of-high-bits instructions bzhi
;;
;; Note that the `src` operands are swapped here. The amount-to-shift-by
;; is stored in `vvvv` which is `src1` in the `AluRmRVex` instruction shape.
(decl x64_bzhi (Type GprMem Gpr) Gpr)
(rule (x64_bzhi ty src1 src2)
      (alu_rm_r_vex ty (AluRmROpcode.Bzhi) src2 src1))

;; Helper for creating byteswap instructions.
;; In x64, 32- and 64-bit registers use BSWAP instruction, and
;; for 16-bit registers one must instead use xchg or rol/ror
(decl x64_bswap (Type Gpr) Gpr)
(rule (x64_bswap ty src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (_ Unit (emit (MInst.Bswap size src dst))))
        dst))

;; Helper for creating `MInst.CmpRmiR` instructions.
(decl cmp_rmi_r (OperandSize CmpOpcode Gpr GprMemImm) ProducesFlags)
(rule (cmp_rmi_r size opcode src1 src2)
      (ProducesFlags.ProducesFlagsSideEffect
       (MInst.CmpRmiR size
                      opcode
                      src1
                      src2)))

;; Helper for creating `cmp` instructions.
(decl x64_cmp (OperandSize Gpr GprMemImm) ProducesFlags)
(rule (x64_cmp size src1 src2)
      (cmp_rmi_r size (CmpOpcode.Cmp) src1 src2))

;; Helper for creating `cmp` instructions with an immediate.
(decl x64_cmp_imm (OperandSize Gpr u32) ProducesFlags)
(rule (x64_cmp_imm size src1 src2)
      (x64_cmp size src1 (RegMemImm.Imm src2)))

;; Helper for creating `MInst.XmmCmpRmR` instructions.
(decl xmm_cmp_rm_r (SseOpcode Xmm XmmMem) ProducesFlags)
(rule (xmm_cmp_rm_r opcode src1 src2)
      (ProducesFlags.ProducesFlagsSideEffect
       (MInst.XmmCmpRmR opcode src1 src2)))

;; Helper for creating `MInst.XmmCmpRmRVex` instructions.
(decl xmm_cmp_rm_r_vex (AvxOpcode Xmm XmmMem) ProducesFlags)
(rule (xmm_cmp_rm_r_vex opcode src1 src2)
      (ProducesFlags.ProducesFlagsSideEffect
       (MInst.XmmCmpRmRVex opcode src1 src2)))

;; Helper for creating floating-point comparison instructions (`UCOMIS[S|D]`).
(decl x64_ucomis (Type Xmm XmmMem) ProducesFlags)
(rule (x64_ucomis $F32 src1 src2)
      (xmm_cmp_rm_r (SseOpcode.Ucomiss) src1 src2))
(rule (x64_ucomis $F64 src1 src2)
      (xmm_cmp_rm_r (SseOpcode.Ucomisd) src1 src2))
(rule 1 (x64_ucomis $F32 src1 src2)
        (if-let $true (use_avx))
        (xmm_cmp_rm_r_vex (AvxOpcode.Vucomiss) src1 src2))
(rule 1 (x64_ucomis $F64 src1 src2)
        (if-let $true (use_avx))
        (xmm_cmp_rm_r_vex (AvxOpcode.Vucomisd) src1 src2))

;; Helper for creating `test` instructions.
(decl x64_test (OperandSize Gpr GprMemImm) ProducesFlags)
(rule (x64_test size src1 src2)
      (cmp_rmi_r size (CmpOpcode.Test) src1 src2))

;; Helper for creating `ptest` instructions.
(decl x64_ptest (Xmm XmmMem) ProducesFlags)
(rule (x64_ptest src1 src2)
      (xmm_cmp_rm_r (SseOpcode.Ptest) src1 src2))
(rule 1 (x64_ptest src1 src2)
        (if-let $true (use_avx))
        (xmm_cmp_rm_r_vex (AvxOpcode.Vptest) src1 src2))

;; Helper for creating `cmove` instructions. Note that these instructions do not
;; always result in a single emitted x86 instruction; e.g., XmmCmove uses jumps
;; to conditionally move the selected value into an XMM register.
(decl cmove (Type CC GprMem Gpr) ConsumesFlags)
(rule (cmove ty cc consequent alternative)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty)))
        (ConsumesFlags.ConsumesFlagsReturnsReg
         (MInst.Cmove size cc consequent alternative dst)
         dst)))

(decl cmove_xmm (Type CC Xmm Xmm) ConsumesFlags)
(rule (cmove_xmm ty cc consequent alternative)
      (let ((dst WritableXmm (temp_writable_xmm)))
        (ConsumesFlags.ConsumesFlagsReturnsReg
         (MInst.XmmCmove ty cc consequent alternative dst)
         dst)))

;; Helper for creating `cmove` instructions directly from values. This allows us
;; to special-case the `I128` types and default to the `cmove` helper otherwise.
;; It also eliminates some `put_in_reg*` boilerplate in the lowering ISLE code.
(decl cmove_from_values (Type CC Value Value) ConsumesFlags)
(rule (cmove_from_values (is_multi_register_gpr_type $I128) cc consequent alternative)
      (let ((cons ValueRegs consequent)
            (alt ValueRegs alternative)
            (dst1 WritableGpr (temp_writable_gpr))
            (dst2 WritableGpr (temp_writable_gpr))
            (size OperandSize (OperandSize.Size64))
            (lower_cmove MInst (MInst.Cmove
                                size cc
                                (value_regs_get_gpr cons 0)
                                (value_regs_get_gpr alt 0)
                                dst1))
            (upper_cmove MInst (MInst.Cmove
                                size cc
                                (value_regs_get_gpr cons 1)
                                (value_regs_get_gpr alt 1)
                                dst2)))
        (ConsumesFlags.ConsumesFlagsTwiceReturnsValueRegs
         lower_cmove
         upper_cmove
         (value_regs dst1 dst2))))

(rule (cmove_from_values (is_single_register_gpr_type ty) cc consequent alternative)
      (cmove ty cc consequent alternative))

(rule (cmove_from_values (is_xmm_type ty) cc consequent alternative)
      (cmove_xmm ty cc consequent alternative))

;; Helper for creating `cmove` instructions with the logical OR of multiple
;; flags. Note that these instructions will always result in more than one
;; emitted x86 instruction.
(decl cmove_or (Type CC CC GprMem Gpr) ConsumesFlags)
(rule (cmove_or ty cc1 cc2 consequent alternative)
      (let ((dst WritableGpr (temp_writable_gpr))
            (tmp WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (cmove1 MInst (MInst.Cmove size cc1 consequent alternative tmp))
            (cmove2 MInst (MInst.Cmove size cc2 consequent tmp dst)))
        (ConsumesFlags.ConsumesFlagsTwiceReturnsValueRegs
         cmove1
         cmove2
         dst)))

(decl cmove_or_xmm (Type CC CC Xmm Xmm) ConsumesFlags)
(rule (cmove_or_xmm ty cc1 cc2 consequent alternative)
      (let ((dst WritableXmm (temp_writable_xmm))
            (tmp WritableXmm (temp_writable_xmm))
            (cmove1 MInst (MInst.XmmCmove ty cc1 consequent alternative tmp))
            (cmove2 MInst (MInst.XmmCmove ty cc2 consequent tmp dst)))
        (ConsumesFlags.ConsumesFlagsTwiceReturnsValueRegs
         cmove1
         cmove2
         dst)))

;; Helper for creating `cmove_or` instructions directly from values. This allows
;; us to special-case the `I128` types and default to the `cmove_or` helper
;; otherwise.
(decl cmove_or_from_values (Type CC CC Value Value) ConsumesFlags)
(rule (cmove_or_from_values (is_multi_register_gpr_type $I128) cc1 cc2 consequent alternative)
      (let ((cons ValueRegs consequent)
            (alt ValueRegs alternative)
            (dst1 WritableGpr (temp_writable_gpr))
            (dst2 WritableGpr (temp_writable_gpr))
            (tmp1 WritableGpr (temp_writable_gpr))
            (tmp2 WritableGpr (temp_writable_gpr))
            (size OperandSize (OperandSize.Size64))
            (cmove1 MInst (MInst.Cmove size cc1 (value_regs_get_gpr cons 0) (value_regs_get_gpr alt 0) tmp1))
            (cmove2 MInst (MInst.Cmove size cc2 (value_regs_get_gpr cons 0) tmp1 dst1))
            (cmove3 MInst (MInst.Cmove size cc1 (value_regs_get_gpr cons 1) (value_regs_get_gpr alt 1) tmp2))
            (cmove4 MInst (MInst.Cmove size cc2 (value_regs_get_gpr cons 1) tmp2 dst2)))
        (ConsumesFlags.ConsumesFlagsFourTimesReturnsValueRegs
         cmove1
         cmove2
         cmove3
         cmove4
         (value_regs dst1 dst2))))

(rule (cmove_or_from_values (is_single_register_gpr_type ty) cc1 cc2 consequent alternative)
      (cmove_or ty cc1 cc2 consequent alternative))

(rule (cmove_or_from_values (is_xmm_type ty) cc1 cc2 consequent alternative)
      (cmove_or_xmm ty cc1 cc2 consequent alternative))

;; Helper for creating `MInst.Setcc` instructions.
(decl x64_setcc (CC) ConsumesFlags)
(rule (x64_setcc cc)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ConsumesFlags.ConsumesFlagsReturnsReg
         (MInst.Setcc cc dst)
         dst)))

;; Helper for creating `MInst.Setcc` instructions, when the flags producer will
;; also return a value.
(decl x64_setcc_paired (CC) ConsumesFlags)
(rule (x64_setcc_paired cc)
      (let ((dst WritableGpr (temp_writable_gpr)))
        (ConsumesFlags.ConsumesFlagsReturnsResultWithProducer
         (MInst.Setcc cc dst)
         dst)))

;; Helper for creating `paddb` instructions.
(decl x64_paddb (Xmm XmmMem) Xmm)
(rule 0 (x64_paddb src1 src2)
      (xmm_rm_r (SseOpcode.Paddb) src1 src2))
(rule 1 (x64_paddb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddb) src1 src2))

;; Helper for creating `paddw` instructions.
(decl x64_paddw (Xmm XmmMem) Xmm)
(rule 0 (x64_paddw src1 src2)
      (xmm_rm_r (SseOpcode.Paddw) src1 src2))
(rule 1 (x64_paddw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddw) src1 src2))

;; Helper for creating `paddd` instructions.
(decl x64_paddd (Xmm XmmMem) Xmm)
(rule 0 (x64_paddd src1 src2)
      (xmm_rm_r (SseOpcode.Paddd) src1 src2))
(rule 1 (x64_paddd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddd) src1 src2))

;; Helper for creating `paddq` instructions.
(decl x64_paddq (Xmm XmmMem) Xmm)
(rule 0 (x64_paddq src1 src2)
      (xmm_rm_r (SseOpcode.Paddq) src1 src2))
(rule 1 (x64_paddq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddq) src1 src2))

;; Helper for creating `paddsb` instructions.
(decl x64_paddsb (Xmm XmmMem) Xmm)
(rule 0 (x64_paddsb src1 src2)
      (xmm_rm_r (SseOpcode.Paddsb) src1 src2))
(rule 1 (x64_paddsb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddsb) src1 src2))

;; Helper for creating `paddsw` instructions.
(decl x64_paddsw (Xmm XmmMem) Xmm)
(rule 0 (x64_paddsw src1 src2)
      (xmm_rm_r (SseOpcode.Paddsw) src1 src2))
(rule 1 (x64_paddsw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddsw) src1 src2))

;; Helper for creating `phaddw` instructions.
(decl x64_phaddw (Xmm XmmMem) Xmm)
(rule 0 (x64_phaddw src1 src2)
      (xmm_rm_r (SseOpcode.Phaddw) src1 src2))
(rule 1 (x64_phaddw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vphaddw) src1 src2))

;; Helper for creating `phaddd` instructions.
(decl x64_phaddd (Xmm XmmMem) Xmm)
(rule 0 (x64_phaddd src1 src2)
      (xmm_rm_r (SseOpcode.Phaddd) src1 src2))
(rule 1 (x64_phaddd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vphaddd) src1 src2))

;; Helper for creating `paddusb` instructions.
(decl x64_paddusb (Xmm XmmMem) Xmm)
(rule 0 (x64_paddusb src1 src2)
      (xmm_rm_r (SseOpcode.Paddusb) src1 src2))
(rule 1 (x64_paddusb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddusb) src1 src2))

;; Helper for creating `paddusw` instructions.
(decl x64_paddusw (Xmm XmmMem) Xmm)
(rule 0 (x64_paddusw src1 src2)
      (xmm_rm_r (SseOpcode.Paddusw) src1 src2))
(rule 1 (x64_paddusw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpaddusw) src1 src2))

;; Helper for creating `psubb` instructions.
(decl x64_psubb (Xmm XmmMem) Xmm)
(rule 0 (x64_psubb src1 src2)
      (xmm_rm_r (SseOpcode.Psubb) src1 src2))
(rule 1 (x64_psubb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubb) src1 src2))

;; Helper for creating `psubw` instructions.
(decl x64_psubw (Xmm XmmMem) Xmm)
(rule 0 (x64_psubw src1 src2)
      (xmm_rm_r (SseOpcode.Psubw) src1 src2))
(rule 1 (x64_psubw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubw) src1 src2))

;; Helper for creating `psubd` instructions.
(decl x64_psubd (Xmm XmmMem) Xmm)
(rule 0 (x64_psubd src1 src2)
      (xmm_rm_r (SseOpcode.Psubd) src1 src2))
(rule 1 (x64_psubd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubd) src1 src2))

;; Helper for creating `psubq` instructions.
(decl x64_psubq (Xmm XmmMem) Xmm)
(rule 0 (x64_psubq src1 src2)
      (xmm_rm_r (SseOpcode.Psubq) src1 src2))
(rule 1 (x64_psubq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubq) src1 src2))

;; Helper for creating `psubsb` instructions.
(decl x64_psubsb (Xmm XmmMem) Xmm)
(rule 0 (x64_psubsb src1 src2)
      (xmm_rm_r (SseOpcode.Psubsb) src1 src2))
(rule 1 (x64_psubsb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubsb) src1 src2))

;; Helper for creating `psubsw` instructions.
(decl x64_psubsw (Xmm XmmMem) Xmm)
(rule 0 (x64_psubsw src1 src2)
      (xmm_rm_r (SseOpcode.Psubsw) src1 src2))
(rule 1 (x64_psubsw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubsw) src1 src2))

;; Helper for creating `psubusb` instructions.
(decl x64_psubusb (Xmm XmmMem) Xmm)
(rule 0 (x64_psubusb src1 src2)
      (xmm_rm_r (SseOpcode.Psubusb) src1 src2))
(rule 1 (x64_psubusb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubusb) src1 src2))

;; Helper for creating `psubusw` instructions.
(decl x64_psubusw (Xmm XmmMem) Xmm)
(rule 0 (x64_psubusw src1 src2)
      (xmm_rm_r (SseOpcode.Psubusw) src1 src2))
(rule 1 (x64_psubusw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsubusw) src1 src2))

;; Helper for creating `pavgb` instructions.
(decl x64_pavgb (Xmm XmmMem) Xmm)
(rule 0 (x64_pavgb src1 src2)
      (xmm_rm_r (SseOpcode.Pavgb) src1 src2))
(rule 1 (x64_pavgb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpavgb) src1 src2))

;; Helper for creating `pavgw` instructions.
(decl x64_pavgw (Xmm XmmMem) Xmm)
(rule 0 (x64_pavgw src1 src2)
      (xmm_rm_r (SseOpcode.Pavgw) src1 src2))
(rule 1 (x64_pavgw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpavgw) src1 src2))

;; Helper for creating `pand` instructions.
(decl x64_pand (Xmm XmmMem) Xmm)
(rule 0 (x64_pand src1 src2)
      (xmm_rm_r (SseOpcode.Pand) src1 src2))
(rule 1 (x64_pand src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpand) src1 src2))

;; Helper for creating `andps` instructions.
(decl x64_andps (Xmm XmmMem) Xmm)
(rule 0 (x64_andps src1 src2)
      (xmm_rm_r (SseOpcode.Andps) src1 src2))
(rule 1 (x64_andps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vandps) src1 src2))

;; Helper for creating `andpd` instructions.
(decl x64_andpd (Xmm XmmMem) Xmm)
(rule 0 (x64_andpd src1 src2)
      (xmm_rm_r (SseOpcode.Andpd) src1 src2))
(rule 1 (x64_andpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vandpd) src1 src2))

;; Helper for creating `por` instructions.
(decl x64_por (Xmm XmmMem) Xmm)
(rule 0 (x64_por src1 src2)
      (xmm_rm_r (SseOpcode.Por) src1 src2))
(rule 1 (x64_por src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpor) src1 src2))

;; Helper for creating `orps` instructions.
(decl x64_orps (Xmm XmmMem) Xmm)
(rule 0 (x64_orps src1 src2)
      (xmm_rm_r (SseOpcode.Orps) src1 src2))
(rule 1 (x64_orps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vorps) src1 src2))

;; Helper for creating `orpd` instructions.
(decl x64_orpd (Xmm XmmMem) Xmm)
(rule 0 (x64_orpd src1 src2)
      (xmm_rm_r (SseOpcode.Orpd) src1 src2))
(rule 1 (x64_orpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vorpd) src1 src2))

;; Helper fxor creating `pxor` instructions.
(decl x64_pxor (Xmm XmmMem) Xmm)
(rule 0 (x64_pxor src1 src2)
      (xmm_rm_r (SseOpcode.Pxor) src1 src2))
(rule 1 (x64_pxor src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpxor) src1 src2))

;; Helper fxor creating `xorps` instructions.
(decl x64_xorps (Xmm XmmMem) Xmm)
(rule 0 (x64_xorps src1 src2)
      (xmm_rm_r (SseOpcode.Xorps) src1 src2))
(rule 1 (x64_xorps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vxorps) src1 src2))

;; Helper fxor creating `xorpd` instructions.
(decl x64_xorpd (Xmm XmmMem) Xmm)
(rule 0 (x64_xorpd src1 src2)
      (xmm_rm_r (SseOpcode.Xorpd) src1 src2))
(rule 1 (x64_xorpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vxorpd) src1 src2))

;; Helper for creating `pmullw` instructions.
(decl x64_pmullw (Xmm XmmMem) Xmm)
(rule 0 (x64_pmullw src1 src2)
      (xmm_rm_r (SseOpcode.Pmullw) src1 src2))
(rule 1 (x64_pmullw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmullw) src1 src2))

;; Helper for creating `pmulld` instructions.
(decl x64_pmulld (Xmm XmmMem) Xmm)
(rule 0 (x64_pmulld src1 src2)
      (xmm_rm_r (SseOpcode.Pmulld) src1 src2))
(rule 1 (x64_pmulld src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmulld) src1 src2))

;; Helper for creating `pmulhw` instructions.
(decl x64_pmulhw (Xmm XmmMem) Xmm)
(rule 0 (x64_pmulhw src1 src2)
      (xmm_rm_r (SseOpcode.Pmulhw) src1 src2))
(rule 1 (x64_pmulhw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmulhw) src1 src2))

;; Helper for creating `pmulhrsw` instructions.
(decl x64_pmulhrsw (Xmm XmmMem) Xmm)
(rule 0 (x64_pmulhrsw src1 src2)
      (xmm_rm_r (SseOpcode.Pmulhrsw) src1 src2))
(rule 1 (x64_pmulhrsw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmulhrsw) src1 src2))

;; Helper for creating `pmulhuw` instructions.
(decl x64_pmulhuw (Xmm XmmMem) Xmm)
(rule 0 (x64_pmulhuw src1 src2)
      (xmm_rm_r (SseOpcode.Pmulhuw) src1 src2))
(rule 1 (x64_pmulhuw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmulhuw) src1 src2))

;; Helper for creating `pmuldq` instructions.
(decl x64_pmuldq (Xmm XmmMem) Xmm)
(rule 0 (x64_pmuldq src1 src2)
      (xmm_rm_r (SseOpcode.Pmuldq) src1 src2))
(rule 1 (x64_pmuldq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmuldq) src1 src2))

;; Helper for creating `pmuludq` instructions.
(decl x64_pmuludq (Xmm XmmMem) Xmm)
(rule 0 (x64_pmuludq src1 src2)
      (xmm_rm_r (SseOpcode.Pmuludq) src1 src2))
(rule 1 (x64_pmuludq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmuludq) src1 src2))

;; Helper for creating `punpckhwd` instructions.
(decl x64_punpckhwd (Xmm XmmMem) Xmm)
(rule 0 (x64_punpckhwd src1 src2)
      (xmm_rm_r (SseOpcode.Punpckhwd) src1 src2))
(rule 1 (x64_punpckhwd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpunpckhwd) src1 src2))

;; Helper for creating `punpcklwd` instructions.
(decl x64_punpcklwd (Xmm XmmMem) Xmm)
(rule 0 (x64_punpcklwd src1 src2)
      (xmm_rm_r (SseOpcode.Punpcklwd) src1 src2))
(rule 1 (x64_punpcklwd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpunpcklwd) src1 src2))

;; Helper for creating `punpckldq` instructions.
(decl x64_punpckldq (Xmm XmmMem) Xmm)
(rule 0 (x64_punpckldq src1 src2)
      (xmm_rm_r (SseOpcode.Punpckldq) src1 src2))
(rule 1 (x64_punpckldq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpunpckldq) src1 src2))

;; Helper for creating `punpckhdq` instructions.
(decl x64_punpckhdq (Xmm XmmMem) Xmm)
(rule 0 (x64_punpckhdq src1 src2)
      (xmm_rm_r (SseOpcode.Punpckhdq) src1 src2))
(rule 1 (x64_punpckhdq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpunpckhdq) src1 src2))

;; Helper for creating `punpcklqdq` instructions.
(decl x64_punpcklqdq (Xmm XmmMem) Xmm)
(rule 0 (x64_punpcklqdq src1 src2)
      (xmm_rm_r (SseOpcode.Punpcklqdq) src1 src2))
(rule 1 (x64_punpcklqdq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpunpcklqdq) src1 src2))

;; Helper for creating `punpckhqdq` instructions.
(decl x64_punpckhqdq (Xmm XmmMem) Xmm)
(rule 0 (x64_punpckhqdq src1 src2)
      (xmm_rm_r (SseOpcode.Punpckhqdq) src1 src2))
(rule 1 (x64_punpckhqdq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpunpckhqdq) src1 src2))

;; Helper for creating `unpcklps` instructions.
(decl x64_unpcklps (Xmm XmmMem) Xmm)
(rule 0 (x64_unpcklps src1 src2)
      (xmm_rm_r (SseOpcode.Unpcklps) src1 src2))
(rule 1 (x64_unpcklps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vunpcklps) src1 src2))

;; Helper for creating `unpcklpd` instructions.
(decl x64_unpcklpd (Xmm XmmMem) Xmm)
(rule 0 (x64_unpcklpd src1 src2)
      (xmm_rm_r (SseOpcode.Unpcklpd) src1 src2))
(rule 1 (x64_unpcklpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vunpcklpd) src1 src2))

;; Helper for creating `unpckhps` instructions.
(decl x64_unpckhps (Xmm XmmMem) Xmm)
(rule 0 (x64_unpckhps src1 src2)
      (xmm_rm_r (SseOpcode.Unpckhps) src1 src2))
(rule 1 (x64_unpckhps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vunpckhps) src1 src2))

;; Helper for creating `andnps` instructions.
(decl x64_andnps (Xmm XmmMem) Xmm)
(rule 0 (x64_andnps src1 src2)
      (xmm_rm_r (SseOpcode.Andnps) src1 src2))
(rule 1 (x64_andnps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vandnps) src1 src2))

;; Helper for creating `andnpd` instructions.
(decl x64_andnpd (Xmm XmmMem) Xmm)
(rule 0 (x64_andnpd src1 src2)
      (xmm_rm_r (SseOpcode.Andnpd) src1 src2))
(rule 1 (x64_andnpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vandnpd) src1 src2))

;; Helper for creating `pandn` instructions.
(decl x64_pandn (Xmm XmmMem) Xmm)
(rule 0 (x64_pandn src1 src2)
      (xmm_rm_r (SseOpcode.Pandn) src1 src2))
(rule 1 (x64_pandn src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpandn) src1 src2))

;; Helper for creating `addss` instructions.
(decl x64_addss (Xmm XmmMem) Xmm)
(rule (x64_addss src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Addss) src1 src2))
(rule 1 (x64_addss src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vaddss) src1 src2))

;; Helper for creating `addsd` instructions.
(decl x64_addsd (Xmm XmmMem) Xmm)
(rule (x64_addsd src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Addsd) src1 src2))
(rule 1 (x64_addsd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vaddsd) src1 src2))

;; Helper for creating `addps` instructions.
(decl x64_addps (Xmm XmmMem) Xmm)
(rule 0 (x64_addps src1 src2)
      (xmm_rm_r (SseOpcode.Addps) src1 src2))
(rule 1 (x64_addps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vaddps) src1 src2))

;; Helper for creating `addpd` instructions.
(decl x64_addpd (Xmm XmmMem) Xmm)
(rule 0 (x64_addpd src1 src2)
      (xmm_rm_r (SseOpcode.Addpd) src1 src2))
(rule 1 (x64_addpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vaddpd) src1 src2))

;; Helper for creating `subss` instructions.
(decl x64_subss (Xmm XmmMem) Xmm)
(rule (x64_subss src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Subss) src1 src2))
(rule 1 (x64_subss src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vsubss) src1 src2))

;; Helper for creating `subsd` instructions.
(decl x64_subsd (Xmm XmmMem) Xmm)
(rule (x64_subsd src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Subsd) src1 src2))
(rule 1 (x64_subsd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vsubsd) src1 src2))

;; Helper for creating `subps` instructions.
(decl x64_subps (Xmm XmmMem) Xmm)
(rule 0 (x64_subps src1 src2)
      (xmm_rm_r (SseOpcode.Subps) src1 src2))
(rule 1 (x64_subps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vsubps) src1 src2))

;; Helper for creating `subpd` instructions.
(decl x64_subpd (Xmm XmmMem) Xmm)
(rule 0 (x64_subpd src1 src2)
      (xmm_rm_r (SseOpcode.Subpd) src1 src2))
(rule 1 (x64_subpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vsubpd) src1 src2))

;; Helper for creating `mulss` instructions.
(decl x64_mulss (Xmm XmmMem) Xmm)
(rule (x64_mulss src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Mulss) src1 src2))
(rule 1 (x64_mulss src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmulss) src1 src2))

;; Helper for creating `mulsd` instructions.
(decl x64_mulsd (Xmm XmmMem) Xmm)
(rule (x64_mulsd src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Mulsd) src1 src2))
(rule 1 (x64_mulsd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmulsd) src1 src2))

;; Helper for creating `mulps` instructions.
(decl x64_mulps (Xmm XmmMem) Xmm)
(rule 0 (x64_mulps src1 src2)
      (xmm_rm_r (SseOpcode.Mulps) src1 src2))
(rule 1 (x64_mulps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmulps) src1 src2))

;; Helper for creating `mulpd` instructions.
(decl x64_mulpd (Xmm XmmMem) Xmm)
(rule (x64_mulpd src1 src2)
      (xmm_rm_r (SseOpcode.Mulpd) src1 src2))
(rule 1 (x64_mulpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmulpd) src1 src2))

;; Helper for creating `divss` instructions.
(decl x64_divss (Xmm XmmMem) Xmm)
(rule (x64_divss src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Divss) src1 src2))
(rule 1 (x64_divss src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vdivss) src1 src2))

;; Helper for creating `divsd` instructions.
(decl x64_divsd (Xmm XmmMem) Xmm)
(rule (x64_divsd src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Divsd) src1 src2))
(rule 1 (x64_divsd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vdivsd) src1 src2))

;; Helper for creating `divps` instructions.
(decl x64_divps (Xmm XmmMem) Xmm)
(rule 0 (x64_divps src1 src2)
      (xmm_rm_r (SseOpcode.Divps) src1 src2))
(rule 1 (x64_divps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vdivps) src1 src2))

;; Helper for creating `divpd` instructions.
(decl x64_divpd (Xmm XmmMem) Xmm)
(rule 0 (x64_divpd src1 src2)
      (xmm_rm_r (SseOpcode.Divpd) src1 src2))
(rule 1 (x64_divpd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vdivpd) src1 src2))

;; Helper for creating `blendvpd` instructions.
(decl x64_blendvpd (Xmm XmmMem Xmm) Xmm)
(rule 0 (x64_blendvpd src1 src2 mask)
      (xmm_rm_r_blend (SseOpcode.Blendvpd) src1 src2 mask))
(rule 1 (x64_blendvpd src1 src2 mask)
      (if-let $true (use_avx))
      (xmm_rmr_blend_vex (AvxOpcode.Vblendvpd) src1 src2 mask))

;; Helper for creating `blendvps` instructions.
(decl x64_blendvps (Xmm XmmMem Xmm) Xmm)
(rule 0 (x64_blendvps src1 src2 mask)
      (xmm_rm_r_blend (SseOpcode.Blendvps) src1 src2 mask))
(rule 1 (x64_blendvps src1 src2 mask)
      (if-let $true (use_avx))
      (xmm_rmr_blend_vex (AvxOpcode.Vblendvps) src1 src2 mask))

;; Helper for creating `pblendvb` instructions.
(decl x64_pblendvb (Xmm XmmMem Xmm) Xmm)
(rule 0 (x64_pblendvb src1 src2 mask)
      (xmm_rm_r_blend (SseOpcode.Pblendvb) src1 src2 mask))
(rule 1 (x64_pblendvb src1 src2 mask)
      (if-let $true (use_avx))
      (xmm_rmr_blend_vex (AvxOpcode.Vpblendvb) src1 src2 mask))

;; Helper for creating `pblendw` instructions.
(decl x64_pblendw (Xmm XmmMem u8) Xmm)
(rule 0 (x64_pblendw src1 src2 imm)
      (xmm_rm_r_imm (SseOpcode.Pblendw) src1 src2 imm (OperandSize.Size32)))
(rule 1 (x64_pblendw src1 src2 imm)
      (if-let $true (use_avx))
      (xmm_rmr_imm_vex (AvxOpcode.Vpblendw) src1 src2 imm))

;; Helper for creating `movsd`/`movss` instructions which create a new vector
;; register where the upper bits are from the first operand and the low
;; bits are from the second operand.
;;
;; Note that the second argument here is specifically `Xmm` instead of `XmmMem`
;; because there is no encoding of a 3-operand form of `movsd` and otherwise
;; when used as a load instruction it wipes out the entire destination register
;; which defeats the purpose of this being a 2-operand instruction.
(decl x64_movsd_regmove (Xmm Xmm) Xmm)
(rule (x64_movsd_regmove src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Movsd) src1 src2))
(rule 1 (x64_movsd_regmove src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vmovsd) src1 src2))

(decl x64_movss_regmove (Xmm Xmm) Xmm)
(rule (x64_movss_regmove src1 src2)
      (xmm_rm_r_unaligned (SseOpcode.Movss) src1 src2))
(rule 1 (x64_movss_regmove src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vmovss) src1 src2))

;; Helper for creating `movlhps` instructions.
(decl x64_movlhps (Xmm XmmMem) Xmm)
(rule 0 (x64_movlhps src1 src2)
      (xmm_rm_r (SseOpcode.Movlhps) src1 src2))
(rule 1 (x64_movlhps src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmovlhps) src1 src2))

;; Helpers for creating `pmaxs*` instructions.
(decl x64_pmaxs (Type Xmm XmmMem) Xmm)
(rule (x64_pmaxs $I8X16 x y) (x64_pmaxsb x y))
(rule (x64_pmaxs $I16X8 x y) (x64_pmaxsw x y))
(rule (x64_pmaxs $I32X4 x y) (x64_pmaxsd x y))
;; No $I64X2 version (PMAXSQ) in SSE4.1.
(decl x64_pmaxsb (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaxsb src1 src2) (xmm_rm_r (SseOpcode.Pmaxsb) src1 src2))
(rule 1 (x64_pmaxsb src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpmaxsb) src1 src2))
(decl x64_pmaxsw (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaxsw src1 src2) (xmm_rm_r (SseOpcode.Pmaxsw) src1 src2))
(rule 1 (x64_pmaxsw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpmaxsw) src1 src2))
(decl x64_pmaxsd (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaxsd src1 src2) (xmm_rm_r (SseOpcode.Pmaxsd) src1 src2))
(rule 1 (x64_pmaxsd src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpmaxsd) src1 src2))

;; Helpers for creating `pmins*` instructions.
(decl x64_pmins (Type Xmm XmmMem) Xmm)
(rule (x64_pmins $I8X16 x y) (x64_pminsb x y))
(rule (x64_pmins $I16X8 x y) (x64_pminsw x y))
(rule (x64_pmins $I32X4 x y) (x64_pminsd x y))
;; No $I64X2 version (PMINSQ) in SSE4.1.
(decl x64_pminsb (Xmm XmmMem) Xmm)
(rule 0 (x64_pminsb src1 src2) (xmm_rm_r (SseOpcode.Pminsb) src1 src2))
(rule 1 (x64_pminsb src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpminsb) src1 src2))
(decl x64_pminsw (Xmm XmmMem) Xmm)
(rule 0 (x64_pminsw src1 src2) (xmm_rm_r (SseOpcode.Pminsw) src1 src2))
(rule 1 (x64_pminsw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpminsw) src1 src2))
(decl x64_pminsd (Xmm XmmMem) Xmm)
(rule 0 (x64_pminsd src1 src2) (xmm_rm_r (SseOpcode.Pminsd) src1 src2))
(rule 1 (x64_pminsd src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpminsd) src1 src2))

;; Helpers for creating `pmaxu*` instructions.
(decl x64_pmaxu (Type Xmm XmmMem) Xmm)
(rule (x64_pmaxu $I8X16 x y) (x64_pmaxub x y))
(rule (x64_pmaxu $I16X8 x y) (x64_pmaxuw x y))
(rule (x64_pmaxu $I32X4 x y) (x64_pmaxud x y))
;; No $I64X2 version (PMAXUQ) in SSE4.1.
(decl x64_pmaxub (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaxub src1 src2) (xmm_rm_r (SseOpcode.Pmaxub) src1 src2))
(rule 1 (x64_pmaxub src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpmaxub) src1 src2))
(decl x64_pmaxuw (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaxuw src1 src2) (xmm_rm_r (SseOpcode.Pmaxuw) src1 src2))
(rule 1 (x64_pmaxuw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpmaxuw) src1 src2))
(decl x64_pmaxud (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaxud src1 src2) (xmm_rm_r (SseOpcode.Pmaxud) src1 src2))
(rule 1 (x64_pmaxud src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpmaxud) src1 src2))

;; Helper for creating `pminu*` instructions.
(decl x64_pminu (Type Xmm XmmMem) Xmm)
(rule (x64_pminu $I8X16 x y) (x64_pminub x y))
(rule (x64_pminu $I16X8 x y) (x64_pminuw x y))
(rule (x64_pminu $I32X4 x y) (x64_pminud x y))
;; No $I64X2 version (PMINUQ) in SSE4.1.
(decl x64_pminub (Xmm XmmMem) Xmm)
(rule 0 (x64_pminub src1 src2) (xmm_rm_r (SseOpcode.Pminub) src1 src2))
(rule 1 (x64_pminub src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpminub) src1 src2))
(decl x64_pminuw (Xmm XmmMem) Xmm)
(rule 0 (x64_pminuw src1 src2) (xmm_rm_r (SseOpcode.Pminuw) src1 src2))
(rule 1 (x64_pminuw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpminuw) src1 src2))
(decl x64_pminud (Xmm XmmMem) Xmm)
(rule 0 (x64_pminud src1 src2) (xmm_rm_r (SseOpcode.Pminud) src1 src2))
(rule 1 (x64_pminud src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpminud) src1 src2))

;; Helper for creating `punpcklbw` instructions.
(decl x64_punpcklbw (Xmm XmmMem) Xmm)
(rule 0 (x64_punpcklbw src1 src2)
      (xmm_rm_r (SseOpcode.Punpcklbw) src1 src2))
(rule 1 (x64_punpcklbw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpunpcklbw) src1 src2))

;; Helper for creating `punpckhbw` instructions.
(decl x64_punpckhbw (Xmm XmmMem) Xmm)
(rule 0 (x64_punpckhbw src1 src2)
      (xmm_rm_r (SseOpcode.Punpckhbw) src1 src2))
(rule 1 (x64_punpckhbw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpunpckhbw) src1 src2))

;; Helper for creating `packsswb` instructions.
(decl x64_packsswb (Xmm XmmMem) Xmm)
(rule 0 (x64_packsswb src1 src2)
      (xmm_rm_r (SseOpcode.Packsswb) src1 src2))
(rule 1 (x64_packsswb src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpacksswb) src1 src2))

;; Helper for creating `packssdw` instructions.
(decl x64_packssdw (Xmm XmmMem) Xmm)
(rule 0 (x64_packssdw src1 src2)
      (xmm_rm_r (SseOpcode.Packssdw) src1 src2))
(rule 1 (x64_packssdw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpackssdw) src1 src2))

;; Helper for creating `packuswb` instructions.
(decl x64_packuswb (Xmm XmmMem) Xmm)
(rule 0 (x64_packuswb src1 src2)
      (xmm_rm_r (SseOpcode.Packuswb) src1 src2))
(rule 1 (x64_packuswb src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpackuswb) src1 src2))

;; Helper for creating `packusdw` instructions.
(decl x64_packusdw (Xmm XmmMem) Xmm)
(rule 0 (x64_packusdw src1 src2)
      (xmm_rm_r (SseOpcode.Packusdw) src1 src2))
(rule 1 (x64_packusdw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpackusdw) src1 src2))

;; Helper for creating `palignr` instructions.
(decl x64_palignr (Xmm XmmMem u8) Xmm)
(rule 0 (x64_palignr src1 src2 imm)
      (xmm_rm_r_imm (SseOpcode.Palignr)
                    src1
                    src2
                    imm
                    (OperandSize.Size32)))
(rule 1 (x64_palignr src1 src2 imm)
      (if-let $true (use_avx))
      (xmm_rmr_imm_vex (AvxOpcode.Vpalignr) src1 src2 imm))

;; Helpers for creating `cmpp*` instructions.
(decl x64_cmpp (Type Xmm XmmMem FcmpImm) Xmm)
(rule (x64_cmpp $F32X4 x y imm) (x64_cmpps x y imm))
(rule (x64_cmpp $F64X2 x y imm) (x64_cmppd x y imm))

(decl x64_cmpps (Xmm XmmMem FcmpImm) Xmm)
(rule 0 (x64_cmpps src1 src2 imm)
      (xmm_rm_r_imm (SseOpcode.Cmpps)
                    src1
                    src2
                    (encode_fcmp_imm imm)
                    (OperandSize.Size32)))
(rule 1 (x64_cmpps src1 src2 imm)
      (if-let $true (use_avx))
      (xmm_rmr_imm_vex (AvxOpcode.Vcmpps)
                       src1
                       src2
                       (encode_fcmp_imm imm)))

;; Note that `Size32` is intentional despite this being used for 64-bit
;; operations, since this presumably induces the correct encoding of the
;; instruction.
(decl x64_cmppd (Xmm XmmMem FcmpImm) Xmm)
(rule 0 (x64_cmppd src1 src2 imm)
      (xmm_rm_r_imm (SseOpcode.Cmppd)
                    src1
                    src2
                    (encode_fcmp_imm imm)
                    (OperandSize.Size32)))
(rule 1 (x64_cmppd src1 src2 imm)
      (if-let $true (use_avx))
      (xmm_rmr_imm_vex (AvxOpcode.Vcmppd)
                       src1
                       src2
                       (encode_fcmp_imm imm)))

;; Helper for creating `pinsrb` instructions.
(decl x64_pinsrb (Xmm GprMem u8) Xmm)
(rule 0 (x64_pinsrb src1 src2 lane)
      (xmm_rm_r_imm (SseOpcode.Pinsrb)
                    src1
                    src2
                    lane
                    (OperandSize.Size32)))
(rule 1 (x64_pinsrb src1 src2 lane)
      (if-let $true (use_avx))
      (xmm_vex_pinsr (AvxOpcode.Vpinsrb) src1 src2 lane))

;; Helper for creating `pinsrw` instructions.
(decl x64_pinsrw (Xmm GprMem u8) Xmm)
(rule 0 (x64_pinsrw src1 src2 lane)
      (xmm_rm_r_imm (SseOpcode.Pinsrw)
                    src1
                    src2
                    lane
                    (OperandSize.Size32)))
(rule 1 (x64_pinsrw src1 src2 lane)
      (if-let $true (use_avx))
      (xmm_vex_pinsr (AvxOpcode.Vpinsrw) src1 src2 lane))

;; Helper for creating `pinsrd` instructions.
(decl x64_pinsrd (Xmm GprMem u8) Xmm)
(rule 0 (x64_pinsrd src1 src2 lane)
      (xmm_rm_r_imm (SseOpcode.Pinsrd)
                    src1
                    src2
                    lane
                    (OperandSize.Size32)))
(rule 1 (x64_pinsrd src1 src2 lane)
      (if-let $true (use_avx))
      (xmm_vex_pinsr (AvxOpcode.Vpinsrd) src1 src2 lane))

;; Helper for creating `pinsrq` instructions.
(decl x64_pinsrq (Xmm GprMem u8) Xmm)
(rule (x64_pinsrq src1 src2 lane)
      (xmm_rm_r_imm (SseOpcode.Pinsrd)
                    src1
                    src2
                    lane
                    (OperandSize.Size64)))
(rule 1 (x64_pinsrq src1 src2 lane)
      (if-let $true (use_avx))
      (xmm_vex_pinsr (AvxOpcode.Vpinsrq) src1 src2 lane))

;; Helper for creating `roundss` instructions.
;;
;; NB: the non-AVX variant of this instruction does not require that the operand
;; is aligned, but the instruction variant used here requires it to be aligned.
;; This means that if the operand here points to memory then we'll eagerly load
;; it, but the eager load will load too much (the full register width of 16
;; bytes). To fix this a `put_xmm_mem_in_xmm` helper is used to force the
;; operand to be a register where the load is done with the appropriate type if
;; it's in memory.
;;
;; Some more discussion of this can be found on #8112. Ideally this would use
;; a variant that allows an unaligned `XmmMem` in the instruction variant.
;; Either that or the auto-conversion to aligned memory is removed and/or starts
;; to require a type.
;;
;; Also note that the argument here isn't changed to `Xmm` instead of `XmmMem`
;; because the AVX variant, when available, doesn't need alignment and can
;; pass through the `src1` argument as-is.
(decl x64_roundss (XmmMem RoundImm) Xmm)
(rule (x64_roundss src1 round)
      (xmm_unary_rm_r_imm (SseOpcode.Roundss) (put_xmm_mem_in_xmm $F32 src1) (encode_round_imm round)))
(rule 1 (x64_roundss src1 round)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_imm_vex (AvxOpcode.Vroundss) src1 (encode_round_imm round)))

;; Helper for creating `roundsd` instructions.
;;
;; NB: see `x64_roundss` above for `put_xmm_mem_in_xmm` in call.
(decl x64_roundsd (XmmMem RoundImm) Xmm)
(rule (x64_roundsd src1 round)
      (xmm_unary_rm_r_imm (SseOpcode.Roundsd) (put_xmm_mem_in_xmm $F64 src1) (encode_round_imm round)))
(rule 1 (x64_roundsd src1 round)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_imm_vex (AvxOpcode.Vroundsd) src1 (encode_round_imm round)))

;; Helper for forcing an `XmmMem` to be placed into an `Xmm` register.
;;
;; If it's already in a register it stays there, otherwise it turns into a
;; load instruction with the destination register as output.
(decl put_xmm_mem_in_xmm (Type XmmMem) Xmm)
(rule (put_xmm_mem_in_xmm ty xmm_mem)
      (if-let (RegMem.Reg r) (xmm_mem_to_reg_mem xmm_mem))
      (xmm_new r))
(rule (put_xmm_mem_in_xmm ty xmm_mem)
      (if-let (RegMem.Mem amode) (xmm_mem_to_reg_mem xmm_mem))
      (x64_load ty amode (ExtKind.None)))

;; Helper for creating `roundps` instructions.
(decl x64_roundps (XmmMem RoundImm) Xmm)
(rule (x64_roundps src1 round)
      (xmm_unary_rm_r_imm (SseOpcode.Roundps) src1 (encode_round_imm round)))
(rule 1 (x64_roundps src1 round)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_imm_vex (AvxOpcode.Vroundps) src1 (encode_round_imm round)))

;; Helper for creating `roundpd` instructions.
(decl x64_roundpd (XmmMem RoundImm) Xmm)
(rule (x64_roundpd src1 round)
      (xmm_unary_rm_r_imm (SseOpcode.Roundpd) src1 (encode_round_imm round)))
(rule 1 (x64_roundpd src1 round)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_imm_vex (AvxOpcode.Vroundpd) src1 (encode_round_imm round)))

;; Helper for creating `pmaddwd` instructions.
(decl x64_pmaddwd (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaddwd src1 src2)
      (xmm_rm_r (SseOpcode.Pmaddwd) src1 src2))
(rule 1 (x64_pmaddwd src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmaddwd) src1 src2))

(decl x64_pmaddubsw (Xmm XmmMem) Xmm)
(rule 0 (x64_pmaddubsw src1 src2)
      (xmm_rm_r (SseOpcode.Pmaddubsw) src1 src2))
(rule 1 (x64_pmaddubsw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpmaddubsw) src1 src2))

;; Helper for creating `insertps` instructions.
(decl x64_insertps (Xmm XmmMem u8) Xmm)
(rule 0 (x64_insertps src1 src2 lane)
      (xmm_rm_r_imm (SseOpcode.Insertps)
                    src1
                    src2
                    lane
                    (OperandSize.Size32)))
(rule 1 (x64_insertps src1 src2 lane)
      (if-let $true (use_avx))
      (xmm_rmr_imm_vex (AvxOpcode.Vinsertps) src1 src2 lane))

;; Helper for creating `pshufd` instructions.
(decl x64_pshufd (XmmMem u8) Xmm)
(rule (x64_pshufd src imm)
      (xmm_unary_rm_r_imm (SseOpcode.Pshufd) src imm))
(rule 1 (x64_pshufd src imm)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_imm_vex (AvxOpcode.Vpshufd) src imm))

;; Helper for creating `pshufb` instructions.
(decl x64_pshufb (Xmm XmmMem) Xmm)
(rule 0 (x64_pshufb src1 src2)
      (xmm_rm_r (SseOpcode.Pshufb) src1 src2))
(rule 1 (x64_pshufb src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpshufb) src1 src2))

;; Helper for creating `pshuflw` instructions.
(decl x64_pshuflw (XmmMem u8) Xmm)
(rule (x64_pshuflw src imm)
      (xmm_unary_rm_r_imm (SseOpcode.Pshuflw) src imm))
(rule 1 (x64_pshuflw src imm)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_imm_vex (AvxOpcode.Vpshuflw) src imm))

;; Helper for creating `pshufhw` instructions.
(decl x64_pshufhw (XmmMem u8) Xmm)
(rule (x64_pshufhw src imm)
      (xmm_unary_rm_r_imm (SseOpcode.Pshufhw) src imm))
(rule 1 (x64_pshufhw src imm)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_imm_vex (AvxOpcode.Vpshufhw) src imm))

;; Helper for creating `shufps` instructions.
(decl x64_shufps (Xmm XmmMem u8) Xmm)
(rule 0 (x64_shufps src1 src2 byte)
      (xmm_rm_r_imm (SseOpcode.Shufps)
                    src1
                    src2
                    byte
                    (OperandSize.Size32)))
(rule 1 (x64_shufps src1 src2 byte)
      (if-let $true (use_avx))
      (xmm_rmr_imm_vex (AvxOpcode.Vshufps) src1 src2 byte))

;; Helper for creating `pabsb` instructions.
(decl x64_pabsb (XmmMem) Xmm)
(rule (x64_pabsb src)
      (xmm_unary_rm_r (SseOpcode.Pabsb) src))
(rule 1 (x64_pabsb src)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpabsb) src))

;; Helper for creating `pabsw` instructions.
(decl x64_pabsw (XmmMem) Xmm)
(rule (x64_pabsw src)
      (xmm_unary_rm_r (SseOpcode.Pabsw) src))
(rule 1 (x64_pabsw src)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpabsw) src))

;; Helper for creating `pabsd` instructions.
(decl x64_pabsd (XmmMem) Xmm)
(rule (x64_pabsd src)
      (xmm_unary_rm_r (SseOpcode.Pabsd) src))
(rule 1 (x64_pabsd src)
      (if-let $true (use_avx))
      (xmm_unary_rm_r_vex (AvxOpcode.Vpabsd) src))

;; Helper for creating `vcvtudq2ps` instructions.
(decl x64_vcvtudq2ps (XmmMem) Xmm)
(rule (x64_vcvtudq2ps src)
      (xmm_unary_rm_r_evex (Avx512Opcode.Vcvtudq2ps) src))

;; Helper for creating `vpabsq` instructions.
(decl x64_vpabsq (XmmMem) Xmm)
(rule (x64_vpabsq src)
      (xmm_unary_rm_r_evex (Avx512Opcode.Vpabsq) src))

;; Helper for creating `vpopcntb` instructions.
(decl x64_vpopcntb (XmmMem) Xmm)
(rule (x64_vpopcntb src)
      (xmm_unary_rm_r_evex (Avx512Opcode.Vpopcntb) src))

;; Helper for creating `vpmullq` instructions.
;;
;; Requires AVX-512 vl and dq.
(decl x64_vpmullq (Xmm XmmMem) Xmm)
(rule (x64_vpmullq src1 src2)
      (xmm_rm_r_evex (Avx512Opcode.Vpmullq)
                     src1
                     src2))

;; Helper for creating `vpermi2b` instructions.
;;
;; Requires AVX-512 vl and vbmi extensions.
(decl x64_vpermi2b (Xmm Xmm XmmMem) Xmm)
(rule (x64_vpermi2b src1 src2 src3)
      (let ((dst WritableXmm (temp_writable_xmm))
            (_ Unit (emit (MInst.XmmRmREvex3 (Avx512Opcode.Vpermi2b)
                                             src1
                                             src2
                                             src3
                                             dst))))
        dst))

;; Helper for creating `psllw` instructions.
(decl x64_psllw (Xmm XmmMemImm) Xmm)
(rule 0 (x64_psllw src1 src2)
      (xmm_rmi_xmm (SseOpcode.Psllw) src1 src2))
(rule 1 (x64_psllw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpsllw) src1 src2))

;; Helper for creating `pslld` instructions.
(decl x64_pslld (Xmm XmmMemImm) Xmm)
(rule 0 (x64_pslld src1 src2)
      (xmm_rmi_xmm (SseOpcode.Pslld) src1 src2))
(rule 1 (x64_pslld src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpslld) src1 src2))

;; Helper for creating `psllq` instructions.
(decl x64_psllq (Xmm XmmMemImm) Xmm)
(rule 0 (x64_psllq src1 src2)
      (xmm_rmi_xmm (SseOpcode.Psllq) src1 src2))
(rule 1 (x64_psllq src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpsllq) src1 src2))

;; Helper for creating `psrlw` instructions.
(decl x64_psrlw (Xmm XmmMemImm) Xmm)
(rule 0 (x64_psrlw src1 src2)
      (xmm_rmi_xmm (SseOpcode.Psrlw) src1 src2))
(rule 1 (x64_psrlw src1 src2)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpsrlw) src1 src2))

;; Helper for creating `psrld` instructions.
(decl x64_psrld (Xmm XmmMemImm) Xmm)
(rule 0 (x64_psrld src1 src2)
      (xmm_rmi_xmm (SseOpcode.Psrld) src1 src2))
(rule 1 (x64_psrld src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsrld) src1 src2))

;; Helper for creating `psrlq` instructions.
(decl x64_psrlq (Xmm XmmMemImm) Xmm)
(rule 0 (x64_psrlq src1 src2)
      (xmm_rmi_xmm (SseOpcode.Psrlq) src1 src2))
(rule 1 (x64_psrlq src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsrlq) src1 src2))

;; Helper for creating `psraw` instructions.
(decl x64_psraw (Xmm XmmMemImm) Xmm)
(rule 0 (x64_psraw src1 src2)
      (xmm_rmi_xmm (SseOpcode.Psraw) src1 src2))
(rule 1 (x64_psraw src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsraw) src1 src2))

;; Helper for creating `psrad` instructions.
(decl x64_psrad (Xmm XmmMemImm) Xmm)
(rule 0 (x64_psrad src1 src2)
      (xmm_rmi_xmm (SseOpcode.Psrad) src1 src2))
(rule 1 (x64_psrad src1 src2)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vpsrad) src1 src2))

;; Helper for creating `vpsraq` instructions.
(decl x64_vpsraq (Xmm XmmMem) Xmm)
(rule (x64_vpsraq src1 src2)
      (xmm_rm_r_evex (Avx512Opcode.Vpsraq) src1 src2))

;; Helper for creating `vpsraq` instructions.
(decl x64_vpsraq_imm (XmmMem u8) Xmm)
(rule (x64_vpsraq_imm src imm)
      (xmm_unary_rm_r_imm_evex (Avx512Opcode.VpsraqImm) src imm))

;; Helper for creating `pextrb` instructions.
(decl x64_pextrb (Xmm u8) Gpr)
(rule (x64_pextrb src lane)
      (xmm_to_gpr_imm (SseOpcode.Pextrb) src lane))
(rule 1 (x64_pextrb src lane)
        (if-let $true (use_avx))
        (xmm_to_gpr_imm_vex (AvxOpcode.Vpextrb) src lane))

(decl x64_pextrb_store (SyntheticAmode Xmm u8) SideEffectNoResult)
(rule (x64_pextrb_store addr src lane)
      (xmm_movrm_imm (SseOpcode.Pextrb) addr src lane))
(rule 1 (x64_pextrb_store addr src lane)
        (if-let $true (use_avx))
        (xmm_movrm_imm_vex (AvxOpcode.Vpextrb) addr src lane))

;; Helper for creating `pextrw` instructions.
(decl x64_pextrw (Xmm u8) Gpr)
(rule (x64_pextrw src lane)
      (xmm_to_gpr_imm (SseOpcode.Pextrw) src lane))
(rule 1 (x64_pextrw src lane)
        (if-let $true (use_avx))
        (xmm_to_gpr_imm_vex (AvxOpcode.Vpextrw) src lane))

(decl x64_pextrw_store (SyntheticAmode Xmm u8) SideEffectNoResult)
(rule (x64_pextrw_store addr src lane)
      (xmm_movrm_imm (SseOpcode.Pextrw) addr src lane))
(rule 1 (x64_pextrw_store addr src lane)
        (if-let $true (use_avx))
        (xmm_movrm_imm_vex (AvxOpcode.Vpextrw) addr src lane))

;; Helper for creating `pextrd` instructions.
(decl x64_pextrd (Xmm u8) Gpr)
(rule (x64_pextrd src lane)
      (xmm_to_gpr_imm (SseOpcode.Pextrd) src lane))
(rule 1 (x64_pextrd src lane)
        (if-let $true (use_avx))
        (xmm_to_gpr_imm_vex (AvxOpcode.Vpextrd) src lane))

(decl x64_pextrd_store (SyntheticAmode Xmm u8) SideEffectNoResult)
(rule (x64_pextrd_store addr src lane)
      (xmm_movrm_imm (SseOpcode.Pextrd) addr src lane))
(rule 1 (x64_pextrd_store addr src lane)
        (if-let $true (use_avx))
        (xmm_movrm_imm_vex (AvxOpcode.Vpextrd) addr src lane))

;; Helper for creating `pextrq` instructions.
(decl x64_pextrq (Xmm u8) Gpr)
(rule (x64_pextrq src lane)
      (xmm_to_gpr_imm (SseOpcode.Pextrq) src lane))
(rule 1 (x64_pextrq src lane)
        (if-let $true (use_avx))
        (xmm_to_gpr_imm_vex (AvxOpcode.Vpextrq) src lane))

(decl x64_pextrq_store (SyntheticAmode Xmm u8) SideEffectNoResult)
(rule (x64_pextrq_store addr src lane)
      (xmm_movrm_imm (SseOpcode.Pextrq) addr src lane))
(rule 1 (x64_pextrq_store addr src lane)
        (if-let $true (use_avx))
        (xmm_movrm_imm_vex (AvxOpcode.Vpextrq) addr src lane))

;; Helper for creating `pmovmskb` instructions.
(decl x64_pmovmskb (OperandSize Xmm) Gpr)
(rule (x64_pmovmskb size src)
      (xmm_to_gpr (SseOpcode.Pmovmskb) src size))
(rule 1 (x64_pmovmskb size src)
        (if-let $true (use_avx))
        (xmm_to_gpr_vex (AvxOpcode.Vpmovmskb) src size))

;; Helper for creating `movmskps` instructions.
(decl x64_movmskps (OperandSize Xmm) Gpr)
(rule (x64_movmskps size src)
      (xmm_to_gpr (SseOpcode.Movmskps) src size))
(rule 1 (x64_movmskps size src)
        (if-let $true (use_avx))
        (xmm_to_gpr_vex (AvxOpcode.Vmovmskps) src size))

;; Helper for creating `movmskpd` instructions.
(decl x64_movmskpd (OperandSize Xmm) Gpr)
(rule (x64_movmskpd size src)
      (xmm_to_gpr (SseOpcode.Movmskpd) src size))
(rule 1 (x64_movmskpd size src)
        (if-let $true (use_avx))
        (xmm_to_gpr_vex (AvxOpcode.Vmovmskpd) src size))

;; Helper for creating `not` instructions.
(decl x64_not (Type Gpr) Gpr)
(rule (x64_not ty src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (_ Unit (emit (MInst.Not size src dst))))
        dst))

;; Helper for creating `neg` instructions.
(decl x64_neg (Type Gpr) Gpr)
(rule (x64_neg ty src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (raw_operand_size_of_type ty))
            (_ Unit (emit (MInst.Neg size src dst))))
        dst))

;; Helper for creating `neg` instructions whose flags are also used.
(decl x64_neg_paired (Type Gpr) ProducesFlags)
(rule (x64_neg_paired ty src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (raw_operand_size_of_type ty))
            (inst MInst (MInst.Neg size src dst)))
        (ProducesFlags.ProducesFlagsReturnsResultWithConsumer inst dst)))

(decl x64_lea (Type SyntheticAmode) Gpr)
(rule (x64_lea ty addr)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.LoadEffectiveAddress addr dst (operand_size_of_type_32_64 ty)))))
        dst))

;; Helper for creating `ud2` instructions.
(decl x64_ud2 (TrapCode) SideEffectNoResult)
(rule (x64_ud2 code)
      (SideEffectNoResult.Inst (MInst.Ud2 code)))

;; Helper for creating `hlt` instructions.
(decl x64_hlt () SideEffectNoResult)
(rule (x64_hlt)
      (SideEffectNoResult.Inst (MInst.Hlt)))

;; Helper for creating `lzcnt` instructions.
(decl x64_lzcnt (Type Gpr) Gpr)
(rule (x64_lzcnt ty src)
      (unary_rm_r (UnaryRmROpcode.Lzcnt) src (operand_size_of_type_32_64 ty)))

;; Helper for creating `tzcnt` instructions.
(decl x64_tzcnt (Type Gpr) Gpr)
(rule (x64_tzcnt ty src)
      (unary_rm_r (UnaryRmROpcode.Tzcnt) src (operand_size_of_type_32_64 ty)))

;; Helper for creating `bsr` instructions.
(decl x64_bsr (Type Gpr) ProducesFlags)
(rule (x64_bsr ty src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (inst MInst (MInst.UnaryRmR size (UnaryRmROpcode.Bsr) src dst)))
        (ProducesFlags.ProducesFlagsReturnsReg inst dst)))

;; Helper for creating `bsr + cmov` instruction pairs that produce the
;; result of the `bsr`, or `alt` if the input was zero.
(decl bsr_or_else (Type Gpr Gpr) Gpr)
(rule (bsr_or_else ty src alt)
      (let ((bsr ProducesFlags (x64_bsr ty src))
            ;; Manually extract the result from the bsr, then ignore
            ;; it below, since we need to thread it into the cmove
            ;; before we pass the cmove to with_flags_reg.
            (bsr_result Gpr (produces_flags_get_reg bsr))
            (cmove ConsumesFlags (cmove ty (CC.Z) alt bsr_result)))
        (with_flags_reg (produces_flags_ignore bsr) cmove)))

;; Helper for creating `bsf` instructions.
(decl x64_bsf (Type Gpr) ProducesFlags)
(rule (x64_bsf ty src)
      (let ((dst WritableGpr (temp_writable_gpr))
            (size OperandSize (operand_size_of_type_32_64 ty))
            (inst MInst (MInst.UnaryRmR size (UnaryRmROpcode.Bsf) src dst)))
        (ProducesFlags.ProducesFlagsReturnsReg inst dst)))

;; Helper for creating `bsf + cmov` instruction pairs that produce the
;; result of the `bsf`, or `alt` if the input was zero.
(decl bsf_or_else (Type Gpr Gpr) Gpr)
(rule (bsf_or_else ty src alt)
      (let ((bsf ProducesFlags (x64_bsf ty src))
            ;; Manually extract the result from the bsf, then ignore
            ;; it below, since we need to thread it into the cmove
            ;; before we pass the cmove to with_flags_reg.
            (bsf_result Gpr (produces_flags_get_reg bsf))
            (cmove ConsumesFlags (cmove ty (CC.Z) alt bsf_result)))
        (with_flags_reg (produces_flags_ignore bsf) cmove)))

;; Helper for creating `blsi` instructions.
(decl x64_blsi (Type GprMem) Gpr)
(rule (x64_blsi ty src)
      (unary_rm_r_vex (UnaryRmRVexOpcode.Blsi) src (operand_size_of_type_32_64 ty)))

;; Helper for creating `blsmsk` instructions.
(decl x64_blsmsk (Type GprMem) Gpr)
(rule (x64_blsmsk ty src)
      (unary_rm_r_vex (UnaryRmRVexOpcode.Blsmsk) src (operand_size_of_type_32_64 ty)))

;; Helper for creating `blsr` instructions.
(decl x64_blsr (Type GprMem) Gpr)
(rule (x64_blsr ty src)
      (unary_rm_r_vex (UnaryRmRVexOpcode.Blsr) src (operand_size_of_type_32_64 ty)))

;; Helper for creating `sarx` instructions.
(decl x64_sarx (Type GprMem Gpr) Gpr)
(rule (x64_sarx ty val amt)
      (alu_rm_r_vex ty (AluRmROpcode.Sarx) amt val))

;; Helper for creating `shrx` instructions.
(decl x64_shrx (Type GprMem Gpr) Gpr)
(rule (x64_shrx ty val amt)
      (alu_rm_r_vex ty (AluRmROpcode.Shrx) amt val))

;; Helper for creating `shlx` instructions.
(decl x64_shlx (Type GprMem Gpr) Gpr)
(rule (x64_shlx ty val amt)
      (alu_rm_r_vex ty (AluRmROpcode.Shlx) amt val))

;; Helper for creating `rorx` instructions.
(decl x64_rorx (Type GprMem u8) Gpr)
(rule (x64_rorx ty src imm)
      (unary_rm_r_imm_vex (UnaryRmRImmVexOpcode.Rorx)
                          src
                          (operand_size_of_type_32_64 ty)
                          imm))

;; Helper for creating `popcnt` instructions.
(decl x64_popcnt (Type Gpr) Gpr)
(rule (x64_popcnt ty src)
      (unary_rm_r (UnaryRmROpcode.Popcnt) src (operand_size_of_type_32_64 ty)))

;; Helper for creating `minss` instructions.
(decl x64_minss (Xmm XmmMem) Xmm)
(rule (x64_minss x y)
      (xmm_rm_r_unaligned (SseOpcode.Minss) x y))
(rule 1 (x64_minss x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vminss) x y))

;; Helper for creating `minsd` instructions.
(decl x64_minsd (Xmm XmmMem) Xmm)
(rule (x64_minsd x y)
      (xmm_rm_r_unaligned (SseOpcode.Minsd) x y))
(rule 1 (x64_minsd x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vminsd) x y))

;; Helper for creating `minps` instructions.
(decl x64_minps (Xmm XmmMem) Xmm)
(rule 0 (x64_minps x y)
      (xmm_rm_r (SseOpcode.Minps) x y))
(rule 1 (x64_minps x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vminps) x y))

;; Helper for creating `minpd` instructions.
(decl x64_minpd (Xmm XmmMem) Xmm)
(rule 0 (x64_minpd x y)
      (xmm_rm_r (SseOpcode.Minpd) x y))
(rule 1 (x64_minpd x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vminpd) x y))

;; Helper for creating `maxss` instructions.
(decl x64_maxss (Xmm XmmMem) Xmm)
(rule (x64_maxss x y)
      (xmm_rm_r_unaligned (SseOpcode.Maxss) x y))
(rule 1 (x64_maxss x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmaxss) x y))

;; Helper for creating `maxsd` instructions.
(decl x64_maxsd (Xmm XmmMem) Xmm)
(rule (x64_maxsd x y)
      (xmm_rm_r_unaligned (SseOpcode.Maxsd) x y))
(rule 1 (x64_maxsd x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmaxsd) x y))

;; Helper for creating `maxps` instructions.
(decl x64_maxps (Xmm XmmMem) Xmm)
(rule 0 (x64_maxps x y)
      (xmm_rm_r (SseOpcode.Maxps) x y))
(rule 1 (x64_maxps x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmaxps) x y))

;; Helper for creating `maxpd` instructions.
(decl x64_maxpd (Xmm XmmMem) Xmm)
(rule 0 (x64_maxpd x y)
      (xmm_rm_r (SseOpcode.Maxpd) x y))
(rule 1 (x64_maxpd x y)
      (if-let $true (use_avx))
      (xmm_rmir_vex (AvxOpcode.Vmaxpd) x y))

;; Helper for creating `vfmadd213*` instructions
(decl x64_vfmadd213 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfmadd213 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd213ss) a b c))
(rule (x64_vfmadd213 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd213sd) a b c))
(rule (x64_vfmadd213 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd213ps) a b c))
(rule (x64_vfmadd213 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd213pd) a b c))

;; Helper for creating `vfmadd132*` instructions
(decl x64_vfmadd132 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfmadd132 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd132ss) a b c))
(rule (x64_vfmadd132 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd132sd) a b c))
(rule (x64_vfmadd132 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd132ps) a b c))
(rule (x64_vfmadd132 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmadd132pd) a b c))

;; Helper for creating `vfnmadd213*` instructions
(decl x64_vfnmadd213 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfnmadd213 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd213ss) a b c))
(rule (x64_vfnmadd213 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd213sd) a b c))
(rule (x64_vfnmadd213 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd213ps) a b c))
(rule (x64_vfnmadd213 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd213pd) a b c))

;; Helper for creating `vfnmadd132*` instructions
(decl x64_vfnmadd132 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfnmadd132 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd132ss) a b c))
(rule (x64_vfnmadd132 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd132sd) a b c))
(rule (x64_vfnmadd132 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd132ps) a b c))
(rule (x64_vfnmadd132 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmadd132pd) a b c))

;; Helper for creating `vfmsub213*` instructions
(decl x64_vfmsub213 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfmsub213 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub213ss) a b c))
(rule (x64_vfmsub213 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub213sd) a b c))
(rule (x64_vfmsub213 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub213ps) a b c))
(rule (x64_vfmsub213 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub213pd) a b c))

;; Helper for creating `vfmsub132*` instructions
(decl x64_vfmsub132 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfmsub132 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub132ss) a b c))
(rule (x64_vfmsub132 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub132sd) a b c))
(rule (x64_vfmsub132 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub132ps) a b c))
(rule (x64_vfmsub132 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfmsub132pd) a b c))

;; Helper for creating `vfnmsub213*` instructions
(decl x64_vfnmsub213 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfnmsub213 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub213ss) a b c))
(rule (x64_vfnmsub213 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub213sd) a b c))
(rule (x64_vfnmsub213 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub213ps) a b c))
(rule (x64_vfnmsub213 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub213pd) a b c))

;; Helper for creating `vfnmsub132*` instructions
(decl x64_vfnmsub132 (Type Xmm Xmm XmmMem) Xmm)
(rule (x64_vfnmsub132 $F32 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub132ss) a b c))
(rule (x64_vfnmsub132 $F64 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub132sd) a b c))
(rule (x64_vfnmsub132 $F32X4 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub132ps) a b c))
(rule (x64_vfnmsub132 $F64X2 a b c) (xmm_rmr_vex3 (AvxOpcode.Vfnmsub132pd) a b c))

;; Note, the `vfmsub231` and `vfnmsub231*` instructions are omitted, because
;; instruction selection happens before register allocation and therefore there
;; is no benefit to a a third permutation

;; Helper for creating `sqrtss` instructions.
;;
;; NB: the square-root operation technically only has one operand but this
;; instruction has two. This is to reflect how the square root operation copies
;; the upper bits of the first register and only performs the square root
;; operation on the low bits of the second register. This introduces
;; a data-dependency on the contents of the first register which is modeled
;; here.
(decl x64_sqrtss (Xmm XmmMem) Xmm)
(rule (x64_sqrtss x y) (xmm_rm_r_unaligned (SseOpcode.Sqrtss) x y))
(rule 1 (x64_sqrtss x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vsqrtss) x y))

;; Helper for creating `sqrtsd` instructions.
;;
;; NB: see `x64_sqrtss` for explanation of why this has two args.
(decl x64_sqrtsd (Xmm XmmMem) Xmm)
(rule (x64_sqrtsd x y) (xmm_rm_r_unaligned (SseOpcode.Sqrtsd) x y))
(rule 1 (x64_sqrtsd x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vsqrtsd) x y))

;; Helper for creating `sqrtps` instructions.
(decl x64_sqrtps (XmmMem) Xmm)
(rule (x64_sqrtps x) (xmm_unary_rm_r (SseOpcode.Sqrtps) x))
(rule 1 (x64_sqrtps x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vsqrtps) x))

;; Helper for creating `sqrtpd` instructions.
(decl x64_sqrtpd (XmmMem) Xmm)
(rule (x64_sqrtpd x) (xmm_unary_rm_r (SseOpcode.Sqrtpd) x))
(rule 1 (x64_sqrtpd x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vsqrtpd) x))

;; Helper for creating `cvtss2sd` instructions.
;;
;; NB: see `x64_sqrtss` for why this has two args (same reasoning, different op)
(decl x64_cvtss2sd (Xmm XmmMem) Xmm)
(rule (x64_cvtss2sd x y) (xmm_rm_r_unaligned (SseOpcode.Cvtss2sd) x y))
(rule 1 (x64_cvtss2sd x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vcvtss2sd) x y))

;; Helper for creating `cvtsd2ss` instructions.
;;
;; NB: see `x64_sqrtss` for why this has two args (same reasoning, different op)
(decl x64_cvtsd2ss (Xmm XmmMem) Xmm)
(rule (x64_cvtsd2ss x y) (xmm_rm_r_unaligned (SseOpcode.Cvtsd2ss) x y))
(rule 1 (x64_cvtsd2ss x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vcvtsd2ss) x y))

;; Helper for creating `cvtdq2ps` instructions.
(decl x64_cvtdq2ps (XmmMem) Xmm)
(rule (x64_cvtdq2ps x) (xmm_unary_rm_r (SseOpcode.Cvtdq2ps) x))
(rule 1 (x64_cvtdq2ps x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vcvtdq2ps) x))

;; Helper for creating `cvtps2pd` instructions.
(decl x64_cvtps2pd (XmmMem) Xmm)
(rule (x64_cvtps2pd x) (xmm_unary_rm_r (SseOpcode.Cvtps2pd) x))
(rule 1 (x64_cvtps2pd x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vcvtps2pd) x))

;; Helper for creating `cvtpd2ps` instructions.
(decl x64_cvtpd2ps (XmmMem) Xmm)
(rule (x64_cvtpd2ps x) (xmm_unary_rm_r (SseOpcode.Cvtpd2ps) x))
(rule 1 (x64_cvtpd2ps x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vcvtpd2ps) x))

;; Helper for creating `cvtdq2pd` instructions.
(decl x64_cvtdq2pd (XmmMem) Xmm)
(rule (x64_cvtdq2pd x) (xmm_unary_rm_r (SseOpcode.Cvtdq2pd) x))
(rule 1 (x64_cvtdq2pd x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vcvtdq2pd) x))

;; Helper for creating `cvtsi2ss` instructions.
(decl x64_cvtsi2ss (Type Xmm GprMem) Xmm)
(rule (x64_cvtsi2ss ty x y)
      (cvt_int_to_float (SseOpcode.Cvtsi2ss) x y (raw_operand_size_of_type ty)))
(rule 1 (x64_cvtsi2ss ty x y)
        (if-let $true (use_avx))
        (cvt_int_to_float_vex (AvxOpcode.Vcvtsi2ss) x y (raw_operand_size_of_type ty)))

;; Helper for creating `cvtsi2sd` instructions.
(decl x64_cvtsi2sd (Type Xmm GprMem) Xmm)
(rule (x64_cvtsi2sd ty x y)
      (cvt_int_to_float (SseOpcode.Cvtsi2sd) x y (raw_operand_size_of_type ty)))
(rule 1 (x64_cvtsi2sd ty x y)
        (if-let $true (use_avx))
        (cvt_int_to_float_vex (AvxOpcode.Vcvtsi2sd) x y (raw_operand_size_of_type ty)))

;; Helper for creating `cvttps2dq` instructions.
(decl x64_cvttps2dq (XmmMem) Xmm)
(rule (x64_cvttps2dq x)
      (xmm_unary_rm_r (SseOpcode.Cvttps2dq) x))
(rule 1 (x64_cvttps2dq x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vcvttps2dq) x))

;; Helper for creating `cvttpd2dq` instructions.
(decl x64_cvttpd2dq (XmmMem) Xmm)
(rule (x64_cvttpd2dq x)
      (xmm_unary_rm_r (SseOpcode.Cvttpd2dq) x))
(rule 1 (x64_cvttpd2dq x)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vcvttpd2dq) x))

;; Helpers for creating `pcmpeq*` instructions.
(decl x64_pcmpeq (Type Xmm XmmMem) Xmm)
(rule (x64_pcmpeq $I8X16 x y) (x64_pcmpeqb x y))
(rule (x64_pcmpeq $I16X8 x y) (x64_pcmpeqw x y))
(rule (x64_pcmpeq $I32X4 x y) (x64_pcmpeqd x y))
(rule (x64_pcmpeq $I64X2 x y)
      (if-let $true (use_sse41))
      (x64_pcmpeqq x y))

;; Without SSE 4.1 there's no access to `pcmpeqq`, so it's emulated by comparing
;; 32-bit lanes instead. The upper and lower halves of the 32-bit comparison are
;; swapped and then these two results are and'd together. This way only if both
;; 32-bit values were equal is the result all ones, otherwise the result is
;; all zeros if either 32-bit comparison was zero.
(rule -1 (x64_pcmpeq $I64X2 x y)
         (let ((cmp32         Xmm (x64_pcmpeqd x y))
               (cmp32_swapped Xmm (x64_pshufd cmp32 0b10_11_00_01)))
            (x64_pand cmp32 cmp32_swapped)))

(decl x64_pcmpeqb (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpeqb x y) (xmm_rm_r (SseOpcode.Pcmpeqb) x y))
(rule 1 (x64_pcmpeqb x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpeqb) x y))
(decl x64_pcmpeqw (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpeqw x y) (xmm_rm_r (SseOpcode.Pcmpeqw) x y))
(rule 1 (x64_pcmpeqw x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpeqw) x y))
(decl x64_pcmpeqd (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpeqd x y) (xmm_rm_r (SseOpcode.Pcmpeqd) x y))
(rule 1 (x64_pcmpeqd x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpeqd) x y))
(decl x64_pcmpeqq (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpeqq x y) (xmm_rm_r (SseOpcode.Pcmpeqq) x y))
(rule 1 (x64_pcmpeqq x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpeqq) x y))

;; Helpers for creating `pcmpgt*` instructions.
(decl x64_pcmpgt (Type Xmm XmmMem) Xmm)
(rule (x64_pcmpgt $I8X16 x y) (x64_pcmpgtb x y))
(rule (x64_pcmpgt $I16X8 x y) (x64_pcmpgtw x y))
(rule (x64_pcmpgt $I32X4 x y) (x64_pcmpgtd x y))

;; SSE4.2 gives a single-instruction for this lowering, but prior to that it's a
;; bit more complicated.
(rule 1 (x64_pcmpgt $I64X2 x y)
        (if-let $true (use_sse42))
        (x64_pcmpgtq x y))

;; Without SSE4.2 a 64-bit comparison is expanded to a number of instructions.
;; The basic idea is to delegate to a 32-bit comparison and work with the
;; results from there. The comparison to execute is:
;;
;;    [ xhi ][ xlo ] > [ yhi ][ ylo ]
;;
;; If xhi != yhi, then the result is whatever the result of that comparison is.
;; If xhi == yhi, then the result is the unsigned comparison of xlo/ylo since
;; the 64-bit value is positive. To achieve this as part of the same comparison
;; the upper bit of `xlo` and `ylo` is flipped to change the sign when compared
;; as a 32-bit signed number. The result here is then:
;;
;; * if xlo and yhi had the same upper bit, then the unsigned comparison should
;;   be the same as comparing the flipped versions as signed.
;; * if xlo had an upper bit of 0 and ylo had an upper bit of 1, then xlo > ylo
;;   is false. When flipping the bits xlo becomes negative and ylo becomes
;;   positive when compared as 32-bits, so the result is the same.
;; * if xlo had an upper bit of 1 and ylo had an upper bit of 0, then xlo > ylo
;;   is true. When flipping the bits xlo becomes positive and ylo becomes
;;   negative when compared as 32-bits, so the result is the same.
;;
;; Given all that the sequence here is to flip the upper bits of xlo and ylo,
;; then compare the masked results for equality and for gt. If the upper 32-bits
;; are not equal then the gt result for the upper bits is used. If the upper
;; 32-bits are equal then the lower 32-bits comparison is used instead.
(rule 0 (x64_pcmpgt $I64X2 x y)
        (let (
            (mask Xmm (x64_movdqu_load (emit_u128_le_const 0x00000000_80000000_00000000_80000000)))
            (x_masked           Xmm (x64_pxor mask x))
            (y_masked           Xmm (x64_pxor mask y))
            (cmp32              Xmm (x64_pcmpgtd x_masked y_masked))
            (low_halves_gt      Xmm (x64_pshufd cmp32 0xa0))
            (high_halves_gt     Xmm (x64_pshufd cmp32 0xf5))
            (cmp_eq             Xmm (x64_pcmpeqd x_masked y_masked))
            (high_halves_eq     Xmm (x64_pshufd cmp_eq 0xf5))
            (low_gt_and_high_eq Xmm (x64_pand low_halves_gt high_halves_eq))
          )
          (x64_por low_gt_and_high_eq high_halves_gt)))

(decl x64_pcmpgtb (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpgtb x y) (xmm_rm_r (SseOpcode.Pcmpgtb) x y))
(rule 1 (x64_pcmpgtb x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpgtb) x y))
(decl x64_pcmpgtw (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpgtw x y) (xmm_rm_r (SseOpcode.Pcmpgtw) x y))
(rule 1 (x64_pcmpgtw x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpgtw) x y))
(decl x64_pcmpgtd (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpgtd x y) (xmm_rm_r (SseOpcode.Pcmpgtd) x y))
(rule 1 (x64_pcmpgtd x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpgtd) x y))
(decl x64_pcmpgtq (Xmm XmmMem) Xmm)
(rule 0 (x64_pcmpgtq x y) (xmm_rm_r (SseOpcode.Pcmpgtq) x y))
(rule 1 (x64_pcmpgtq x y)
        (if-let $true (use_avx))
        (xmm_rmir_vex (AvxOpcode.Vpcmpgtq) x y))

;; Helpers for read-modify-write ALU form (AluRM).
(decl alu_rm (Type AluRmiROpcode Amode Gpr) SideEffectNoResult)
(rule (alu_rm ty opcode src1_dst src2)
      (let ((size OperandSize (operand_size_of_type_32_64 ty)))
        (SideEffectNoResult.Inst (MInst.AluRM size opcode src1_dst src2))))

(decl x64_add_mem (Type Amode Gpr) SideEffectNoResult)
(rule (x64_add_mem ty addr val)
      (alu_rm ty (AluRmiROpcode.Add) addr val))

(decl x64_sub_mem (Type Amode Gpr) SideEffectNoResult)
(rule (x64_sub_mem ty addr val)
      (alu_rm ty (AluRmiROpcode.Sub) addr val))

(decl x64_and_mem (Type Amode Gpr) SideEffectNoResult)
(rule (x64_and_mem ty addr val)
      (alu_rm ty (AluRmiROpcode.And) addr val))

(decl x64_or_mem (Type Amode Gpr) SideEffectNoResult)
(rule (x64_or_mem ty addr val)
      (alu_rm ty (AluRmiROpcode.Or) addr val))

(decl x64_xor_mem (Type Amode Gpr) SideEffectNoResult)
(rule (x64_xor_mem ty addr val)
      (alu_rm ty (AluRmiROpcode.Xor) addr val))

;; Trap if the condition code supplied is set.
(decl trap_if (CC TrapCode) ConsumesFlags)
(rule (trap_if cc tc)
      (ConsumesFlags.ConsumesFlagsSideEffect (MInst.TrapIf cc tc)))

;; Trap if both of the condition codes supplied are set.
(decl trap_if_and (CC CC TrapCode) ConsumesFlags)
(rule (trap_if_and cc1 cc2 tc)
      (ConsumesFlags.ConsumesFlagsSideEffect (MInst.TrapIfAnd cc1 cc2 tc)))

;; Trap if either of the condition codes supplied are set.
(decl trap_if_or (CC CC TrapCode) ConsumesFlags)
(rule (trap_if_or cc1 cc2 tc)
      (ConsumesFlags.ConsumesFlagsSideEffect (MInst.TrapIfOr cc1 cc2 tc)))

(decl trap_if_icmp (IcmpCondResult TrapCode) SideEffectNoResult)
(rule (trap_if_icmp (IcmpCondResult.Condition producer cc) tc)
      (with_flags_side_effect producer (trap_if cc tc)))

(decl trap_if_fcmp (FcmpCondResult TrapCode) SideEffectNoResult)
(rule (trap_if_fcmp (FcmpCondResult.Condition producer cc) tc)
      (with_flags_side_effect producer (trap_if cc tc)))
(rule (trap_if_fcmp (FcmpCondResult.AndCondition producer cc1 cc2) tc)
      (with_flags_side_effect producer (trap_if_and cc1 cc2 tc)))
(rule (trap_if_fcmp (FcmpCondResult.OrCondition producer cc1 cc2) tc)
      (with_flags_side_effect producer (trap_if_or cc1 cc2 tc)))

;; Helper for creating `movddup` instructions
(decl x64_movddup (XmmMem) Xmm)
(rule (x64_movddup src)
      (xmm_unary_rm_r_unaligned (SseOpcode.Movddup) src))
(rule 1 (x64_movddup src)
        (if-let $true (use_avx))
        (xmm_unary_rm_r_vex (AvxOpcode.Vmovddup) src))

;; Helper for creating `vpbroadcastb` instructions
(decl x64_vpbroadcastb (XmmMem) Xmm)
(rule (x64_vpbroadcastb src)
      (xmm_unary_rm_r_vex (AvxOpcode.Vpbroadcastb) src))

;; Helper for creating `vpbroadcastw` instructions
(decl x64_vpbroadcastw (XmmMem) Xmm)
(rule (x64_vpbroadcastw src)
      (xmm_unary_rm_r_vex (AvxOpcode.Vpbroadcastw) src))

;; Helper for creating `vpbroadcastd` instructions
(decl x64_vpbroadcastd (XmmMem) Xmm)
(rule (x64_vpbroadcastd src)
      (xmm_unary_rm_r_vex (AvxOpcode.Vpbroadcastd) src))

;; Helper for creating `vbroadcastss` instructions
(decl x64_vbroadcastss (XmmMem) Xmm)
(rule (x64_vbroadcastss src)
      (xmm_unary_rm_r_vex (AvxOpcode.Vbroadcastss) src))

;;;; Jumps ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Unconditional jump.
(decl jmp_known (MachLabel) SideEffectNoResult)
(rule (jmp_known target)
      (SideEffectNoResult.Inst (MInst.JmpKnown target)))

(decl jmp_if (CC MachLabel) ConsumesFlags)
(rule (jmp_if cc taken)
      (ConsumesFlags.ConsumesFlagsSideEffect (MInst.JmpIf cc taken)))

;; Conditional jump based on the condition code.
(decl jmp_cond (CC MachLabel MachLabel) ConsumesFlags)
(rule (jmp_cond cc taken not_taken)
      (ConsumesFlags.ConsumesFlagsSideEffect (MInst.JmpCond cc taken not_taken)))

;; Conditional jump based on the result of an icmp.
(decl jmp_cond_icmp (IcmpCondResult MachLabel MachLabel) SideEffectNoResult)
(rule (jmp_cond_icmp (IcmpCondResult.Condition producer cc) taken not_taken)
      (with_flags_side_effect producer (jmp_cond cc taken not_taken)))

;; Conditional jump based on the result of an fcmp.
(decl jmp_cond_fcmp (FcmpCondResult MachLabel MachLabel) SideEffectNoResult)
(rule (jmp_cond_fcmp (FcmpCondResult.Condition producer cc) taken not_taken)
      (with_flags_side_effect producer (jmp_cond cc taken not_taken)))
(rule (jmp_cond_fcmp (FcmpCondResult.AndCondition producer cc1 cc2) taken not_taken)
      (with_flags_side_effect producer
                              (consumes_flags_concat
                                (jmp_if (cc_invert cc1) not_taken)
                                (jmp_cond (cc_invert cc2) not_taken taken))))
(rule (jmp_cond_fcmp (FcmpCondResult.OrCondition producer cc1 cc2) taken not_taken)
      (with_flags_side_effect producer
                              (consumes_flags_concat
                                (jmp_if cc1 taken)
                                (jmp_cond cc2 taken not_taken))))

;; Emit the compound instruction that does:
;;
;; lea $jt, %rA
;; movsbl [%rA, %rIndex, 2], %rB
;; add %rB, %rA
;; j *%rA
;; [jt entries]
;;
;; This must be *one* instruction in the vcode because we cannot allow regalloc
;; to insert any spills/fills in the middle of the sequence; otherwise, the
;; lea PC-rel offset to the jumptable would be incorrect.  (The alternative
;; is to introduce a relocation pass for inlined jumptables, which is much
;; worse.)
(decl jmp_table_seq (Type Gpr MachLabel BoxVecMachLabel) SideEffectNoResult)
(rule (jmp_table_seq ty idx default_target jt_targets)
      (let (;; This temporary is used as a signed integer of 64-bits (to hold
            ;; addresses).
            (tmp1 WritableGpr (temp_writable_gpr))

            ;; This temporary is used as a signed integer of 32-bits (for the
            ;; wasm-table index) and then 64-bits (address addend). The small
            ;; lie about the I64 type is benign, since the temporary is dead
            ;; after this instruction (and its Cranelift type is thus unused).
            (tmp2 WritableGpr (temp_writable_gpr)))

          (SideEffectNoResult.Inst
            (MInst.JmpTableSeq idx tmp1 tmp2 default_target jt_targets))))

;;;; Comparisons ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(type IcmpCondResult (enum (Condition (producer ProducesFlags) (cc CC))))

(decl icmp_cond_result (ProducesFlags CC) IcmpCondResult)
(rule (icmp_cond_result producer cc) (IcmpCondResult.Condition producer cc))

(decl invert_icmp_cond_result (IcmpCondResult) IcmpCondResult)
(rule (invert_icmp_cond_result (IcmpCondResult.Condition producer cc))
      (icmp_cond_result producer (cc_invert cc)))

;; Lower an Icmp result into a boolean value in a register.
(decl lower_icmp_bool (IcmpCondResult) ValueRegs)
(rule (lower_icmp_bool (IcmpCondResult.Condition producer cc))
      (with_flags producer (x64_setcc cc)))

;; Emit a conditional move based on the result of an icmp.
(decl select_icmp (IcmpCondResult Value Value) ValueRegs)

;; Ensure that we put the `x` argument into a register for single-register
;; gpr-typed arguments, as we rely on this for the legalization of heap_addr and
;; loading easily computed constants (like 0) from memory is too expensive.
(rule 1 (select_icmp (IcmpCondResult.Condition producer cc) x @ (value_type (is_single_register_gpr_type ty)) y)
      (with_flags producer (cmove ty cc (put_in_gpr x) y)))

;; Otherwise, fall back on the behavior of `cmove_from_values`.
(rule 0 (select_icmp (IcmpCondResult.Condition producer cc) x @ (value_type ty) y)
      (with_flags producer (cmove_from_values ty cc x y)))

(decl emit_cmp (IntCC Value Value) IcmpCondResult)

;; For GPR-held values we only need to emit `CMP + SETCC`. We rely here on
;; Cranelift's verification that `a` and `b` are of the same type.
(rule 0 (emit_cmp cc a @ (value_type ty) b)
      (let ((size OperandSize (raw_operand_size_of_type ty)))
        (icmp_cond_result (x64_cmp size a b) cc)))

;; As a special case, swap the arguments to the comparison when the LHS is a
;; constant. This ensures that we avoid moving the constant into a register when
;; performing the comparison.
(rule 1 (emit_cmp cc (and (simm32_from_value a) (value_type ty)) b)
      (let ((size OperandSize (raw_operand_size_of_type ty)))
        (icmp_cond_result (x64_cmp size b a) (intcc_swap_args cc))))

;; Special case: use the test instruction for comparisons with 0.
(rule 2 (emit_cmp cc a @ (value_type ty) (u64_from_iconst 0))
      (let ((size OperandSize (raw_operand_size_of_type ty))
            (a Gpr (put_in_reg a)))
        (icmp_cond_result (x64_test size a a) cc)))

(rule 3 (emit_cmp cc (u64_from_iconst 0) b @ (value_type ty))
      (let ((size OperandSize (raw_operand_size_of_type ty))
            (b Gpr (put_in_reg b)))
        (icmp_cond_result (x64_test size b b) (intcc_swap_args cc))))

;; For I128 values (held in two GPRs), the instruction sequences depend on what
;; kind of condition is tested.
(rule 4 (emit_cmp cc a @ (value_type $I128) b)
      (let ((a_lo Gpr (value_regs_get_gpr a 0))
            (a_hi Gpr (value_regs_get_gpr a 1))
            (b_lo Gpr (value_regs_get_gpr b 0))
            (b_hi Gpr (value_regs_get_gpr b 1)))
      (emit_cmp_i128 cc a_hi a_lo b_hi b_lo)))

(decl emit_cmp_i128 (CC Gpr Gpr Gpr Gpr) IcmpCondResult)
;; Eliminate cases which compare something "or equal" by swapping arguments.
(rule 2 (emit_cmp_i128 (CC.NLE) a_hi a_lo b_hi b_lo)
        (emit_cmp_i128 (CC.L)   b_hi b_lo a_hi a_lo))
(rule 2 (emit_cmp_i128 (CC.LE)  a_hi a_lo b_hi b_lo)
        (emit_cmp_i128 (CC.NL)  b_hi b_lo a_hi a_lo))
(rule 2 (emit_cmp_i128 (CC.NBE) a_hi a_lo b_hi b_lo)
        (emit_cmp_i128 (CC.B)   b_hi b_lo a_hi a_lo))
(rule 2 (emit_cmp_i128 (CC.BE)  a_hi a_lo b_hi b_lo)
        (emit_cmp_i128 (CC.NB)  b_hi b_lo a_hi a_lo))

;; 128-bit strict equality/inequality can't be easily tested using subtraction
;; but we can quickly determine whether any bits are different instead.
(rule 1 (emit_cmp_i128 (cc_nz_or_z cc) a_hi a_lo b_hi b_lo)
        (let ((same_lo Reg (x64_xor $I64 a_lo b_lo))
              (same_hi Reg (x64_xor $I64 a_hi b_hi)))
          (icmp_cond_result
            (x64_alurmi_flags_side_effect (AluRmiROpcode.Or) $I64 same_lo same_hi)
            cc)))

;; The only cases left are L/NL/B/NB which we can implement with a sub/sbb
;; sequence. But since we don't care about anything but the flags we can
;; replace the sub with cmp, which avoids clobbering one of the registers.
(rule 0 (emit_cmp_i128 cc a_hi a_lo b_hi b_lo)
        (icmp_cond_result
          (produces_flags_concat
            (x64_cmp (OperandSize.Size64) a_lo b_lo)
            (x64_alurmi_flags_side_effect (AluRmiROpcode.Sbb) $I64 a_hi b_hi))
          cc))

(type FcmpCondResult
      (enum
        ;; The given condition code must be set.
        (Condition (producer ProducesFlags) (cc CC))

        ;; Both condition codes must be set.
        (AndCondition (producer ProducesFlags) (cc1 CC) (cc2 CC))

        ;; Either of the conditions codes must be set.
        (OrCondition (producer ProducesFlags) (cc1 CC) (cc2 CC))))

;; Lower a FcmpCondResult to a boolean value in a register.
(decl lower_fcmp_bool (FcmpCondResult) ValueRegs)

(rule (lower_fcmp_bool (FcmpCondResult.Condition producer cc))
      (with_flags producer (x64_setcc cc)))

(rule (lower_fcmp_bool (FcmpCondResult.AndCondition producer cc1 cc2))
      (let ((maybe ValueRegs (with_flags producer
                                         (consumes_flags_concat
                                           (x64_setcc cc1)
                                           (x64_setcc cc2))))
            (maybe0 Gpr (value_regs_get_gpr maybe 0))
            (maybe1 Gpr (value_regs_get_gpr maybe 1)))
        (value_reg (x64_and $I8 maybe0 maybe1))))

(rule (lower_fcmp_bool (FcmpCondResult.OrCondition producer cc1 cc2))
      (let ((maybe ValueRegs (with_flags producer
                                         (consumes_flags_concat
                                           (x64_setcc cc1)
                                           (x64_setcc cc2))))
            (maybe0 Gpr (value_regs_get_gpr maybe 0))
            (maybe1 Gpr (value_regs_get_gpr maybe 1)))
        (value_reg (x64_or $I8 maybe0 maybe1))))

;; CLIF's `fcmp` instruction always operates on XMM registers--both scalar and
;; vector. For the scalar versions, we use the flag-setting behavior of the
;; `UCOMIS*` instruction to `SETcc` a 0 or 1 in a GPR register. Note that CLIF's
;; `select` uses the same kind of flag-setting behavior but chooses values other
;; than 0 or 1.
;;
;; Checking the result of `UCOMIS*` is unfortunately difficult in some cases
;; because we do not have `SETcc` instructions that explicitly check
;; simultaneously for the condition (i.e., `eq`, `le`, `gt`, etc.) *and*
;; orderedness. Instead, we must check the flags multiple times. The UCOMIS*
;; documentation (see Intel's Software Developer's Manual, volume 2, chapter 4)
;; is helpful:
;;  - unordered assigns    Z = 1, P = 1, C = 1
;;  - greater than assigns Z = 0, P = 0, C = 0
;;  - less than assigns    Z = 0, P = 0, C = 1
;;  - equal assigns        Z = 1, P = 0, C = 0
(decl emit_fcmp (FloatCC Value Value) FcmpCondResult)

(rule (emit_fcmp (FloatCC.Equal) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.AndCondition (x64_ucomis ty a b) (CC.NP) (CC.Z)))

(rule (emit_fcmp (FloatCC.NotEqual) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.OrCondition (x64_ucomis ty a b) (CC.P) (CC.NZ)))

;; Some scalar lowerings correspond to one condition code.

(rule (emit_fcmp (FloatCC.Ordered) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.NP)))
(rule (emit_fcmp (FloatCC.Unordered) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.P)))
(rule (emit_fcmp (FloatCC.OrderedNotEqual) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.NZ)))
(rule (emit_fcmp (FloatCC.UnorderedOrEqual) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.Z)))
(rule (emit_fcmp (FloatCC.GreaterThan) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.NBE)))
(rule (emit_fcmp (FloatCC.GreaterThanOrEqual) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.NB)))
(rule (emit_fcmp (FloatCC.UnorderedOrLessThan) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.B)))
(rule (emit_fcmp (FloatCC.UnorderedOrLessThanOrEqual) a @ (value_type (ty_scalar_float ty)) b)
      (FcmpCondResult.Condition (x64_ucomis ty a b) (CC.BE)))

;; Other scalar lowerings are made possible by flipping the operands and
;; reversing the condition code.

(rule (emit_fcmp (FloatCC.LessThan) a @ (value_type (ty_scalar_float ty)) b)
      ;; Same flags as `GreaterThan`.
      (FcmpCondResult.Condition (x64_ucomis ty b a) (CC.NBE)))
(rule (emit_fcmp (FloatCC.LessThanOrEqual) a @ (value_type (ty_scalar_float ty)) b)
      ;; Same flags as `GreaterThanOrEqual`.
      (FcmpCondResult.Condition (x64_ucomis ty b a) (CC.NB)))
(rule (emit_fcmp (FloatCC.UnorderedOrGreaterThan) a @ (value_type (ty_scalar_float ty)) b)
      ;; Same flags as `UnorderedOrLessThan`.
      (FcmpCondResult.Condition (x64_ucomis ty b a) (CC.B)))
(rule (emit_fcmp (FloatCC.UnorderedOrGreaterThanOrEqual) a @ (value_type (ty_scalar_float ty)) b)
      ;; Same flags as `UnorderedOrLessThanOrEqual`.
      (FcmpCondResult.Condition (x64_ucomis ty b a) (CC.BE)))

;;;; Type Guards ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; A type guard for matching ints and bools up to 64 bits, or 64 bit references.
(decl ty_int_bool_or_ref () Type)
(extern extractor ty_int_bool_or_ref ty_int_bool_or_ref)

;;;; Atomics ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(decl x64_mfence () SideEffectNoResult)
(rule (x64_mfence)
      (SideEffectNoResult.Inst (MInst.Fence (FenceKind.MFence))))

(decl x64_cmpxchg (Type Gpr Gpr SyntheticAmode) Gpr)
(rule (x64_cmpxchg ty expected replacement addr)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.LockCmpxchg ty replacement expected addr dst))))
        dst))

(decl x64_atomic_rmw_seq (Type MachAtomicRmwOp SyntheticAmode Gpr) Gpr)
(rule (x64_atomic_rmw_seq ty op mem input)
      (let ((dst WritableGpr (temp_writable_gpr))
            (tmp WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.AtomicRmwSeq ty op mem input tmp dst))))
        dst))

;; CLIF IR has one enumeration for atomic operations (`AtomicRmwOp`) while the
;; mach backend has another (`MachAtomicRmwOp`)--this converts one to the other.
(type MachAtomicRmwOp extern (enum))
(decl atomic_rmw_op_to_mach_atomic_rmw_op (AtomicRmwOp) MachAtomicRmwOp)
(extern constructor atomic_rmw_op_to_mach_atomic_rmw_op atomic_rmw_op_to_mach_atomic_rmw_op)

;;;; Casting ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(decl bitcast_xmm_to_gpr (u8 Xmm) Gpr)
(rule (bitcast_xmm_to_gpr 16 src)
      (x64_pextrw src 0))
(rule (bitcast_xmm_to_gpr 32 src)
      (x64_movd_to_gpr src))
(rule (bitcast_xmm_to_gpr 64 src)
      (x64_movq_to_gpr src))

(decl bitcast_xmm_to_gprs (Xmm) ValueRegs)
(rule (bitcast_xmm_to_gprs src)
      (value_regs (x64_movq_to_gpr src) (x64_movq_to_gpr (x64_pshufd src 0b11101110))))

(decl bitcast_gpr_to_xmm (u8 Gpr) Xmm)
(rule (bitcast_gpr_to_xmm 16 src)
      (x64_pinsrw (xmm_uninit_value) src 0))
(rule (bitcast_gpr_to_xmm 32 src)
      (x64_movd_to_xmm src))
(rule (bitcast_gpr_to_xmm 64 src)
      (x64_movq_to_xmm src))

(decl bitcast_gprs_to_xmm (ValueRegs) Xmm)
(rule (bitcast_gprs_to_xmm src)
      (x64_punpcklqdq (x64_movq_to_xmm (value_regs_get_gpr src 0)) (x64_movq_to_xmm (value_regs_get_gpr src 1))))

;;;; Stack Addresses ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(decl stack_addr_impl (StackSlot Offset32) Gpr)
(rule (stack_addr_impl stack_slot offset)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (abi_stackslot_addr dst stack_slot offset))))
        dst))

;;;; Division/Remainders ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Helper for creating `CheckedSRemSeq` instructions.
(decl x64_checked_srem_seq (OperandSize Gpr Gpr Gpr) ValueRegs)
(rule (x64_checked_srem_seq size dividend_lo dividend_hi divisor)
      (let ((dst_quotient WritableGpr (temp_writable_gpr))
            (dst_remainder WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.CheckedSRemSeq size dividend_lo dividend_hi divisor dst_quotient dst_remainder))))
        (value_regs dst_quotient dst_remainder)))

(decl x64_checked_srem_seq8 (Gpr Gpr) Gpr)
(rule (x64_checked_srem_seq8 dividend divisor)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.CheckedSRemSeq8 dividend divisor dst))))
        dst))

;; Helper for creating `Div8` instructions
(decl x64_div8 (Gpr GprMem DivSignedness TrapCode) Gpr)
(rule (x64_div8 dividend divisor sign trap)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.Div8 sign trap divisor dividend dst))))
        dst))

;; Helper for creating `Div` instructions
;;
;; Two registers are returned through `ValueRegs` where the first is the
;; quotient and the second is the remainder.
(decl x64_div (Gpr Gpr GprMem OperandSize DivSignedness TrapCode) ValueRegs)
(rule (x64_div dividend_lo dividend_hi divisor size sign trap)
      (let ((dst_quotient WritableGpr (temp_writable_gpr))
            (dst_remainder WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.Div size sign trap divisor dividend_lo dividend_hi dst_quotient dst_remainder))))
        (value_regs dst_quotient dst_remainder)))

;; Helper for `Div`, returning the quotient and discarding the remainder.
(decl x64_div_quotient (Gpr Gpr GprMem OperandSize DivSignedness TrapCode) ValueRegs)
(rule (x64_div_quotient dividend_lo dividend_hi divisor size sign trap)
      (value_regs_get (x64_div dividend_lo dividend_hi divisor size sign trap) 0))

;; Helper for `Div`, returning the remainder and discarding the quotient.
(decl x64_div_remainder (Gpr Gpr GprMem OperandSize DivSignedness TrapCode) ValueRegs)
(rule (x64_div_remainder dividend_lo dividend_hi divisor size sign trap)
      (value_regs_get (x64_div dividend_lo dividend_hi divisor size sign trap) 1))

;; Helper for creating `SignExtendData` instructions
(decl x64_sign_extend_data (Gpr OperandSize) Gpr)
(rule (x64_sign_extend_data src size)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.SignExtendData size src dst))))
        dst))

;;;; Pinned Register ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(decl read_pinned_gpr () Gpr)
(rule (read_pinned_gpr)
      (mov_from_preg (preg_pinned)))

(decl write_pinned_gpr (Gpr) SideEffectNoResult)
(rule (write_pinned_gpr val)
      (mov_to_preg (preg_pinned) val))

;;;; Shuffle ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Produce a mask suitable for use with `pshufb` for permuting the argument to
;; shuffle, when the arguments are the same (i.e. `shuffle a a mask`). This will
;; map all indices in the range 0..31 to the range 0..15.
(decl shuffle_0_31_mask (VecMask) VCodeConstant)
(extern constructor shuffle_0_31_mask shuffle_0_31_mask)

;; Produce a mask suitable for use with `pshufb` for permuting the lhs of a
;; `shuffle` operation (lanes 0-15).
(decl shuffle_0_15_mask (VecMask) VCodeConstant)
(extern constructor shuffle_0_15_mask shuffle_0_15_mask)

;; Produce a mask suitable for use with `pshufb` for permuting the rhs of a
;; `shuffle` operation (lanes 16-31).
(decl shuffle_16_31_mask (VecMask) VCodeConstant)
(extern constructor shuffle_16_31_mask shuffle_16_31_mask)

;; Produce a permutation suitable for use with `vpermi2b`, for permuting two
;; I8X16 vectors simultaneously.
;;
;; NOTE: `vpermi2b` will mask the indices in each lane to 5 bits when indexing
;; into vectors, so this constructor makes no effort to handle indices that are
;; larger than 31. If you are lowering a clif opcode like `shuffle` that has
;; special behavior for out of bounds indices (emitting a `0` in the resulting
;; vector in the case of `shuffle`) you'll need to handle that behavior
;; separately.
(decl perm_from_mask (VecMask) VCodeConstant)
(extern constructor perm_from_mask perm_from_mask)

;; If the mask that would be given to `shuffle` contains any out-of-bounds
;; indices, return a mask that will zero those.
(decl perm_from_mask_with_zeros (VCodeConstant VCodeConstant) VecMask)
(extern extractor perm_from_mask_with_zeros perm_from_mask_with_zeros)

;;;; TLS Values ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; Helper for emitting ElfTlsGetAddr.
(decl elf_tls_get_addr (ExternalName) Gpr)
(rule (elf_tls_get_addr name)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.ElfTlsGetAddr name dst))))
        dst))

;; Helper for emitting MachOTlsGetAddr.
(decl macho_tls_get_addr (ExternalName) Gpr)
(rule (macho_tls_get_addr name)
      (let ((dst WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.MachOTlsGetAddr name dst))))
        dst))

;; Helper for emitting CoffTlsGetAddr.
(decl coff_tls_get_addr (ExternalName) Gpr)
(rule (coff_tls_get_addr name)
      (let ((dst WritableGpr (temp_writable_gpr))
            (tmp WritableGpr (temp_writable_gpr))
            (_ Unit (emit (MInst.CoffTlsGetAddr name dst tmp))))
        dst))

;;;; Automatic conversions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(convert Gpr InstOutput output_gpr)
(convert Value Gpr put_in_gpr)
(convert Value GprMem put_in_gpr_mem)
(convert Value GprMemImm put_in_gpr_mem_imm)
(convert Value RegMem put_in_reg_mem)
(convert Value RegMemImm put_in_reg_mem_imm)
(convert Gpr GprMemImm gpr_to_gpr_mem_imm)
(convert Gpr GprMem gpr_to_gpr_mem)
(convert Gpr Reg gpr_to_reg)
(convert GprMem RegMem gpr_mem_to_reg_mem)
(convert Reg Gpr gpr_new)
(convert WritableGpr Gpr writable_gpr_to_gpr)
(convert RegMemImm GprMemImm gpr_mem_imm_new)
(convert RegMem GprMem reg_mem_to_gpr_mem)
(convert RegMem RegMemImm reg_mem_to_reg_mem_imm)
(convert Reg GprMem reg_to_gpr_mem)
(convert Reg GprMemImm reg_to_gpr_mem_imm)
(convert WritableGpr WritableReg writable_gpr_to_reg)
(convert WritableGpr Reg writable_gpr_to_r_reg)
(convert WritableGpr GprMem writable_gpr_to_gpr_mem)
(convert WritableGpr ValueRegs writable_gpr_to_value_regs)

(convert Xmm InstOutput output_xmm)
(convert Value Xmm put_in_xmm)
(convert Value XmmMem put_in_xmm_mem)
(convert Value XmmMemAligned put_in_xmm_mem_aligned)
(convert Value XmmMemImm put_in_xmm_mem_imm)
(convert Xmm Reg xmm_to_reg)
(convert Xmm RegMem xmm_to_reg_mem)
(convert Reg Xmm xmm_new)
(convert Reg XmmMem reg_to_xmm_mem)
(convert Reg RegMemImm reg_to_reg_mem_imm)
(convert RegMem XmmMem reg_mem_to_xmm_mem)
(convert Xmm XmmMem xmm_to_xmm_mem)
(convert Xmm XmmMemImm xmm_to_xmm_mem_imm)
(convert Xmm XmmMemAligned xmm_to_xmm_mem_aligned)
(convert XmmMem XmmMemImm xmm_mem_to_xmm_mem_imm)
(convert XmmMem RegMem xmm_mem_to_reg_mem)
(convert RegMemImm XmmMemImm xmm_mem_imm_new)
(convert WritableXmm Xmm writable_xmm_to_xmm)
(convert WritableXmm WritableReg writable_xmm_to_reg)
(convert WritableXmm Reg writable_xmm_to_r_reg)
(convert WritableXmm XmmMem writable_xmm_to_xmm_mem)
(convert WritableXmm ValueRegs writable_xmm_to_value_regs)

;; Note that these conversions will introduce a `movupd` instruction if
;; the memory location is not aligned to a 16-byte boundary. This is primarily
;; used to convert `XmmMem` inputs, which themselves were typically created
;; via the `put_in_xmm_mem` constructor, into operands of SSE instructions.
;; Most pre-AVX instructions working with 16-bytes of data (e.g. full xmm
;; registers) require 16-byte alignment.
(convert XmmMem XmmMemAligned xmm_mem_to_xmm_mem_aligned)
(convert XmmMemImm XmmMemAlignedImm xmm_mem_imm_to_xmm_mem_aligned_imm)

(convert Gpr Imm8Gpr gpr_to_imm8_gpr)
(convert Imm8Reg Imm8Gpr imm8_reg_to_imm8_gpr)

(convert Amode SyntheticAmode amode_to_synthetic_amode)
(convert Amode GprMem amode_to_gpr_mem)
(convert SyntheticAmode GprMem synthetic_amode_to_gpr_mem)
(convert Amode XmmMem amode_to_xmm_mem)
(convert SyntheticAmode XmmMem synthetic_amode_to_xmm_mem)
(convert Amode XmmMemAligned amode_to_xmm_mem_aligned)
(convert SyntheticAmode XmmMemAligned synthetic_amode_to_xmm_mem_aligned)
(convert VCodeConstant SyntheticAmode const_to_synthetic_amode)
(convert VCodeConstant XmmMem const_to_xmm_mem)
(convert VCodeConstant RegMem const_to_reg_mem)

(convert IntCC CC intcc_to_cc)
(convert AtomicRmwOp MachAtomicRmwOp atomic_rmw_op_to_mach_atomic_rmw_op)

(convert SinkableLoad RegMem sink_load_to_reg_mem)
(convert SinkableLoad GprMem sink_load_to_gpr_mem)
(convert SinkableLoad RegMemImm sink_load_to_reg_mem_imm)
(convert SinkableLoad GprMemImm sink_load_to_gpr_mem_imm)
(convert SinkableLoad XmmMem sink_load_to_xmm_mem)
(convert SinkableLoad SyntheticAmode sink_load)

(decl reg_to_xmm_mem (Reg) XmmMem)
(rule (reg_to_xmm_mem r)
      (xmm_to_xmm_mem (xmm_new r)))
(decl xmm_to_reg_mem (Reg) XmmMem)
(rule (xmm_to_reg_mem r)
      (RegMem.Reg (xmm_to_reg r)))

(decl writable_gpr_to_r_reg (WritableGpr) Reg)
(rule (writable_gpr_to_r_reg w_gpr)
      (writable_reg_to_reg (writable_gpr_to_reg w_gpr)))
(decl writable_gpr_to_gpr_mem (WritableGpr) GprMem)
(rule (writable_gpr_to_gpr_mem w_gpr)
      (gpr_to_gpr_mem w_gpr))
(decl writable_gpr_to_value_regs (WritableGpr) ValueRegs)
(rule (writable_gpr_to_value_regs w_gpr)
      (value_reg w_gpr))
(decl writable_xmm_to_r_reg (WritableXmm) Reg)
(rule (writable_xmm_to_r_reg w_xmm)
      (writable_reg_to_reg (writable_xmm_to_reg w_xmm)))
(decl writable_xmm_to_xmm_mem (WritableXmm) XmmMem)
(rule (writable_xmm_to_xmm_mem w_xmm)
      (xmm_to_xmm_mem (writable_xmm_to_xmm w_xmm)))
(decl writable_xmm_to_value_regs (WritableXmm) ValueRegs)
(rule (writable_xmm_to_value_regs w_xmm)
      (value_reg w_xmm))

(decl synthetic_amode_to_gpr_mem (SyntheticAmode) GprMem)
(decl amode_to_gpr_mem (Amode) GprMem)
(rule (amode_to_gpr_mem amode)
      (amode_to_synthetic_amode amode))
(rule (synthetic_amode_to_gpr_mem amode)
      (synthetic_amode_to_reg_mem amode))
(decl amode_to_xmm_mem (Amode) XmmMem)
(rule (amode_to_xmm_mem amode)
      (amode_to_synthetic_amode amode))
(decl synthetic_amode_to_xmm_mem (SyntheticAmode) XmmMem)
(rule (synthetic_amode_to_xmm_mem amode)
      (synthetic_amode_to_reg_mem amode))
(decl const_to_synthetic_amode (VCodeConstant) SyntheticAmode)
(extern constructor const_to_synthetic_amode const_to_synthetic_amode)
(decl const_to_xmm_mem (VCodeConstant) XmmMem)
(rule (const_to_xmm_mem c) (const_to_synthetic_amode c))
(decl const_to_reg_mem (VCodeConstant) RegMem)
(rule (const_to_reg_mem c) (RegMem.Mem (const_to_synthetic_amode c)))

(decl xmm_to_xmm_mem_aligned (Xmm) XmmMemAligned)
(rule (xmm_to_xmm_mem_aligned reg) (xmm_mem_to_xmm_mem_aligned reg))
(decl amode_to_xmm_mem_aligned (Amode) XmmMemAligned)
(rule (amode_to_xmm_mem_aligned mode) (amode_to_xmm_mem mode))
(decl synthetic_amode_to_xmm_mem_aligned (SyntheticAmode) XmmMemAligned)
(rule (synthetic_amode_to_xmm_mem_aligned mode) (synthetic_amode_to_xmm_mem mode))
(decl put_in_xmm_mem_aligned (Value) XmmMemAligned)
(rule (put_in_xmm_mem_aligned val) (put_in_xmm_mem val))

(decl mov_to_preg (PReg Gpr) SideEffectNoResult)
(rule (mov_to_preg dst src)
      (SideEffectNoResult.Inst (MInst.MovToPReg src dst)))

(decl preg_rbp () PReg)
(extern constructor preg_rbp preg_rbp)

(decl preg_rsp () PReg)
(extern constructor preg_rsp preg_rsp)

(decl preg_pinned () PReg)
(extern constructor preg_pinned preg_pinned)

(decl x64_rbp () Reg)
(rule (x64_rbp)
      (mov_from_preg (preg_rbp)))

(decl x64_rsp () Reg)
(rule (x64_rsp)
      (mov_from_preg (preg_rsp)))

;;;; Helpers for Emitting LibCalls ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(type LibCall extern
      (enum
        FmaF32
        FmaF64
        CeilF32
        CeilF64
        FloorF32
        FloorF64
        NearestF32
        NearestF64
        TruncF32
        TruncF64
        X86Pshufb))

(decl libcall_1 (LibCall Reg) Reg)
(extern constructor libcall_1 libcall_1)

(decl libcall_2 (LibCall Reg Reg) Reg)
(extern constructor libcall_2 libcall_2)

(decl libcall_3 (LibCall Reg Reg Reg) Reg)
(extern constructor libcall_3 libcall_3)