cranelift-codegen 0.130.0

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
//! S390x ISA: binary code emission.

use crate::ir::{self, LibCall, MemFlags, TrapCode};
use crate::isa::CallConv;
use crate::isa::s390x::abi::REG_SAVE_AREA_SIZE;
use crate::isa::s390x::inst::*;
use crate::isa::s390x::settings as s390x_settings;
use cranelift_control::ControlPlane;

/// Debug macro for testing that a regpair is valid: that the high register is even, and the low
/// register is one higher than the high register.
macro_rules! debug_assert_valid_regpair {
    ($hi:expr, $lo:expr) => {
        if cfg!(debug_assertions) {
            match ($hi.to_real_reg(), $lo.to_real_reg()) {
                (Some(hi), Some(lo)) => {
                    assert!(
                        hi.hw_enc() % 2 == 0,
                        "High register is not even: {}",
                        show_reg($hi)
                    );
                    assert_eq!(
                        hi.hw_enc() + 1,
                        lo.hw_enc(),
                        "Low register is not valid: {}, {}",
                        show_reg($hi),
                        show_reg($lo)
                    );
                }

                _ => {
                    panic!(
                        "Expected real registers for {} {}",
                        show_reg($hi),
                        show_reg($lo)
                    );
                }
            }
        }
    };
}

macro_rules! debug_assert_valid_fp_regpair {
    ($hi:expr, $lo:expr) => {
        if cfg!(debug_assertions) {
            match ($hi.to_real_reg(), $lo.to_real_reg()) {
                (Some(hi), Some(lo)) => {
                    assert!(
                        hi.hw_enc() & 2 == 0,
                        "High register is not valid: {}",
                        show_reg($hi)
                    );
                    assert_eq!(
                        hi.hw_enc() + 2,
                        lo.hw_enc(),
                        "Low register is not valid: {}, {}",
                        show_reg($hi),
                        show_reg($lo)
                    );
                }

                _ => {
                    panic!(
                        "Expected real registers for {} {}",
                        show_reg($hi),
                        show_reg($lo)
                    );
                }
            }
        }
    };
}

const OPCODE_BRAS: u16 = 0xa75;
const OPCODE_BCR: u16 = 0xa74;
const OPCODE_LDR: u16 = 0x28;
const OPCODE_VLR: u16 = 0xe756;

/// Type(s) of memory instructions available for mem_finalize.
pub struct MemInstType {
    /// True if 12-bit unsigned displacement is supported.
    pub have_d12: bool,
    /// True if 20-bit signed displacement is supported.
    pub have_d20: bool,
    /// True if PC-relative addressing is supported (memory access).
    pub have_pcrel: bool,
    /// True if PC-relative addressing is supported (load address).
    pub have_unaligned_pcrel: bool,
    /// True if an index register is supported.
    pub have_index: bool,
}

/// Memory addressing mode finalization: convert "special" modes (e.g.,
/// generic arbitrary stack offset) into real addressing modes, possibly by
/// emitting some helper instructions that come immediately before the use
/// of this amode.
pub fn mem_finalize(
    mem: &MemArg,
    state: &EmitState,
    mi: MemInstType,
) -> (SmallVec<[Inst; 4]>, MemArg) {
    let mut insts = SmallVec::new();

    // Resolve virtual addressing modes.
    let mem = match mem {
        &MemArg::RegOffset { off, .. }
        | &MemArg::InitialSPOffset { off }
        | &MemArg::IncomingArgOffset { off }
        | &MemArg::OutgoingArgOffset { off }
        | &MemArg::SlotOffset { off }
        | &MemArg::SpillOffset { off } => {
            let base = match mem {
                &MemArg::RegOffset { reg, .. } => reg,
                &MemArg::InitialSPOffset { .. }
                | &MemArg::IncomingArgOffset { .. }
                | &MemArg::OutgoingArgOffset { .. }
                | &MemArg::SlotOffset { .. }
                | &MemArg::SpillOffset { .. } => stack_reg(),
                _ => unreachable!(),
            };
            let adj = match mem {
                &MemArg::IncomingArgOffset { .. } => i64::from(
                    state.incoming_args_size
                        + REG_SAVE_AREA_SIZE
                        + state.frame_layout().clobber_size
                        + state.frame_layout().fixed_frame_storage_size
                        + state.frame_layout().outgoing_args_size
                        + state.nominal_sp_offset,
                ),
                &MemArg::InitialSPOffset { .. } => i64::from(
                    state.frame_layout().clobber_size
                        + state.frame_layout().fixed_frame_storage_size
                        + state.frame_layout().outgoing_args_size
                        + state.nominal_sp_offset,
                ),
                &MemArg::SpillOffset { .. } => i64::from(
                    state.frame_layout().stackslots_size
                        + state.frame_layout().outgoing_args_size
                        + state.nominal_sp_offset,
                ),
                &MemArg::SlotOffset { .. } => {
                    i64::from(state.frame_layout().outgoing_args_size + state.nominal_sp_offset)
                }
                &MemArg::OutgoingArgOffset { .. } => {
                    i64::from(REG_SAVE_AREA_SIZE) - i64::from(state.outgoing_sp_offset)
                }
                _ => 0,
            };
            let off = off + adj;

            if let Some(disp) = UImm12::maybe_from_u64(off as u64) {
                MemArg::BXD12 {
                    base,
                    index: zero_reg(),
                    disp,
                    flags: mem.get_flags(),
                }
            } else if let Some(disp) = SImm20::maybe_from_i64(off) {
                MemArg::BXD20 {
                    base,
                    index: zero_reg(),
                    disp,
                    flags: mem.get_flags(),
                }
            } else {
                let tmp = writable_spilltmp_reg();
                assert!(base != tmp.to_reg());
                if let Ok(imm) = i16::try_from(off) {
                    insts.push(Inst::Mov64SImm16 { rd: tmp, imm });
                } else if let Ok(imm) = i32::try_from(off) {
                    insts.push(Inst::Mov64SImm32 { rd: tmp, imm });
                } else {
                    // The offset must be smaller than the stack frame size,
                    // which the ABI code limits to 128 MB.
                    unreachable!();
                }
                MemArg::reg_plus_reg(base, tmp.to_reg(), mem.get_flags())
            }
        }
        _ => mem.clone(),
    };

    // If this addressing mode cannot be handled by the instruction, use load-address.
    let need_load_address = match &mem {
        &MemArg::Label { .. } | &MemArg::Constant { .. } if !mi.have_pcrel => true,
        &MemArg::Symbol { .. } if !mi.have_pcrel => true,
        &MemArg::Symbol { flags, .. } if !mi.have_unaligned_pcrel && !flags.aligned() => true,
        &MemArg::BXD20 { .. } if !mi.have_d20 => true,
        &MemArg::BXD12 { index, .. } | &MemArg::BXD20 { index, .. } if !mi.have_index => {
            index != zero_reg()
        }
        _ => false,
    };
    let mem = if need_load_address {
        let flags = mem.get_flags();
        let tmp = writable_spilltmp_reg();
        insts.push(Inst::LoadAddr { rd: tmp, mem });
        MemArg::reg(tmp.to_reg(), flags)
    } else {
        mem
    };

    // Convert 12-bit displacement to 20-bit if required.
    let mem = match &mem {
        &MemArg::BXD12 {
            base,
            index,
            disp,
            flags,
        } if !mi.have_d12 => {
            assert!(mi.have_d20);
            MemArg::BXD20 {
                base,
                index,
                disp: SImm20::from_uimm12(disp),
                flags,
            }
        }
        _ => mem,
    };

    (insts, mem)
}

pub fn mem_emit(
    rd: Reg,
    mem: &MemArg,
    opcode_rx: Option<u16>,
    opcode_rxy: Option<u16>,
    opcode_ril: Option<u16>,
    add_trap: bool,
    sink: &mut MachBuffer<Inst>,
    emit_info: &EmitInfo,
    state: &mut EmitState,
) {
    let (mem_insts, mem) = mem_finalize(
        mem,
        state,
        MemInstType {
            have_d12: opcode_rx.is_some(),
            have_d20: opcode_rxy.is_some(),
            have_pcrel: opcode_ril.is_some(),
            have_unaligned_pcrel: opcode_ril.is_some() && !add_trap,
            have_index: true,
        },
    );
    for inst in mem_insts.into_iter() {
        inst.emit(sink, emit_info, state);
    }

    if add_trap {
        if let Some(trap_code) = mem.get_flags().trap_code() {
            sink.add_trap(trap_code);
        }
    }

    match &mem {
        &MemArg::BXD12 {
            base, index, disp, ..
        } => {
            put(
                sink,
                &enc_rx(opcode_rx.unwrap(), rd, base, index, disp.bits()),
            );
        }
        &MemArg::BXD20 {
            base, index, disp, ..
        } => {
            put(
                sink,
                &enc_rxy(opcode_rxy.unwrap(), rd, base, index, disp.bits()),
            );
        }
        &MemArg::Label { target } => {
            sink.use_label_at_offset(sink.cur_offset(), target, LabelUse::BranchRIL);
            put(sink, &enc_ril_b(opcode_ril.unwrap(), rd, 0));
        }
        &MemArg::Constant { constant } => {
            let target = sink.get_label_for_constant(constant);
            sink.use_label_at_offset(sink.cur_offset(), target, LabelUse::BranchRIL);
            put(sink, &enc_ril_b(opcode_ril.unwrap(), rd, 0));
        }
        &MemArg::Symbol {
            ref name, offset, ..
        } => {
            let reloc_offset = sink.cur_offset() + 2;
            sink.add_reloc_at_offset(
                reloc_offset,
                Reloc::S390xPCRel32Dbl,
                &**name,
                (offset + 2).into(),
            );
            put(sink, &enc_ril_b(opcode_ril.unwrap(), rd, 0));
        }
        _ => unreachable!(),
    }
}

pub fn mem_rs_emit(
    rd: Reg,
    rn: Reg,
    mem: &MemArg,
    opcode_rs: Option<u16>,
    opcode_rsy: Option<u16>,
    add_trap: bool,
    sink: &mut MachBuffer<Inst>,
    emit_info: &EmitInfo,
    state: &mut EmitState,
) {
    let (mem_insts, mem) = mem_finalize(
        mem,
        state,
        MemInstType {
            have_d12: opcode_rs.is_some(),
            have_d20: opcode_rsy.is_some(),
            have_pcrel: false,
            have_unaligned_pcrel: false,
            have_index: false,
        },
    );
    for inst in mem_insts.into_iter() {
        inst.emit(sink, emit_info, state);
    }

    if add_trap {
        if let Some(trap_code) = mem.get_flags().trap_code() {
            sink.add_trap(trap_code);
        }
    }

    match &mem {
        &MemArg::BXD12 {
            base, index, disp, ..
        } => {
            assert!(index == zero_reg());
            put(sink, &enc_rs(opcode_rs.unwrap(), rd, rn, base, disp.bits()));
        }
        &MemArg::BXD20 {
            base, index, disp, ..
        } => {
            assert!(index == zero_reg());
            put(
                sink,
                &enc_rsy(opcode_rsy.unwrap(), rd, rn, base, disp.bits()),
            );
        }
        _ => unreachable!(),
    }
}

pub fn mem_imm8_emit(
    imm: u8,
    mem: &MemArg,
    opcode_si: u16,
    opcode_siy: u16,
    add_trap: bool,
    sink: &mut MachBuffer<Inst>,
    emit_info: &EmitInfo,
    state: &mut EmitState,
) {
    let (mem_insts, mem) = mem_finalize(
        mem,
        state,
        MemInstType {
            have_d12: true,
            have_d20: true,
            have_pcrel: false,
            have_unaligned_pcrel: false,
            have_index: false,
        },
    );
    for inst in mem_insts.into_iter() {
        inst.emit(sink, emit_info, state);
    }

    if add_trap {
        if let Some(trap_code) = mem.get_flags().trap_code() {
            sink.add_trap(trap_code);
        }
    }

    match &mem {
        &MemArg::BXD12 {
            base, index, disp, ..
        } => {
            assert!(index == zero_reg());
            put(sink, &enc_si(opcode_si, base, disp.bits(), imm));
        }
        &MemArg::BXD20 {
            base, index, disp, ..
        } => {
            assert!(index == zero_reg());
            put(sink, &enc_siy(opcode_siy, base, disp.bits(), imm));
        }
        _ => unreachable!(),
    }
}

pub fn mem_imm16_emit(
    imm: i16,
    mem: &MemArg,
    opcode_sil: u16,
    add_trap: bool,
    sink: &mut MachBuffer<Inst>,
    emit_info: &EmitInfo,
    state: &mut EmitState,
) {
    let (mem_insts, mem) = mem_finalize(
        mem,
        state,
        MemInstType {
            have_d12: true,
            have_d20: false,
            have_pcrel: false,
            have_unaligned_pcrel: false,
            have_index: false,
        },
    );
    for inst in mem_insts.into_iter() {
        inst.emit(sink, emit_info, state);
    }

    if add_trap {
        if let Some(trap_code) = mem.get_flags().trap_code() {
            sink.add_trap(trap_code);
        }
    }

    match &mem {
        &MemArg::BXD12 {
            base, index, disp, ..
        } => {
            assert!(index == zero_reg());
            put(sink, &enc_sil(opcode_sil, base, disp.bits(), imm));
        }
        _ => unreachable!(),
    }
}

pub fn mem_vrx_emit(
    rd: Reg,
    mem: &MemArg,
    opcode: u16,
    m3: u8,
    add_trap: bool,
    sink: &mut MachBuffer<Inst>,
    emit_info: &EmitInfo,
    state: &mut EmitState,
) {
    let (mem_insts, mem) = mem_finalize(
        mem,
        state,
        MemInstType {
            have_d12: true,
            have_d20: false,
            have_pcrel: false,
            have_unaligned_pcrel: false,
            have_index: true,
        },
    );
    for inst in mem_insts.into_iter() {
        inst.emit(sink, emit_info, state);
    }

    if add_trap {
        if let Some(trap_code) = mem.get_flags().trap_code() {
            sink.add_trap(trap_code);
        }
    }

    match &mem {
        &MemArg::BXD12 {
            base, index, disp, ..
        } => {
            put(sink, &enc_vrx(opcode, rd, base, index, disp.bits(), m3));
        }
        _ => unreachable!(),
    }
}

//=============================================================================
// Instructions and subcomponents: emission

fn machreg_to_gpr(m: Reg) -> u8 {
    assert_eq!(m.class(), RegClass::Int);
    m.to_real_reg().unwrap().hw_enc()
}

fn machreg_to_vr(m: Reg) -> u8 {
    assert_eq!(m.class(), RegClass::Float);
    m.to_real_reg().unwrap().hw_enc()
}

fn machreg_to_fpr(m: Reg) -> u8 {
    assert!(is_fpr(m));
    m.to_real_reg().unwrap().hw_enc()
}

fn machreg_to_gpr_or_fpr(m: Reg) -> u8 {
    let reg = m.to_real_reg().unwrap().hw_enc();
    assert!(reg < 16);
    reg
}

fn rxb(v1: Option<Reg>, v2: Option<Reg>, v3: Option<Reg>, v4: Option<Reg>) -> u8 {
    let mut rxb = 0;

    let is_high_vr = |reg| -> bool {
        if let Some(reg) = reg {
            if !is_fpr(reg) {
                return true;
            }
        }
        false
    };

    if is_high_vr(v1) {
        rxb = rxb | 8;
    }
    if is_high_vr(v2) {
        rxb = rxb | 4;
    }
    if is_high_vr(v3) {
        rxb = rxb | 2;
    }
    if is_high_vr(v4) {
        rxb = rxb | 1;
    }

    rxb
}

/// E-type instructions.
///
///   15
///   opcode
///        0
///
fn enc_e(opcode: u16) -> [u8; 2] {
    let mut enc: [u8; 2] = [0; 2];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;

    enc[0] = opcode1;
    enc[1] = opcode2;
    enc
}

/// RIa-type instructions.
///
///   31      23 19      15
///   opcode1 r1 opcode2 i2
///        24 20      16  0
///
fn enc_ri_a(opcode: u16, r1: Reg, i2: u16) -> [u8; 4] {
    let mut enc: [u8; 4] = [0; 4];
    let opcode1 = ((opcode >> 4) & 0xff) as u8;
    let opcode2 = (opcode & 0xf) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;

    enc[0] = opcode1;
    enc[1] = r1 << 4 | opcode2;
    enc[2..].copy_from_slice(&i2.to_be_bytes());
    enc
}

/// RIb-type instructions.
///
///   31      23 19      15
///   opcode1 r1 opcode2 ri2
///        24 20      16   0
///
fn enc_ri_b(opcode: u16, r1: Reg, ri2: i32) -> [u8; 4] {
    let mut enc: [u8; 4] = [0; 4];
    let opcode1 = ((opcode >> 4) & 0xff) as u8;
    let opcode2 = (opcode & 0xf) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;
    let ri2 = ((ri2 >> 1) & 0xffff) as u16;

    enc[0] = opcode1;
    enc[1] = r1 << 4 | opcode2;
    enc[2..].copy_from_slice(&ri2.to_be_bytes());
    enc
}

/// RIc-type instructions.
///
///   31      23 19      15
///   opcode1 m1 opcode2 ri2
///        24 20      16   0
///
fn enc_ri_c(opcode: u16, m1: u8, ri2: i32) -> [u8; 4] {
    let mut enc: [u8; 4] = [0; 4];
    let opcode1 = ((opcode >> 4) & 0xff) as u8;
    let opcode2 = (opcode & 0xf) as u8;
    let m1 = m1 & 0x0f;
    let ri2 = ((ri2 >> 1) & 0xffff) as u16;

    enc[0] = opcode1;
    enc[1] = m1 << 4 | opcode2;
    enc[2..].copy_from_slice(&ri2.to_be_bytes());
    enc
}

/// RIEa-type instructions.
///
///   47      39 35 31 15 11 7
///   opcode1 r1 -- i2 m3 -- opcode2
///        40 36 32 16 12 8       0
///
fn enc_rie_a(opcode: u16, r1: Reg, i2: u16, m3: u8) -> [u8; 6] {
    let mut enc: [u8; 6] = [0; 6];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;
    let m3 = m3 & 0x0f;

    enc[0] = opcode1;
    enc[1] = r1 << 4;
    enc[2..4].copy_from_slice(&i2.to_be_bytes());
    enc[4] = m3 << 4;
    enc[5] = opcode2;
    enc
}

/// RIEd-type instructions.
///
///   47      39 35 31 15 7
///   opcode1 r1 r3 i2 -- opcode2
///        40 36 32 16  8       0
///
fn enc_rie_d(opcode: u16, r1: Reg, r3: Reg, i2: u16) -> [u8; 6] {
    let mut enc: [u8; 6] = [0; 6];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;
    let r3 = machreg_to_gpr(r3) & 0x0f;

    enc[0] = opcode1;
    enc[1] = r1 << 4 | r3;
    enc[2..4].copy_from_slice(&i2.to_be_bytes());
    enc[5] = opcode2;
    enc
}

/// RIEf-type instructions.
///
///   47      39 35 31 23 15 7
///   opcode1 r1 r2 i3 i4 i5 opcode2
///        40 36 32 24 16  8       0
///
fn enc_rie_f(opcode: u16, r1: Reg, r2: Reg, i3: u8, i4: u8, i5: u8) -> [u8; 6] {
    let mut enc: [u8; 6] = [0; 6];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;
    let r2 = machreg_to_gpr(r2) & 0x0f;

    enc[0] = opcode1;
    enc[1] = r1 << 4 | r2;
    enc[2] = i3;
    enc[3] = i4;
    enc[4] = i5;
    enc[5] = opcode2;
    enc
}

/// RIEg-type instructions.
///
///   47      39 35 31 15 7
///   opcode1 r1 m3 i2 -- opcode2
///        40 36 32 16  8       0
///
fn enc_rie_g(opcode: u16, r1: Reg, i2: u16, m3: u8) -> [u8; 6] {
    let mut enc: [u8; 6] = [0; 6];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;
    let m3 = m3 & 0x0f;

    enc[0] = opcode1;
    enc[1] = r1 << 4 | m3;
    enc[2..4].copy_from_slice(&i2.to_be_bytes());
    enc[5] = opcode2;
    enc
}

/// RILa-type instructions.
///
///   47      39 35      31
///   opcode1 r1 opcode2 i2
///        40 36      32  0
///
fn enc_ril_a(opcode: u16, r1: Reg, i2: u32) -> [u8; 6] {
    let mut enc: [u8; 6] = [0; 6];
    let opcode1 = ((opcode >> 4) & 0xff) as u8;
    let opcode2 = (opcode & 0xf) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;

    enc[0] = opcode1;
    enc[1] = r1 << 4 | opcode2;
    enc[2..].copy_from_slice(&i2.to_be_bytes());
    enc
}

/// RILb-type instructions.
///
///   47      39 35      31
///   opcode1 r1 opcode2 ri2
///        40 36      32   0
///
fn enc_ril_b(opcode: u16, r1: Reg, ri2: u32) -> [u8; 6] {
    let mut enc: [u8; 6] = [0; 6];
    let opcode1 = ((opcode >> 4) & 0xff) as u8;
    let opcode2 = (opcode & 0xf) as u8;
    let r1 = machreg_to_gpr(r1) & 0x0f;
    let ri2 = ri2 >> 1;

    enc[0] = opcode1;
    enc[1] = r1 << 4 | opcode2;
    enc[2..].copy_from_slice(&ri2.to_be_bytes());
    enc
}

/// RILc-type instructions.
///
///   47      39 35      31
///   opcode1 m1 opcode2 i2
///        40 36      32  0
///
fn enc_ril_c(opcode: u16, m1: u8, ri2: u32) -> [u8; 6] {
    let mut enc: [u8; 6] = [0; 6];
    let opcode1 = ((opcode >> 4) & 0xff) as u8;
    let opcode2 = (opcode & 0xf) as u8;
    let m1 = m1 & 0x0f;
    let ri2 = ri2 >> 1;

    enc[0] = opcode1;
    enc[1] = m1 << 4 | opcode2;
    enc[2..].copy_from_slice(&ri2.to_be_bytes());
    enc
}

/// RR-type instructions.
///
///   15     7  3
///   opcode r1 r2
///        8  4  0
///
fn enc_rr(opcode: u16, r1: Reg, r2: Reg) -> [u8; 2] {
    let mut enc: [u8; 2] = [0; 2];
    let opcode = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let r2 = machreg_to_gpr_or_fpr(r2) & 0x0f;

    enc[0] = opcode;
    enc[1] = r1 << 4 | r2;
    enc
}

/// RRD-type instructions.
///
///   31     15 11 7  3
///   opcode r1 -- r3 r2
///       16 12  8 4  0
///
fn enc_rrd(opcode: u16, r1: Reg, r2: Reg, r3: Reg) -> [u8; 4] {
    let mut enc: [u8; 4] = [0; 4];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_fpr(r1) & 0x0f;
    let r2 = machreg_to_fpr(r2) & 0x0f;
    let r3 = machreg_to_fpr(r3) & 0x0f;

    enc[0] = opcode1;
    enc[1] = opcode2;
    enc[2] = r1 << 4;
    enc[3] = r3 << 4 | r2;
    enc
}

/// RRE-type instructions.
///
///   31     15 7  3
///   opcode -- r1 r2
///       16  8  4  0
///
fn enc_rre(opcode: u16, r1: Reg, r2: Reg) -> [u8; 4] {
    let mut enc: [u8; 4] = [0; 4];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let r2 = machreg_to_gpr_or_fpr(r2) & 0x0f;

    enc[0] = opcode1;
    enc[1] = opcode2;
    enc[3] = r1 << 4 | r2;
    enc
}

/// RRFa/b-type instructions.
///
///   31     15 11 7  3
///   opcode r3 m4 r1 r2
///       16 12  8  4  0
///
fn enc_rrf_ab(opcode: u16, r1: Reg, r2: Reg, r3: Reg, m4: u8) -> [u8; 4] {
    let mut enc: [u8; 4] = [0; 4];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let r2 = machreg_to_gpr_or_fpr(r2) & 0x0f;
    let r3 = machreg_to_gpr_or_fpr(r3) & 0x0f;
    let m4 = m4 & 0x0f;

    enc[0] = opcode1;
    enc[1] = opcode2;
    enc[2] = r3 << 4 | m4;
    enc[3] = r1 << 4 | r2;
    enc
}

/// RRFc/d/e-type instructions.
///
///   31     15 11 7  3
///   opcode m3 m4 r1 r2
///       16 12  8  4  0
///
fn enc_rrf_cde(opcode: u16, r1: Reg, r2: Reg, m3: u8, m4: u8) -> [u8; 4] {
    let mut enc: [u8; 4] = [0; 4];
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let r2 = machreg_to_gpr_or_fpr(r2) & 0x0f;
    let m3 = m3 & 0x0f;
    let m4 = m4 & 0x0f;

    enc[0] = opcode1;
    enc[1] = opcode2;
    enc[2] = m3 << 4 | m4;
    enc[3] = r1 << 4 | r2;
    enc
}

/// RS-type instructions.
///
///   31     23 19 15 11
///   opcode r1 r3 b2 d2
///       24 20 16 12  0
///
fn enc_rs(opcode: u16, r1: Reg, r3: Reg, b2: Reg, d2: u32) -> [u8; 4] {
    let opcode = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let r3 = machreg_to_gpr_or_fpr(r3) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let d2_lo = (d2 & 0xff) as u8;
    let d2_hi = ((d2 >> 8) & 0x0f) as u8;

    let mut enc: [u8; 4] = [0; 4];
    enc[0] = opcode;
    enc[1] = r1 << 4 | r3;
    enc[2] = b2 << 4 | d2_hi;
    enc[3] = d2_lo;
    enc
}

/// RSY-type instructions.
///
///   47      39 35 31 27  15  7
///   opcode1 r1 r3 b2 dl2 dh2 opcode2
///        40 36 32 28  16   8       0
///
fn enc_rsy(opcode: u16, r1: Reg, r3: Reg, b2: Reg, d2: u32) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let r3 = machreg_to_gpr_or_fpr(r3) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let dl2_lo = (d2 & 0xff) as u8;
    let dl2_hi = ((d2 >> 8) & 0x0f) as u8;
    let dh2 = ((d2 >> 12) & 0xff) as u8;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = r1 << 4 | r3;
    enc[2] = b2 << 4 | dl2_hi;
    enc[3] = dl2_lo;
    enc[4] = dh2;
    enc[5] = opcode2;
    enc
}

/// RX-type instructions.
///
///   31     23 19 15 11
///   opcode r1 x2 b2 d2
///       24 20 16 12  0
///
fn enc_rx(opcode: u16, r1: Reg, b2: Reg, x2: Reg, d2: u32) -> [u8; 4] {
    let opcode = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let x2 = machreg_to_gpr(x2) & 0x0f;
    let d2_lo = (d2 & 0xff) as u8;
    let d2_hi = ((d2 >> 8) & 0x0f) as u8;

    let mut enc: [u8; 4] = [0; 4];
    enc[0] = opcode;
    enc[1] = r1 << 4 | x2;
    enc[2] = b2 << 4 | d2_hi;
    enc[3] = d2_lo;
    enc
}

/// RXY-type instructions.
///
///   47      39 35 31 27  15  7
///   opcode1 r1 x2 b2 dl2 dh2 opcode2
///        40 36 32 28  16   8       0
///
fn enc_rxy(opcode: u16, r1: Reg, b2: Reg, x2: Reg, d2: u32) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let r1 = machreg_to_gpr_or_fpr(r1) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let x2 = machreg_to_gpr(x2) & 0x0f;
    let dl2_lo = (d2 & 0xff) as u8;
    let dl2_hi = ((d2 >> 8) & 0x0f) as u8;
    let dh2 = ((d2 >> 12) & 0xff) as u8;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = r1 << 4 | x2;
    enc[2] = b2 << 4 | dl2_hi;
    enc[3] = dl2_lo;
    enc[4] = dh2;
    enc[5] = opcode2;
    enc
}

/// SI-type instructions.
///
///   31     23 15 11
///   opcode i2 b1 d1
///       24 16 12  0
///
fn enc_si(opcode: u16, b1: Reg, d1: u32, i2: u8) -> [u8; 4] {
    let opcode = (opcode & 0xff) as u8;
    let b1 = machreg_to_gpr(b1) & 0x0f;
    let d1_lo = (d1 & 0xff) as u8;
    let d1_hi = ((d1 >> 8) & 0x0f) as u8;

    let mut enc: [u8; 4] = [0; 4];
    enc[0] = opcode;
    enc[1] = i2;
    enc[2] = b1 << 4 | d1_hi;
    enc[3] = d1_lo;
    enc
}

/// SIL-type instructions.
///
///   47     31 27 15
///   opcode b1 d1 i2
///       32 28 16  0
///
fn enc_sil(opcode: u16, b1: Reg, d1: u32, i2: i16) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let b1 = machreg_to_gpr(b1) & 0x0f;
    let d1_lo = (d1 & 0xff) as u8;
    let d1_hi = ((d1 >> 8) & 0x0f) as u8;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = opcode2;
    enc[2] = b1 << 4 | d1_hi;
    enc[3] = d1_lo;
    enc[4..].copy_from_slice(&i2.to_be_bytes());
    enc
}

/// SIY-type instructions.
///
///   47      39 31 27  15  7
///   opcode1 i2 b1 dl1 dh1 opcode2
///        40 32 28  16   8       0
///
fn enc_siy(opcode: u16, b1: Reg, d1: u32, i2: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let b1 = machreg_to_gpr(b1) & 0x0f;
    let dl1_lo = (d1 & 0xff) as u8;
    let dl1_hi = ((d1 >> 8) & 0x0f) as u8;
    let dh1 = ((d1 >> 12) & 0xff) as u8;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = i2;
    enc[2] = b1 << 4 | dl1_hi;
    enc[3] = dl1_lo;
    enc[4] = dh1;
    enc[5] = opcode2;
    enc
}

/// VRIa-type instructions.
///
///   47      39 35 31 15 11  7
///   opcode1 v1 -  i2 m3 rxb opcode2
///        40 36 32 16 12   8       0
///
fn enc_vri_a(opcode: u16, v1: Reg, i2: u16, m3: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), None, None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let m3 = m3 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4;
    enc[2..4].copy_from_slice(&i2.to_be_bytes());
    enc[4] = m3 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRIb-type instructions.
///
///   47      39 35 31 23 15 11  7
///   opcode1 v1 -  i2 i3 m4 rxb opcode2
///        40 36 32 24 16 12   8       0
///
fn enc_vri_b(opcode: u16, v1: Reg, i2: u8, i3: u8, m4: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), None, None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let m4 = m4 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4;
    enc[2] = i2;
    enc[3] = i3;
    enc[4] = m4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRIc-type instructions.
///
///   47      39 35 31 15 11  7
///   opcode1 v1 v3 i2 m4 rxb opcode2
///        40 36 32 16 12   8       0
///
fn enc_vri_c(opcode: u16, v1: Reg, i2: u16, v3: Reg, m4: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v3), None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let m4 = m4 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v3;
    enc[2..4].copy_from_slice(&i2.to_be_bytes());
    enc[4] = m4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRIk-type instructions.
///
///   47      39 35 31 27 23 15 11  7
///   opcode1 v1 v2 v3 -  i5 v4 rxb opcode2
///        40 36 32 28 24 16 12   8       0
///
fn enc_vri_k(opcode: u16, i5: u8, v1: Reg, v2: Reg, v3: Reg, v4: Reg) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v2), Some(v3), Some(v4));
    let v1 = machreg_to_vr(v1) & 0x0f;
    let v2 = machreg_to_vr(v2) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let v4 = machreg_to_vr(v4) & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v2;
    enc[2] = v3 << 4;
    enc[3] = i5;
    enc[4] = v4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRRa-type instructions.
///
///   47      39 35 31 23 19 15 11  7
///   opcode1 v1 v2 -  m5 m3 m2 rxb opcode2
///        40 36 32 24 20 16 12   8       0
///
fn enc_vrr_a(opcode: u16, v1: Reg, v2: Reg, m3: u8, m4: u8, m5: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v2), None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let v2 = machreg_to_vr(v2) & 0x0f;
    let m3 = m3 & 0x0f;
    let m4 = m4 & 0x0f;
    let m5 = m5 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v2;
    enc[2] = 0;
    enc[3] = m5 << 4 | m4;
    enc[4] = m3 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRRb-type instructions.
///
///   47      39 35 31 27 23 19 15 11  7
///   opcode1 v1 v2 v3 -  m5 -  m4 rxb opcode2
///        40 36 32 28 24 20 16 12   8       0
///
fn enc_vrr_b(opcode: u16, v1: Reg, v2: Reg, v3: Reg, m4: u8, m5: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v2), Some(v3), None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let v2 = machreg_to_vr(v2) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let m4 = m4 & 0x0f;
    let m5 = m5 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v2;
    enc[2] = v3 << 4;
    enc[3] = m5 << 4;
    enc[4] = m4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRRc-type instructions.
///
///   47      39 35 31 27 23 19 15 11  7
///   opcode1 v1 v2 v3 -  m6 m5 m4 rxb opcode2
///        40 36 32 28 24 20 16 12   8       0
///
fn enc_vrr_c(opcode: u16, v1: Reg, v2: Reg, v3: Reg, m4: u8, m5: u8, m6: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v2), Some(v3), None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let v2 = machreg_to_vr(v2) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let m4 = m4 & 0x0f;
    let m5 = m5 & 0x0f;
    let m6 = m6 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v2;
    enc[2] = v3 << 4;
    enc[3] = m6 << 4 | m5;
    enc[4] = m4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRRd-type instructions.
///
///   47      39 35 31 27 23 19 15 11  7
///   opcode1 v1 v2 v3 m5 m6 -  v4 rxb opcode2
///        40 36 32 28 24 20 16 12   8       0
///
fn enc_vrr_d(opcode: u16, v1: Reg, v2: Reg, v3: Reg, v4: Reg, m5: u8, m6: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v2), Some(v3), Some(v4));
    let v1 = machreg_to_vr(v1) & 0x0f;
    let v2 = machreg_to_vr(v2) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let v4 = machreg_to_vr(v4) & 0x0f;
    let m5 = m5 & 0x0f;
    let m6 = m6 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v2;
    enc[2] = v3 << 4 | m5;
    enc[3] = m6 << 4;
    enc[4] = v4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRRe-type instructions.
///
///   47      39 35 31 27 23 19 15 11  7
///   opcode1 v1 v2 v3 m6 -  m5 v4 rxb opcode2
///        40 36 32 28 24 20 16 12   8       0
///
fn enc_vrr_e(opcode: u16, v1: Reg, v2: Reg, v3: Reg, v4: Reg, m5: u8, m6: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v2), Some(v3), Some(v4));
    let v1 = machreg_to_vr(v1) & 0x0f;
    let v2 = machreg_to_vr(v2) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let v4 = machreg_to_vr(v4) & 0x0f;
    let m5 = m5 & 0x0f;
    let m6 = m6 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v2;
    enc[2] = v3 << 4 | m6;
    enc[3] = m5;
    enc[4] = v4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRRf-type instructions.
///
///   47      39 35 31 27 11  7
///   opcode1 v1 r2 r3 -  rxb opcode2
///        40 36 32 28 12   8       0
///
fn enc_vrr_f(opcode: u16, v1: Reg, r2: Reg, r3: Reg) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), None, None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let r2 = machreg_to_gpr(r2) & 0x0f;
    let r3 = machreg_to_gpr(r3) & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | r2;
    enc[2] = r3 << 4;
    enc[4] = rxb;
    enc[5] = opcode2;
    enc
}

/// VRSa-type instructions.
///
///   47      39 35 31 27 15 11  7
///   opcode1 v1 v3 b2 d2 m4 rxb opcode2
///        40 36 32 28 16 12   8       0
///
fn enc_vrs_a(opcode: u16, v1: Reg, b2: Reg, d2: u32, v3: Reg, m4: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), Some(v3), None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let d2_lo = (d2 & 0xff) as u8;
    let d2_hi = ((d2 >> 8) & 0x0f) as u8;
    let m4 = m4 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | v3;
    enc[2] = b2 << 4 | d2_hi;
    enc[3] = d2_lo;
    enc[4] = m4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRSb-type instructions.
///
///   47      39 35 31 27 15 11  7
///   opcode1 v1 r3 b2 d2 m4 rxb opcode2
///        40 36 32 28 16 12   8       0
///
fn enc_vrs_b(opcode: u16, v1: Reg, b2: Reg, d2: u32, r3: Reg, m4: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), None, None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let r3 = machreg_to_gpr(r3) & 0x0f;
    let d2_lo = (d2 & 0xff) as u8;
    let d2_hi = ((d2 >> 8) & 0x0f) as u8;
    let m4 = m4 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | r3;
    enc[2] = b2 << 4 | d2_hi;
    enc[3] = d2_lo;
    enc[4] = m4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRSc-type instructions.
///
///   47      39 35 31 27 15 11  7
///   opcode1 r1 v3 b2 d2 m4 rxb opcode2
///        40 36 32 28 16 12   8       0
///
fn enc_vrs_c(opcode: u16, r1: Reg, b2: Reg, d2: u32, v3: Reg, m4: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(None, Some(v3), None, None);
    let r1 = machreg_to_gpr(r1) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let v3 = machreg_to_vr(v3) & 0x0f;
    let d2_lo = (d2 & 0xff) as u8;
    let d2_hi = ((d2 >> 8) & 0x0f) as u8;
    let m4 = m4 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = r1 << 4 | v3;
    enc[2] = b2 << 4 | d2_hi;
    enc[3] = d2_lo;
    enc[4] = m4 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// VRX-type instructions.
///
///   47      39 35 31 27 15 11  7
///   opcode1 v1 x2 b2 d2 m3 rxb opcode2
///        40 36 32 28 16 12   8       0
///
fn enc_vrx(opcode: u16, v1: Reg, b2: Reg, x2: Reg, d2: u32, m3: u8) -> [u8; 6] {
    let opcode1 = ((opcode >> 8) & 0xff) as u8;
    let opcode2 = (opcode & 0xff) as u8;
    let rxb = rxb(Some(v1), None, None, None);
    let v1 = machreg_to_vr(v1) & 0x0f;
    let b2 = machreg_to_gpr(b2) & 0x0f;
    let x2 = machreg_to_gpr(x2) & 0x0f;
    let d2_lo = (d2 & 0xff) as u8;
    let d2_hi = ((d2 >> 8) & 0x0f) as u8;
    let m3 = m3 & 0x0f;

    let mut enc: [u8; 6] = [0; 6];
    enc[0] = opcode1;
    enc[1] = v1 << 4 | x2;
    enc[2] = b2 << 4 | d2_hi;
    enc[3] = d2_lo;
    enc[4] = m3 << 4 | rxb;
    enc[5] = opcode2;
    enc
}

/// Emit encoding to sink.
fn put(sink: &mut MachBuffer<Inst>, enc: &[u8]) {
    for byte in enc {
        sink.put1(*byte);
    }
}

/// Emit encoding to sink, adding a trap on the last byte.
fn put_with_trap(sink: &mut MachBuffer<Inst>, enc: &[u8], trap_code: TrapCode) {
    let len = enc.len();
    for i in 0..len - 1 {
        sink.put1(enc[i]);
    }
    sink.add_trap(trap_code);
    sink.put1(enc[len - 1]);
}

/// State carried between emissions of a sequence of instructions.
#[derive(Default, Clone, Debug)]
pub struct EmitState {
    /// Offset from the actual SP to the "nominal SP".  The latter is defined
    /// as the value the stack pointer has after the prolog.  This offset is
    /// normally always zero, except during a call sequence using the tail-call
    /// ABI, between the AllocateArgs and the actual call instruction.
    pub(crate) nominal_sp_offset: u32,

    /// Offset from the actual SP to the SP during an outgoing function call.
    /// This is normally always zero, except during processing of the return
    /// argument handling after a call using the tail-call ABI has returned.
    pub(crate) outgoing_sp_offset: u32,

    /// Size of the incoming argument area in the caller's frame.  Always zero
    /// for functions using the tail-call ABI.
    pub(crate) incoming_args_size: u32,

    /// The user stack map for the upcoming instruction, as provided to
    /// `pre_safepoint()`.
    user_stack_map: Option<ir::UserStackMap>,

    /// Only used during fuzz-testing. Otherwise, it is a zero-sized struct and
    /// optimized away at compiletime. See [cranelift_control].
    ctrl_plane: ControlPlane,

    frame_layout: FrameLayout,
}

impl MachInstEmitState<Inst> for EmitState {
    fn new(abi: &Callee<S390xMachineDeps>, ctrl_plane: ControlPlane) -> Self {
        let incoming_args_size = if abi.call_conv() == CallConv::Tail {
            0
        } else {
            abi.frame_layout().incoming_args_size
        };
        EmitState {
            nominal_sp_offset: 0,
            outgoing_sp_offset: 0,
            incoming_args_size,
            user_stack_map: None,
            ctrl_plane,
            frame_layout: abi.frame_layout().clone(),
        }
    }

    fn pre_safepoint(&mut self, user_stack_map: Option<ir::UserStackMap>) {
        self.user_stack_map = user_stack_map;
    }

    fn ctrl_plane_mut(&mut self) -> &mut ControlPlane {
        &mut self.ctrl_plane
    }

    fn take_ctrl_plane(self) -> ControlPlane {
        self.ctrl_plane
    }

    fn frame_layout(&self) -> &FrameLayout {
        &self.frame_layout
    }
}

impl EmitState {
    fn take_stack_map(&mut self) -> Option<ir::UserStackMap> {
        self.user_stack_map.take()
    }

    fn clear_post_insn(&mut self) {
        self.user_stack_map = None;
    }
}

/// Constant state used during function compilation.
pub struct EmitInfo {
    isa_flags: s390x_settings::Flags,
}

impl EmitInfo {
    pub(crate) fn new(isa_flags: s390x_settings::Flags) -> Self {
        Self { isa_flags }
    }
}

impl MachInstEmit for Inst {
    type State = EmitState;
    type Info = EmitInfo;

    fn emit(&self, sink: &mut MachBuffer<Inst>, emit_info: &Self::Info, state: &mut EmitState) {
        self.emit_with_alloc_consumer(sink, emit_info, state)
    }

    fn pretty_print_inst(&self, state: &mut EmitState) -> String {
        self.print_with_state(state)
    }
}

impl Inst {
    fn emit_with_alloc_consumer(
        &self,
        sink: &mut MachBuffer<Inst>,
        emit_info: &EmitInfo,
        state: &mut EmitState,
    ) {
        // Verify that we can emit this Inst in the current ISA
        let matches_isa_flags = |iset_requirement: &InstructionSet| -> bool {
            match iset_requirement {
                // Baseline ISA is z14
                InstructionSet::Base => true,
                // Miscellaneous-Instruction-Extensions Facility 3 (z15)
                InstructionSet::MIE3 => emit_info.isa_flags.has_mie3(),
                // Miscellaneous-Instruction-Extensions Facility 4 (z17)
                InstructionSet::MIE4 => emit_info.isa_flags.has_mie4(),
                // Vector-Enhancements Facility 2 (z15)
                InstructionSet::VXRS_EXT2 => emit_info.isa_flags.has_vxrs_ext2(),
                // Vector-Enhancements Facility 3 (z17)
                InstructionSet::VXRS_EXT3 => emit_info.isa_flags.has_vxrs_ext3(),
            }
        };
        let isa_requirements = self.available_in_isa();
        if !matches_isa_flags(&isa_requirements) {
            panic!(
                "Cannot emit inst '{self:?}' for target; failed to match ISA requirements: {isa_requirements:?}"
            )
        }

        match self {
            &Inst::AluRRR { alu_op, rd, rn, rm } => {
                let (opcode, have_rr) = match alu_op {
                    ALUOp::Add32 => (0xb9f8, true),        // ARK
                    ALUOp::Add64 => (0xb9e8, true),        // AGRK
                    ALUOp::AddLogical32 => (0xb9fa, true), // ALRK
                    ALUOp::AddLogical64 => (0xb9ea, true), // ALGRK
                    ALUOp::Sub32 => (0xb9f9, true),        // SRK
                    ALUOp::Sub64 => (0xb9e9, true),        // SGRK
                    ALUOp::SubLogical32 => (0xb9fb, true), // SLRK
                    ALUOp::SubLogical64 => (0xb9eb, true), // SLGRK
                    ALUOp::Mul32 => (0xb9fd, true),        // MSRKC
                    ALUOp::Mul64 => (0xb9ed, true),        // MSGRKC
                    ALUOp::And32 => (0xb9f4, true),        // NRK
                    ALUOp::And64 => (0xb9e4, true),        // NGRK
                    ALUOp::Orr32 => (0xb9f6, true),        // ORK
                    ALUOp::Orr64 => (0xb9e6, true),        // OGRK
                    ALUOp::Xor32 => (0xb9f7, true),        // XRK
                    ALUOp::Xor64 => (0xb9e7, true),        // XGRK
                    ALUOp::NotAnd32 => (0xb974, false),    // NNRK
                    ALUOp::NotAnd64 => (0xb964, false),    // NNGRK
                    ALUOp::NotOrr32 => (0xb976, false),    // NORK
                    ALUOp::NotOrr64 => (0xb966, false),    // NOGRK
                    ALUOp::NotXor32 => (0xb977, false),    // NXRK
                    ALUOp::NotXor64 => (0xb967, false),    // NXGRK
                    ALUOp::AndNot32 => (0xb9f5, false),    // NCRK
                    ALUOp::AndNot64 => (0xb9e5, false),    // NCGRK
                    ALUOp::OrrNot32 => (0xb975, false),    // OCRK
                    ALUOp::OrrNot64 => (0xb965, false),    // OCGRK
                    _ => unreachable!(),
                };
                if have_rr && rd.to_reg() == rn {
                    let inst = Inst::AluRR {
                        alu_op,
                        rd,
                        ri: rn,
                        rm,
                    };
                    inst.emit(sink, emit_info, state);
                } else {
                    put(sink, &enc_rrf_ab(opcode, rd.to_reg(), rn, rm, 0));
                }
            }
            &Inst::AluRRSImm16 {
                alu_op,
                rd,
                rn,
                imm,
            } => {
                if rd.to_reg() == rn {
                    let inst = Inst::AluRSImm16 {
                        alu_op,
                        rd,
                        ri: rn,
                        imm,
                    };
                    inst.emit(sink, emit_info, state);
                } else {
                    let opcode = match alu_op {
                        ALUOp::Add32 => 0xecd8, // AHIK
                        ALUOp::Add64 => 0xecd9, // AGHIK
                        _ => unreachable!(),
                    };
                    put(sink, &enc_rie_d(opcode, rd.to_reg(), rn, imm as u16));
                }
            }
            &Inst::AluRR { alu_op, rd, ri, rm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let (opcode, is_rre) = match alu_op {
                    ALUOp::Add32 => (0x1a, false),              // AR
                    ALUOp::Add64 => (0xb908, true),             // AGR
                    ALUOp::Add64Ext32 => (0xb918, true),        // AGFR
                    ALUOp::AddLogical32 => (0x1e, false),       // ALR
                    ALUOp::AddLogical64 => (0xb90a, true),      // ALGR
                    ALUOp::AddLogical64Ext32 => (0xb91a, true), // ALGFR
                    ALUOp::Sub32 => (0x1b, false),              // SR
                    ALUOp::Sub64 => (0xb909, true),             // SGR
                    ALUOp::Sub64Ext32 => (0xb919, true),        // SGFR
                    ALUOp::SubLogical32 => (0x1f, false),       // SLR
                    ALUOp::SubLogical64 => (0xb90b, true),      // SLGR
                    ALUOp::SubLogical64Ext32 => (0xb91b, true), // SLGFR
                    ALUOp::Mul32 => (0xb252, true),             // MSR
                    ALUOp::Mul64 => (0xb90c, true),             // MSGR
                    ALUOp::Mul64Ext32 => (0xb91c, true),        // MSGFR
                    ALUOp::And32 => (0x14, false),              // NR
                    ALUOp::And64 => (0xb980, true),             // NGR
                    ALUOp::Orr32 => (0x16, false),              // OR
                    ALUOp::Orr64 => (0xb981, true),             // OGR
                    ALUOp::Xor32 => (0x17, false),              // XR
                    ALUOp::Xor64 => (0xb982, true),             // XGR
                    _ => unreachable!(),
                };
                if is_rre {
                    put(sink, &enc_rre(opcode, rd.to_reg(), rm));
                } else {
                    put(sink, &enc_rr(opcode, rd.to_reg(), rm));
                }
            }
            &Inst::AluRX {
                alu_op,
                rd,
                ri,
                ref mem,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);
                let mem = mem.clone();

                let (opcode_rx, opcode_rxy) = match alu_op {
                    ALUOp::Add32 => (Some(0x5a), Some(0xe35a)),        // A(Y)
                    ALUOp::Add32Ext16 => (Some(0x4a), Some(0xe37a)),   // AH(Y)
                    ALUOp::Add64 => (None, Some(0xe308)),              // AG
                    ALUOp::Add64Ext16 => (None, Some(0xe338)),         // AGH
                    ALUOp::Add64Ext32 => (None, Some(0xe318)),         // AGF
                    ALUOp::AddLogical32 => (Some(0x5e), Some(0xe35e)), // AL(Y)
                    ALUOp::AddLogical64 => (None, Some(0xe30a)),       // ALG
                    ALUOp::AddLogical64Ext32 => (None, Some(0xe31a)),  // ALGF
                    ALUOp::Sub32 => (Some(0x5b), Some(0xe35b)),        // S(Y)
                    ALUOp::Sub32Ext16 => (Some(0x4b), Some(0xe37b)),   // SH(Y)
                    ALUOp::Sub64 => (None, Some(0xe309)),              // SG
                    ALUOp::Sub64Ext16 => (None, Some(0xe339)),         // SGH
                    ALUOp::Sub64Ext32 => (None, Some(0xe319)),         // SGF
                    ALUOp::SubLogical32 => (Some(0x5f), Some(0xe35f)), // SL(Y)
                    ALUOp::SubLogical64 => (None, Some(0xe30b)),       // SLG
                    ALUOp::SubLogical64Ext32 => (None, Some(0xe31b)),  // SLGF
                    ALUOp::Mul32 => (Some(0x71), Some(0xe351)),        // MS(Y)
                    ALUOp::Mul32Ext16 => (Some(0x4c), Some(0xe37c)),   // MH(Y)
                    ALUOp::Mul64 => (None, Some(0xe30c)),              // MSG
                    ALUOp::Mul64Ext16 => (None, Some(0xe33c)),         // MSH
                    ALUOp::Mul64Ext32 => (None, Some(0xe31c)),         // MSGF
                    ALUOp::And32 => (Some(0x54), Some(0xe354)),        // N(Y)
                    ALUOp::And64 => (None, Some(0xe380)),              // NG
                    ALUOp::Orr32 => (Some(0x56), Some(0xe356)),        // O(Y)
                    ALUOp::Orr64 => (None, Some(0xe381)),              // OG
                    ALUOp::Xor32 => (Some(0x57), Some(0xe357)),        // X(Y)
                    ALUOp::Xor64 => (None, Some(0xe382)),              // XG
                    _ => unreachable!(),
                };
                let rd = rd.to_reg();
                mem_emit(
                    rd, &mem, opcode_rx, opcode_rxy, None, true, sink, emit_info, state,
                );
            }
            &Inst::AluRSImm16 {
                alu_op,
                rd,
                ri,
                imm,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match alu_op {
                    ALUOp::Add32 => 0xa7a, // AHI
                    ALUOp::Add64 => 0xa7b, // AGHI
                    ALUOp::Mul32 => 0xa7c, // MHI
                    ALUOp::Mul64 => 0xa7d, // MGHI
                    _ => unreachable!(),
                };
                put(sink, &enc_ri_a(opcode, rd.to_reg(), imm as u16));
            }
            &Inst::AluRSImm32 {
                alu_op,
                rd,
                ri,
                imm,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match alu_op {
                    ALUOp::Add32 => 0xc29, // AFI
                    ALUOp::Add64 => 0xc28, // AGFI
                    ALUOp::Mul32 => 0xc21, // MSFI
                    ALUOp::Mul64 => 0xc20, // MSGFI
                    _ => unreachable!(),
                };
                put(sink, &enc_ril_a(opcode, rd.to_reg(), imm as u32));
            }
            &Inst::AluRUImm32 {
                alu_op,
                rd,
                ri,
                imm,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match alu_op {
                    ALUOp::AddLogical32 => 0xc2b, // ALFI
                    ALUOp::AddLogical64 => 0xc2a, // ALGFI
                    ALUOp::SubLogical32 => 0xc25, // SLFI
                    ALUOp::SubLogical64 => 0xc24, // SLGFI
                    _ => unreachable!(),
                };
                put(sink, &enc_ril_a(opcode, rd.to_reg(), imm));
            }
            &Inst::AluRUImm16Shifted {
                alu_op,
                rd,
                ri,
                imm,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match (alu_op, imm.shift) {
                    (ALUOp::And32, 0) => 0xa57, // NILL
                    (ALUOp::And32, 1) => 0xa56, // NILH
                    (ALUOp::And64, 0) => 0xa57, // NILL
                    (ALUOp::And64, 1) => 0xa56, // NILH
                    (ALUOp::And64, 2) => 0xa55, // NIHL
                    (ALUOp::And64, 3) => 0xa54, // NIHL
                    (ALUOp::Orr32, 0) => 0xa5b, // OILL
                    (ALUOp::Orr32, 1) => 0xa5a, // OILH
                    (ALUOp::Orr64, 0) => 0xa5b, // OILL
                    (ALUOp::Orr64, 1) => 0xa5a, // OILH
                    (ALUOp::Orr64, 2) => 0xa59, // OIHL
                    (ALUOp::Orr64, 3) => 0xa58, // OIHH
                    _ => unreachable!(),
                };
                put(sink, &enc_ri_a(opcode, rd.to_reg(), imm.bits));
            }
            &Inst::AluRUImm32Shifted {
                alu_op,
                rd,
                ri,
                imm,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match (alu_op, imm.shift) {
                    (ALUOp::And32, 0) => 0xc0b, // NILF
                    (ALUOp::And64, 0) => 0xc0b, // NILF
                    (ALUOp::And64, 1) => 0xc0a, // NIHF
                    (ALUOp::Orr32, 0) => 0xc0d, // OILF
                    (ALUOp::Orr64, 0) => 0xc0d, // OILF
                    (ALUOp::Orr64, 1) => 0xc0c, // OILF
                    (ALUOp::Xor32, 0) => 0xc07, // XILF
                    (ALUOp::Xor64, 0) => 0xc07, // XILF
                    (ALUOp::Xor64, 1) => 0xc06, // XILH
                    _ => unreachable!(),
                };
                put(sink, &enc_ril_a(opcode, rd.to_reg(), imm.bits));
            }

            &Inst::SMulWide { rd, rn, rm } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_regpair!(rd1.to_reg(), rd2.to_reg());

                let opcode = 0xb9ec; // MGRK
                put(sink, &enc_rrf_ab(opcode, rd1.to_reg(), rn, rm, 0));
            }
            &Inst::UMulWide { rd, ri, rn } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_regpair!(rd1.to_reg(), rd2.to_reg());
                debug_assert_eq!(rd2.to_reg(), ri);

                let opcode = 0xb986; // MLGR
                put(sink, &enc_rre(opcode, rd1.to_reg(), rn));
            }
            &Inst::SDivMod32 { rd, ri, rn } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_regpair!(rd1.to_reg(), rd2.to_reg());
                debug_assert_eq!(rd2.to_reg(), ri);

                let opcode = 0xb91d; // DSGFR
                let trap_code = TrapCode::INTEGER_DIVISION_BY_ZERO;
                put_with_trap(sink, &enc_rre(opcode, rd1.to_reg(), rn), trap_code);
            }
            &Inst::SDivMod64 { rd, ri, rn } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_regpair!(rd1.to_reg(), rd2.to_reg());
                debug_assert_eq!(rd2.to_reg(), ri);

                let opcode = 0xb90d; // DSGR
                let trap_code = TrapCode::INTEGER_DIVISION_BY_ZERO;
                put_with_trap(sink, &enc_rre(opcode, rd1.to_reg(), rn), trap_code);
            }
            &Inst::UDivMod32 { rd, ri, rn } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_regpair!(rd1.to_reg(), rd2.to_reg());
                let ri1 = ri.hi;
                let ri2 = ri.lo;
                debug_assert_eq!(rd1.to_reg(), ri1);
                debug_assert_eq!(rd2.to_reg(), ri2);

                let opcode = 0xb997; // DLR
                let trap_code = TrapCode::INTEGER_DIVISION_BY_ZERO;
                put_with_trap(sink, &enc_rre(opcode, rd1.to_reg(), rn), trap_code);
            }
            &Inst::UDivMod64 { rd, ri, rn } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_regpair!(rd1.to_reg(), rd2.to_reg());
                let ri1 = ri.hi;
                let ri2 = ri.lo;
                debug_assert_eq!(rd1.to_reg(), ri1);
                debug_assert_eq!(rd2.to_reg(), ri2);

                let opcode = 0xb987; // DLGR
                let trap_code = TrapCode::INTEGER_DIVISION_BY_ZERO;
                put_with_trap(sink, &enc_rre(opcode, rd1.to_reg(), rn), trap_code);
            }
            &Inst::Flogr { rd, rn } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_regpair!(rd1.to_reg(), rd2.to_reg());

                let opcode = 0xb983; // FLOGR
                put(sink, &enc_rre(opcode, rd1.to_reg(), rn));
            }

            &Inst::ShiftRR {
                shift_op,
                rd,
                rn,
                shift_imm,
                shift_reg,
            } => {
                let opcode = match shift_op {
                    ShiftOp::RotL32 => 0xeb1d, // RLL
                    ShiftOp::RotL64 => 0xeb1c, // RLLG
                    ShiftOp::LShL32 => 0xebdf, // SLLK  (SLL ?)
                    ShiftOp::LShL64 => 0xeb0d, // SLLG
                    ShiftOp::LShR32 => 0xebde, // SRLK  (SRL ?)
                    ShiftOp::LShR64 => 0xeb0c, // SRLG
                    ShiftOp::AShR32 => 0xebdc, // SRAK  (SRA ?)
                    ShiftOp::AShR64 => 0xeb0a, // SRAG
                };
                put(
                    sink,
                    &enc_rsy(opcode, rd.to_reg(), rn, shift_reg, shift_imm.into()),
                );
            }

            &Inst::RxSBG {
                op,
                rd,
                ri,
                rn,
                start_bit,
                end_bit,
                rotate_amt,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match op {
                    RxSBGOp::Insert => 0xec59, // RISBGN
                    RxSBGOp::And => 0xec54,    // RNSBG
                    RxSBGOp::Or => 0xec56,     // ROSBG
                    RxSBGOp::Xor => 0xec57,    // RXSBG
                };
                put(
                    sink,
                    &enc_rie_f(
                        opcode,
                        rd.to_reg(),
                        rn,
                        start_bit,
                        end_bit,
                        (rotate_amt as u8) & 63,
                    ),
                );
            }

            &Inst::RxSBGTest {
                op,
                rd,
                rn,
                start_bit,
                end_bit,
                rotate_amt,
            } => {
                let opcode = match op {
                    RxSBGOp::And => 0xec54, // RNSBG
                    RxSBGOp::Or => 0xec56,  // ROSBG
                    RxSBGOp::Xor => 0xec57, // RXSBG
                    _ => unreachable!(),
                };
                put(
                    sink,
                    &enc_rie_f(
                        opcode,
                        rd,
                        rn,
                        start_bit | 0x80,
                        end_bit,
                        (rotate_amt as u8) & 63,
                    ),
                );
            }

            &Inst::UnaryRR { op, rd, rn } => {
                match op {
                    UnaryOp::Abs32 => {
                        let opcode = 0x10; // LPR
                        put(sink, &enc_rr(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::Abs64 => {
                        let opcode = 0xb900; // LPGR
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::Abs64Ext32 => {
                        let opcode = 0xb910; // LPGFR
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::Neg32 => {
                        let opcode = 0x13; // LCR
                        put(sink, &enc_rr(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::Neg64 => {
                        let opcode = 0xb903; // LCGR
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::Neg64Ext32 => {
                        let opcode = 0xb913; // LCGFR
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::PopcntByte => {
                        let opcode = 0xb9e1; // POPCNT
                        put(sink, &enc_rrf_cde(opcode, rd.to_reg(), rn, 0, 0));
                    }
                    UnaryOp::PopcntReg => {
                        let opcode = 0xb9e1; // POPCNT
                        put(sink, &enc_rrf_cde(opcode, rd.to_reg(), rn, 8, 0));
                    }
                    UnaryOp::BSwap32 => {
                        let opcode = 0xb91f; // LRVR
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::BSwap64 => {
                        let opcode = 0xb90f; // LRVRG
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::Clz64 => {
                        let opcode = 0xb968; // CLZG
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                    UnaryOp::Ctz64 => {
                        let opcode = 0xb969; // CTZG
                        put(sink, &enc_rre(opcode, rd.to_reg(), rn));
                    }
                }
            }

            &Inst::Extend {
                rd,
                rn,
                signed,
                from_bits,
                to_bits,
            } => {
                let opcode = match (signed, from_bits, to_bits) {
                    (_, 1, 32) => 0xb926,      // LBR
                    (_, 1, 64) => 0xb906,      // LGBR
                    (false, 8, 32) => 0xb994,  // LLCR
                    (false, 8, 64) => 0xb984,  // LLGCR
                    (true, 8, 32) => 0xb926,   // LBR
                    (true, 8, 64) => 0xb906,   // LGBR
                    (false, 16, 32) => 0xb995, // LLHR
                    (false, 16, 64) => 0xb985, // LLGHR
                    (true, 16, 32) => 0xb927,  // LHR
                    (true, 16, 64) => 0xb907,  // LGHR
                    (false, 32, 64) => 0xb916, // LLGFR
                    (true, 32, 64) => 0xb914,  // LGFR
                    _ => panic!(
                        "Unsupported extend combination: signed = {signed}, from_bits = {from_bits}, to_bits = {to_bits}"
                    ),
                };
                put(sink, &enc_rre(opcode, rd.to_reg(), rn));
            }

            &Inst::CmpRR { op, rn, rm } => {
                let (opcode, is_rre) = match op {
                    CmpOp::CmpS32 => (0x19, false),       // CR
                    CmpOp::CmpS64 => (0xb920, true),      // CGR
                    CmpOp::CmpS64Ext32 => (0xb930, true), // CGFR
                    CmpOp::CmpL32 => (0x15, false),       // CLR
                    CmpOp::CmpL64 => (0xb921, true),      // CLGR
                    CmpOp::CmpL64Ext32 => (0xb931, true), // CLGFR
                    _ => unreachable!(),
                };
                if is_rre {
                    put(sink, &enc_rre(opcode, rn, rm));
                } else {
                    put(sink, &enc_rr(opcode, rn, rm));
                }
            }
            &Inst::CmpRX { op, rn, ref mem } => {
                let mem = mem.clone();

                let (opcode_rx, opcode_rxy, opcode_ril) = match op {
                    CmpOp::CmpS32 => (Some(0x59), Some(0xe359), Some(0xc6d)), // C(Y), CRL
                    CmpOp::CmpS32Ext16 => (Some(0x49), Some(0xe379), Some(0xc65)), // CH(Y), CHRL
                    CmpOp::CmpS64 => (None, Some(0xe320), Some(0xc68)),       // CG, CGRL
                    CmpOp::CmpS64Ext16 => (None, Some(0xe334), Some(0xc64)),  // CGH, CGHRL
                    CmpOp::CmpS64Ext32 => (None, Some(0xe330), Some(0xc6c)),  // CGF, CGFRL
                    CmpOp::CmpL32 => (Some(0x55), Some(0xe355), Some(0xc6f)), // CL(Y), CLRL
                    CmpOp::CmpL32Ext16 => (None, None, Some(0xc67)),          // CLHRL
                    CmpOp::CmpL64 => (None, Some(0xe321), Some(0xc6a)),       // CLG, CLGRL
                    CmpOp::CmpL64Ext16 => (None, None, Some(0xc66)),          // CLGHRL
                    CmpOp::CmpL64Ext32 => (None, Some(0xe331), Some(0xc6e)),  // CLGF, CLGFRL
                };
                mem_emit(
                    rn, &mem, opcode_rx, opcode_rxy, opcode_ril, true, sink, emit_info, state,
                );
            }
            &Inst::CmpRSImm16 { op, rn, imm } => {
                let opcode = match op {
                    CmpOp::CmpS32 => 0xa7e, // CHI
                    CmpOp::CmpS64 => 0xa7f, // CGHI
                    _ => unreachable!(),
                };
                put(sink, &enc_ri_a(opcode, rn, imm as u16));
            }
            &Inst::CmpRSImm32 { op, rn, imm } => {
                let opcode = match op {
                    CmpOp::CmpS32 => 0xc2d, // CFI
                    CmpOp::CmpS64 => 0xc2c, // CGFI
                    _ => unreachable!(),
                };
                put(sink, &enc_ril_a(opcode, rn, imm as u32));
            }
            &Inst::CmpRUImm32 { op, rn, imm } => {
                let opcode = match op {
                    CmpOp::CmpL32 => 0xc2f, // CLFI
                    CmpOp::CmpL64 => 0xc2e, // CLGFI
                    _ => unreachable!(),
                };
                put(sink, &enc_ril_a(opcode, rn, imm));
            }
            &Inst::CmpTrapRR {
                op,
                rn,
                rm,
                cond,
                trap_code,
            } => {
                let opcode = match op {
                    CmpOp::CmpS32 => 0xb972, // CRT
                    CmpOp::CmpS64 => 0xb960, // CGRT
                    CmpOp::CmpL32 => 0xb973, // CLRT
                    CmpOp::CmpL64 => 0xb961, // CLGRT
                    _ => unreachable!(),
                };
                put_with_trap(
                    sink,
                    &enc_rrf_cde(opcode, rn, rm, cond.bits(), 0),
                    trap_code,
                );
            }
            &Inst::CmpTrapRSImm16 {
                op,
                rn,
                imm,
                cond,
                trap_code,
            } => {
                let opcode = match op {
                    CmpOp::CmpS32 => 0xec72, // CIT
                    CmpOp::CmpS64 => 0xec70, // CGIT
                    _ => unreachable!(),
                };
                put_with_trap(
                    sink,
                    &enc_rie_a(opcode, rn, imm as u16, cond.bits()),
                    trap_code,
                );
            }
            &Inst::CmpTrapRUImm16 {
                op,
                rn,
                imm,
                cond,
                trap_code,
            } => {
                let opcode = match op {
                    CmpOp::CmpL32 => 0xec73, // CLFIT
                    CmpOp::CmpL64 => 0xec71, // CLGIT
                    _ => unreachable!(),
                };
                put_with_trap(sink, &enc_rie_a(opcode, rn, imm, cond.bits()), trap_code);
            }

            &Inst::AtomicRmw {
                alu_op,
                rd,
                rn,
                ref mem,
            } => {
                let mem = mem.clone();

                let opcode = match alu_op {
                    ALUOp::Add32 => 0xebf8,        // LAA
                    ALUOp::Add64 => 0xebe8,        // LAAG
                    ALUOp::AddLogical32 => 0xebfa, // LAAL
                    ALUOp::AddLogical64 => 0xebea, // LAALG
                    ALUOp::And32 => 0xebf4,        // LAN
                    ALUOp::And64 => 0xebe4,        // LANG
                    ALUOp::Orr32 => 0xebf6,        // LAO
                    ALUOp::Orr64 => 0xebe6,        // LAOG
                    ALUOp::Xor32 => 0xebf7,        // LAX
                    ALUOp::Xor64 => 0xebe7,        // LAXG
                    _ => unreachable!(),
                };

                let rd = rd.to_reg();
                mem_rs_emit(
                    rd,
                    rn,
                    &mem,
                    None,
                    Some(opcode),
                    true,
                    sink,
                    emit_info,
                    state,
                );
            }
            &Inst::Loop { ref body, cond } => {
                // This sequence is *one* instruction in the vcode, and is expanded only here at
                // emission time, because it requires branching to internal labels.
                let loop_label = sink.get_label();
                let done_label = sink.get_label();

                // Emit label at the start of the loop.
                sink.bind_label(loop_label, &mut state.ctrl_plane);

                for inst in (&body).into_iter() {
                    match &inst {
                        // Replace a CondBreak with a branch to done_label.
                        &Inst::CondBreak { cond } => {
                            let opcode = 0xc04; // BCRL
                            sink.use_label_at_offset(
                                sink.cur_offset(),
                                done_label,
                                LabelUse::BranchRIL,
                            );
                            put(sink, &enc_ril_c(opcode, cond.bits(), 0));
                        }
                        _ => inst.emit_with_alloc_consumer(sink, emit_info, state),
                    };
                }

                let opcode = 0xc04; // BCRL
                sink.use_label_at_offset(sink.cur_offset(), loop_label, LabelUse::BranchRIL);
                put(sink, &enc_ril_c(opcode, cond.bits(), 0));

                // Emit label at the end of the loop.
                sink.bind_label(done_label, &mut state.ctrl_plane);
            }
            &Inst::CondBreak { .. } => unreachable!(), // Only valid inside a Loop.
            &Inst::AtomicCas32 {
                rd,
                ri,
                rn,
                ref mem,
            }
            | &Inst::AtomicCas64 {
                rd,
                ri,
                rn,
                ref mem,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);
                let mem = mem.clone();

                let (opcode_rs, opcode_rsy) = match self {
                    &Inst::AtomicCas32 { .. } => (Some(0xba), Some(0xeb14)), // CS(Y)
                    &Inst::AtomicCas64 { .. } => (None, Some(0xeb30)),       // CSG
                    _ => unreachable!(),
                };

                let rd = rd.to_reg();
                mem_rs_emit(
                    rd, rn, &mem, opcode_rs, opcode_rsy, true, sink, emit_info, state,
                );
            }
            &Inst::Fence => {
                put(sink, &enc_e(0x07e0));
            }

            &Inst::Load32 { rd, ref mem }
            | &Inst::Load32ZExt8 { rd, ref mem }
            | &Inst::Load32SExt8 { rd, ref mem }
            | &Inst::Load32ZExt16 { rd, ref mem }
            | &Inst::Load32SExt16 { rd, ref mem }
            | &Inst::Load64 { rd, ref mem }
            | &Inst::Load64ZExt8 { rd, ref mem }
            | &Inst::Load64SExt8 { rd, ref mem }
            | &Inst::Load64ZExt16 { rd, ref mem }
            | &Inst::Load64SExt16 { rd, ref mem }
            | &Inst::Load64ZExt32 { rd, ref mem }
            | &Inst::Load64SExt32 { rd, ref mem }
            | &Inst::LoadRev16 { rd, ref mem }
            | &Inst::LoadRev32 { rd, ref mem }
            | &Inst::LoadRev64 { rd, ref mem } => {
                let mem = mem.clone();

                let (opcode_rx, opcode_rxy, opcode_ril) = match self {
                    &Inst::Load32 { .. } => (Some(0x58), Some(0xe358), Some(0xc4d)), // L(Y), LRL
                    &Inst::Load32ZExt8 { .. } => (None, Some(0xe394), None),         // LLC
                    &Inst::Load32SExt8 { .. } => (None, Some(0xe376), None),         // LB
                    &Inst::Load32ZExt16 { .. } => (None, Some(0xe395), Some(0xc42)), // LLH, LLHRL
                    &Inst::Load32SExt16 { .. } => (Some(0x48), Some(0xe378), Some(0xc45)), // LH(Y), LHRL
                    &Inst::Load64 { .. } => (None, Some(0xe304), Some(0xc48)), // LG, LGRL
                    &Inst::Load64ZExt8 { .. } => (None, Some(0xe390), None),   // LLGC
                    &Inst::Load64SExt8 { .. } => (None, Some(0xe377), None),   // LGB
                    &Inst::Load64ZExt16 { .. } => (None, Some(0xe391), Some(0xc46)), // LLGH, LLGHRL
                    &Inst::Load64SExt16 { .. } => (None, Some(0xe315), Some(0xc44)), // LGH, LGHRL
                    &Inst::Load64ZExt32 { .. } => (None, Some(0xe316), Some(0xc4e)), // LLGF, LLGFRL
                    &Inst::Load64SExt32 { .. } => (None, Some(0xe314), Some(0xc4c)), // LGF, LGFRL
                    &Inst::LoadRev16 { .. } => (None, Some(0xe31f), None),     // LRVH
                    &Inst::LoadRev32 { .. } => (None, Some(0xe31e), None),     // LRV
                    &Inst::LoadRev64 { .. } => (None, Some(0xe30f), None),     // LRVG
                    _ => unreachable!(),
                };
                let rd = rd.to_reg();
                mem_emit(
                    rd, &mem, opcode_rx, opcode_rxy, opcode_ril, true, sink, emit_info, state,
                );
            }

            &Inst::Store8 { rd, ref mem }
            | &Inst::Store16 { rd, ref mem }
            | &Inst::Store32 { rd, ref mem }
            | &Inst::Store64 { rd, ref mem }
            | &Inst::StoreRev16 { rd, ref mem }
            | &Inst::StoreRev32 { rd, ref mem }
            | &Inst::StoreRev64 { rd, ref mem } => {
                let mem = mem.clone();

                let (opcode_rx, opcode_rxy, opcode_ril) = match self {
                    &Inst::Store8 { .. } => (Some(0x42), Some(0xe372), None), // STC(Y)
                    &Inst::Store16 { .. } => (Some(0x40), Some(0xe370), Some(0xc47)), // STH(Y), STHRL
                    &Inst::Store32 { .. } => (Some(0x50), Some(0xe350), Some(0xc4f)), // ST(Y), STRL
                    &Inst::Store64 { .. } => (None, Some(0xe324), Some(0xc4b)),       // STG, STGRL
                    &Inst::StoreRev16 { .. } => (None, Some(0xe33f), None),           // STRVH
                    &Inst::StoreRev32 { .. } => (None, Some(0xe33e), None),           // STRV
                    &Inst::StoreRev64 { .. } => (None, Some(0xe32f), None),           // STRVG
                    _ => unreachable!(),
                };
                mem_emit(
                    rd, &mem, opcode_rx, opcode_rxy, opcode_ril, true, sink, emit_info, state,
                );
            }
            &Inst::StoreImm8 { imm, ref mem } => {
                let mem = mem.clone();

                let opcode_si = 0x92; // MVI
                let opcode_siy = 0xeb52; // MVIY
                mem_imm8_emit(
                    imm, &mem, opcode_si, opcode_siy, true, sink, emit_info, state,
                );
            }
            &Inst::StoreImm16 { imm, ref mem }
            | &Inst::StoreImm32SExt16 { imm, ref mem }
            | &Inst::StoreImm64SExt16 { imm, ref mem } => {
                let mem = mem.clone();

                let opcode = match self {
                    &Inst::StoreImm16 { .. } => 0xe544,       // MVHHI
                    &Inst::StoreImm32SExt16 { .. } => 0xe54c, // MVHI
                    &Inst::StoreImm64SExt16 { .. } => 0xe548, // MVGHI
                    _ => unreachable!(),
                };
                mem_imm16_emit(imm, &mem, opcode, true, sink, emit_info, state);
            }

            &Inst::LoadMultiple64 { rt, rt2, ref mem } => {
                let mem = mem.clone();

                let opcode = 0xeb04; // LMG
                let rt = rt.to_reg();
                let rt2 = rt2.to_reg();
                mem_rs_emit(
                    rt,
                    rt2,
                    &mem,
                    None,
                    Some(opcode),
                    true,
                    sink,
                    emit_info,
                    state,
                );
            }
            &Inst::StoreMultiple64 { rt, rt2, ref mem } => {
                let mem = mem.clone();

                let opcode = 0xeb24; // STMG
                mem_rs_emit(
                    rt,
                    rt2,
                    &mem,
                    None,
                    Some(opcode),
                    true,
                    sink,
                    emit_info,
                    state,
                );
            }

            &Inst::LoadAddr { rd, ref mem } => {
                let mem = mem.clone();

                let opcode_rx = Some(0x41); // LA
                let opcode_rxy = Some(0xe371); // LAY
                let opcode_ril = Some(0xc00); // LARL
                let rd = rd.to_reg();
                mem_emit(
                    rd, &mem, opcode_rx, opcode_rxy, opcode_ril, false, sink, emit_info, state,
                );
            }

            &Inst::Mov64 { rd, rm } => {
                let opcode = 0xb904; // LGR
                put(sink, &enc_rre(opcode, rd.to_reg(), rm));
            }
            &Inst::MovPReg { rd, rm } => {
                Inst::Mov64 { rd, rm: rm.into() }.emit(sink, emit_info, state);
            }
            &Inst::Mov32 { rd, rm } => {
                let opcode = 0x18; // LR
                put(sink, &enc_rr(opcode, rd.to_reg(), rm));
            }
            &Inst::Mov32Imm { rd, imm } => {
                let opcode = 0xc09; // IILF
                put(sink, &enc_ril_a(opcode, rd.to_reg(), imm));
            }
            &Inst::Mov32SImm16 { rd, imm } => {
                let opcode = 0xa78; // LHI
                put(sink, &enc_ri_a(opcode, rd.to_reg(), imm as u16));
            }
            &Inst::Mov64SImm16 { rd, imm } => {
                let opcode = 0xa79; // LGHI
                put(sink, &enc_ri_a(opcode, rd.to_reg(), imm as u16));
            }
            &Inst::Mov64SImm32 { rd, imm } => {
                let opcode = 0xc01; // LGFI
                put(sink, &enc_ril_a(opcode, rd.to_reg(), imm as u32));
            }
            &Inst::CMov32 { rd, cond, ri, rm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = 0xb9f2; // LOCR
                put(sink, &enc_rrf_cde(opcode, rd.to_reg(), rm, cond.bits(), 0));
            }
            &Inst::CMov64 { rd, cond, ri, rm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = 0xb9e2; // LOCGR
                put(sink, &enc_rrf_cde(opcode, rd.to_reg(), rm, cond.bits(), 0));
            }
            &Inst::CMov32SImm16 { rd, cond, ri, imm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = 0xec42; // LOCHI
                put(
                    sink,
                    &enc_rie_g(opcode, rd.to_reg(), imm as u16, cond.bits()),
                );
            }
            &Inst::CMov64SImm16 { rd, cond, ri, imm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = 0xec46; // LOCGHI
                put(
                    sink,
                    &enc_rie_g(opcode, rd.to_reg(), imm as u16, cond.bits()),
                );
            }
            &Inst::Mov64UImm16Shifted { rd, imm } => {
                let opcode = match imm.shift {
                    0 => 0xa5f, // LLILL
                    1 => 0xa5e, // LLILH
                    2 => 0xa5d, // LLIHL
                    3 => 0xa5c, // LLIHH
                    _ => unreachable!(),
                };
                put(sink, &enc_ri_a(opcode, rd.to_reg(), imm.bits));
            }
            &Inst::Mov64UImm32Shifted { rd, imm } => {
                let opcode = match imm.shift {
                    0 => 0xc0f, // LLILF
                    1 => 0xc0e, // LLIHF
                    _ => unreachable!(),
                };
                put(sink, &enc_ril_a(opcode, rd.to_reg(), imm.bits));
            }
            &Inst::Insert64UImm16Shifted { rd, ri, imm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match imm.shift {
                    0 => 0xa53, // IILL
                    1 => 0xa52, // IILH
                    2 => 0xa51, // IIHL
                    3 => 0xa50, // IIHH
                    _ => unreachable!(),
                };
                put(sink, &enc_ri_a(opcode, rd.to_reg(), imm.bits));
            }
            &Inst::Insert64UImm32Shifted { rd, ri, imm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match imm.shift {
                    0 => 0xc09, // IILF
                    1 => 0xc08, // IIHF
                    _ => unreachable!(),
                };
                put(sink, &enc_ril_a(opcode, rd.to_reg(), imm.bits));
            }
            &Inst::LoadAR { rd, ar } => {
                let opcode = 0xb24f; // EAR
                put(sink, &enc_rre(opcode, rd.to_reg(), gpr(ar)));
            }

            &Inst::InsertAR { rd, ri, ar } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = 0xb24f; // EAR
                put(sink, &enc_rre(opcode, rd.to_reg(), gpr(ar)));
            }
            &Inst::LoadSymbolReloc {
                rd,
                ref symbol_reloc,
            } => {
                let reg = writable_spilltmp_reg().to_reg();
                put(sink, &enc_ri_b(OPCODE_BRAS, reg, 12));
                let (reloc, name, offset) = match &**symbol_reloc {
                    SymbolReloc::Absolute { name, offset } => (Reloc::Abs8, name, *offset),
                    SymbolReloc::TlsGd { name } => (Reloc::S390xTlsGd64, name, 0),
                };
                sink.add_reloc(reloc, name, offset);
                sink.put8(0);
                let inst = Inst::Load64 {
                    rd,
                    mem: MemArg::reg(reg, MemFlags::trusted()),
                };
                inst.emit(sink, emit_info, state);
            }

            &Inst::FpuMove32 { rd, rn } => {
                if is_fpr(rd.to_reg()) && is_fpr(rn) {
                    let opcode = 0x38; // LER
                    put(sink, &enc_rr(opcode, rd.to_reg(), rn));
                } else {
                    put(sink, &enc_vrr_a(OPCODE_VLR, rd.to_reg(), rn, 0, 0, 0));
                }
            }
            &Inst::FpuMove64 { rd, rn } => {
                if is_fpr(rd.to_reg()) && is_fpr(rn) {
                    put(sink, &enc_rr(OPCODE_LDR, rd.to_reg(), rn));
                } else {
                    put(sink, &enc_vrr_a(OPCODE_VLR, rd.to_reg(), rn, 0, 0, 0));
                }
            }
            &Inst::FpuCMov32 { rd, cond, ri, rm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                if is_fpr(rd.to_reg()) && is_fpr(rm) {
                    put(sink, &enc_ri_c(OPCODE_BCR, cond.invert().bits(), 4 + 2));
                    let opcode = 0x38; // LER
                    put(sink, &enc_rr(opcode, rd.to_reg(), rm));
                } else {
                    put(sink, &enc_ri_c(OPCODE_BCR, cond.invert().bits(), 4 + 6));
                    put(sink, &enc_vrr_a(OPCODE_VLR, rd.to_reg(), rm, 0, 0, 0));
                }
            }
            &Inst::FpuCMov64 { rd, cond, ri, rm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                if is_fpr(rd.to_reg()) && is_fpr(rm) {
                    put(sink, &enc_ri_c(OPCODE_BCR, cond.invert().bits(), 4 + 2));
                    put(sink, &enc_rr(OPCODE_LDR, rd.to_reg(), rm));
                } else {
                    put(sink, &enc_ri_c(OPCODE_BCR, cond.invert().bits(), 4 + 6));
                    put(sink, &enc_vrr_a(OPCODE_VLR, rd.to_reg(), rm, 0, 0, 0));
                }
            }
            &Inst::FpuRR { fpu_op, rd, rn } => {
                let (opcode, m3, m4, m5, opcode_fpr) = match fpu_op {
                    FPUOp1::Abs32 => (0xe7cc, 2, 8, 2, Some(0xb300)), // WFPSO, LPEBR
                    FPUOp1::Abs64 => (0xe7cc, 3, 8, 2, Some(0xb310)), // WFPSO, LPDBR
                    FPUOp1::Abs128 => (0xe7cc, 4, 8, 2, None),        // WFPSO
                    FPUOp1::Abs32x4 => (0xe7cc, 2, 0, 2, None),       // VFPSO
                    FPUOp1::Abs64x2 => (0xe7cc, 3, 0, 2, None),       // VFPSO
                    FPUOp1::Neg32 => (0xe7cc, 2, 8, 0, Some(0xb303)), // WFPSO, LCEBR
                    FPUOp1::Neg64 => (0xe7cc, 3, 8, 0, Some(0xb313)), // WFPSO, LCDBR
                    FPUOp1::Neg128 => (0xe7cc, 4, 8, 0, None),        // WFPSO
                    FPUOp1::Neg32x4 => (0xe7cc, 2, 0, 0, None),       // VFPSO
                    FPUOp1::Neg64x2 => (0xe7cc, 3, 0, 0, None),       // VFPSO
                    FPUOp1::NegAbs32 => (0xe7cc, 2, 8, 1, Some(0xb301)), // WFPSO, LNEBR
                    FPUOp1::NegAbs64 => (0xe7cc, 3, 8, 1, Some(0xb311)), // WFPSO, LNDBR
                    FPUOp1::NegAbs128 => (0xe7cc, 4, 8, 1, None),     // WFPSO
                    FPUOp1::NegAbs32x4 => (0xe7cc, 2, 0, 1, None),    // VFPSO
                    FPUOp1::NegAbs64x2 => (0xe7cc, 3, 0, 1, None),    // VFPSO
                    FPUOp1::Sqrt32 => (0xe7ce, 2, 8, 0, Some(0xb314)), // WFSQ, SQEBR
                    FPUOp1::Sqrt64 => (0xe7ce, 3, 8, 0, Some(0xb315)), // WFSQ, SQDBR
                    FPUOp1::Sqrt128 => (0xe7ce, 4, 8, 0, None),       // WFSQ
                    FPUOp1::Sqrt32x4 => (0xe7ce, 2, 0, 0, None),      // VFSQ
                    FPUOp1::Sqrt64x2 => (0xe7ce, 3, 0, 0, None),      // VFSQ
                    FPUOp1::Cvt32To64 => (0xe7c4, 2, 8, 0, Some(0xb304)), // WFLL, LDEBR
                    FPUOp1::Cvt32x4To64x2 => (0xe7c4, 2, 0, 0, None), // VFLL
                    FPUOp1::Cvt64To128 => (0xe7c4, 3, 8, 0, None),    // WFLL
                };
                if m4 == 8 && opcode_fpr.is_some() && is_fpr(rd.to_reg()) && is_fpr(rn) {
                    put(sink, &enc_rre(opcode_fpr.unwrap(), rd.to_reg(), rn));
                } else {
                    put(sink, &enc_vrr_a(opcode, rd.to_reg(), rn, m3, m4, m5));
                }
            }
            &Inst::FpuRRR { fpu_op, rd, rn, rm } => {
                let (opcode, m4, m5, m6, opcode_fpr) = match fpu_op {
                    FPUOp2::Add32 => (0xe7e3, 2, 8, 0, Some(0xb30a)), // WFA, AEBR
                    FPUOp2::Add64 => (0xe7e3, 3, 8, 0, Some(0xb31a)), // WFA, ADBR
                    FPUOp2::Add128 => (0xe7e3, 4, 8, 0, None),        // WFA
                    FPUOp2::Add32x4 => (0xe7e3, 2, 0, 0, None),       // VFA
                    FPUOp2::Add64x2 => (0xe7e3, 3, 0, 0, None),       // VFA
                    FPUOp2::Sub32 => (0xe7e2, 2, 8, 0, Some(0xb30b)), // WFS, SEBR
                    FPUOp2::Sub64 => (0xe7e2, 3, 8, 0, Some(0xb31b)), // WFS, SDBR
                    FPUOp2::Sub128 => (0xe7e2, 4, 8, 0, None),        // WFS
                    FPUOp2::Sub32x4 => (0xe7e2, 2, 0, 0, None),       // VFS
                    FPUOp2::Sub64x2 => (0xe7e2, 3, 0, 0, None),       // VFS
                    FPUOp2::Mul32 => (0xe7e7, 2, 8, 0, Some(0xb317)), // WFM, MEEBR
                    FPUOp2::Mul64 => (0xe7e7, 3, 8, 0, Some(0xb31c)), // WFM, MDBR
                    FPUOp2::Mul128 => (0xe7e7, 4, 8, 0, None),        // WFM
                    FPUOp2::Mul32x4 => (0xe7e7, 2, 0, 0, None),       // VFM
                    FPUOp2::Mul64x2 => (0xe7e7, 3, 0, 0, None),       // VFM
                    FPUOp2::Div32 => (0xe7e5, 2, 8, 0, Some(0xb30d)), // WFD, DEBR
                    FPUOp2::Div64 => (0xe7e5, 3, 8, 0, Some(0xb31d)), // WFD, DDBR
                    FPUOp2::Div128 => (0xe7e5, 4, 8, 0, None),        // WFD
                    FPUOp2::Div32x4 => (0xe7e5, 2, 0, 0, None),       // VFD
                    FPUOp2::Div64x2 => (0xe7e5, 3, 0, 0, None),       // VFD
                    FPUOp2::Max32 => (0xe7ef, 2, 8, 1, None),         // WFMAX
                    FPUOp2::Max64 => (0xe7ef, 3, 8, 1, None),         // WFMAX
                    FPUOp2::Max128 => (0xe7ef, 4, 8, 1, None),        // WFMAX
                    FPUOp2::Max32x4 => (0xe7ef, 2, 0, 1, None),       // VFMAX
                    FPUOp2::Max64x2 => (0xe7ef, 3, 0, 1, None),       // VFMAX
                    FPUOp2::Min32 => (0xe7ee, 2, 8, 1, None),         // WFMIN
                    FPUOp2::Min64 => (0xe7ee, 3, 8, 1, None),         // WFMIN
                    FPUOp2::Min128 => (0xe7ee, 4, 8, 1, None),        // WFMIN
                    FPUOp2::Min32x4 => (0xe7ee, 2, 0, 1, None),       // VFMIN
                    FPUOp2::Min64x2 => (0xe7ee, 3, 0, 1, None),       // VFMIN
                    FPUOp2::MaxPseudo32 => (0xe7ef, 2, 8, 3, None),   // WFMAX
                    FPUOp2::MaxPseudo64 => (0xe7ef, 3, 8, 3, None),   // WFMAX
                    FPUOp2::MaxPseudo128 => (0xe7ef, 4, 8, 3, None),  // WFMAX
                    FPUOp2::MaxPseudo32x4 => (0xe7ef, 2, 0, 3, None), // VFMAX
                    FPUOp2::MaxPseudo64x2 => (0xe7ef, 3, 0, 3, None), // VFMAX
                    FPUOp2::MinPseudo32 => (0xe7ee, 2, 8, 3, None),   // WFMIN
                    FPUOp2::MinPseudo64 => (0xe7ee, 3, 8, 3, None),   // WFMIN
                    FPUOp2::MinPseudo128 => (0xe7ee, 4, 8, 3, None),  // WFMIN
                    FPUOp2::MinPseudo32x4 => (0xe7ee, 2, 0, 3, None), // VFMIN
                    FPUOp2::MinPseudo64x2 => (0xe7ee, 3, 0, 3, None), // VFMIN
                };
                if m5 == 8 && opcode_fpr.is_some() && rd.to_reg() == rn && is_fpr(rn) && is_fpr(rm)
                {
                    put(sink, &enc_rre(opcode_fpr.unwrap(), rd.to_reg(), rm));
                } else {
                    put(sink, &enc_vrr_c(opcode, rd.to_reg(), rn, rm, m4, m5, m6));
                }
            }
            &Inst::FpuRRRR {
                fpu_op,
                rd,
                rn,
                rm,
                ra,
            } => {
                let (opcode, m5, m6, opcode_fpr) = match fpu_op {
                    FPUOp3::MAdd32 => (0xe78f, 8, 2, Some(0xb30e)), // WFMA, MAEBR
                    FPUOp3::MAdd64 => (0xe78f, 8, 3, Some(0xb31e)), // WFMA, MADBR
                    FPUOp3::MAdd128 => (0xe78f, 8, 4, None),        // WFMA
                    FPUOp3::MAdd32x4 => (0xe78f, 0, 2, None),       // VFMA
                    FPUOp3::MAdd64x2 => (0xe78f, 0, 3, None),       // VFMA
                    FPUOp3::MSub32 => (0xe78e, 8, 2, Some(0xb30f)), // WFMS, MSEBR
                    FPUOp3::MSub64 => (0xe78e, 8, 3, Some(0xb31f)), // WFMS, MSDBR
                    FPUOp3::MSub128 => (0xe78e, 8, 4, None),        // WFMS
                    FPUOp3::MSub32x4 => (0xe78e, 0, 2, None),       // VFMS
                    FPUOp3::MSub64x2 => (0xe78e, 0, 3, None),       // VFMS
                };
                if m5 == 8
                    && opcode_fpr.is_some()
                    && rd.to_reg() == ra
                    && is_fpr(rn)
                    && is_fpr(rm)
                    && is_fpr(ra)
                {
                    put(sink, &enc_rrd(opcode_fpr.unwrap(), rd.to_reg(), rm, rn));
                } else {
                    put(sink, &enc_vrr_e(opcode, rd.to_reg(), rn, rm, ra, m5, m6));
                }
            }
            &Inst::FpuRound { op, mode, rd, rn } => {
                let mode = match mode {
                    FpuRoundMode::Current => 0,
                    FpuRoundMode::ToNearest => 1,
                    FpuRoundMode::ShorterPrecision => 3,
                    FpuRoundMode::ToNearestTiesToEven => 4,
                    FpuRoundMode::ToZero => 5,
                    FpuRoundMode::ToPosInfinity => 6,
                    FpuRoundMode::ToNegInfinity => 7,
                };
                let (opcode, m3, m4, opcode_fpr) = match op {
                    FpuRoundOp::Cvt64To32 => (0xe7c5, 3, 8, Some(0xb344)), // WFLR, LEDBR(A)
                    FpuRoundOp::Cvt64x2To32x4 => (0xe7c5, 3, 0, None),     // VFLR
                    FpuRoundOp::Cvt128To64 => (0xe7c5, 4, 8, None),        // WFLR
                    FpuRoundOp::Round32 => (0xe7c7, 2, 8, Some(0xb357)),   // WFI, FIEBR
                    FpuRoundOp::Round64 => (0xe7c7, 3, 8, Some(0xb35f)),   // WFI, FIDBR
                    FpuRoundOp::Round128 => (0xe7c7, 4, 8, None),          // WFI
                    FpuRoundOp::Round32x4 => (0xe7c7, 2, 0, None),         // VFI
                    FpuRoundOp::Round64x2 => (0xe7c7, 3, 0, None),         // VFI
                    FpuRoundOp::ToSInt32 => (0xe7c2, 2, 8, None),          // WCSFP
                    FpuRoundOp::ToSInt64 => (0xe7c2, 3, 8, None),          // WCSFP
                    FpuRoundOp::ToUInt32 => (0xe7c0, 2, 8, None),          // WCLFP
                    FpuRoundOp::ToUInt64 => (0xe7c0, 3, 8, None),          // WCLFP
                    FpuRoundOp::ToSInt32x4 => (0xe7c2, 2, 0, None),        // VCSFP
                    FpuRoundOp::ToSInt64x2 => (0xe7c2, 3, 0, None),        // VCSFP
                    FpuRoundOp::ToUInt32x4 => (0xe7c0, 2, 0, None),        // VCLFP
                    FpuRoundOp::ToUInt64x2 => (0xe7c0, 3, 0, None),        // VCLFP
                    FpuRoundOp::FromSInt32 => (0xe7c3, 2, 8, None),        // WCFPS
                    FpuRoundOp::FromSInt64 => (0xe7c3, 3, 8, None),        // WCFPS
                    FpuRoundOp::FromUInt32 => (0xe7c1, 2, 8, None),        // WCFPL
                    FpuRoundOp::FromUInt64 => (0xe7c1, 3, 8, None),        // WCFPL
                    FpuRoundOp::FromSInt32x4 => (0xe7c3, 2, 0, None),      // VCFPS
                    FpuRoundOp::FromSInt64x2 => (0xe7c3, 3, 0, None),      // VCFPS
                    FpuRoundOp::FromUInt32x4 => (0xe7c1, 2, 0, None),      // VCFPL
                    FpuRoundOp::FromUInt64x2 => (0xe7c1, 3, 0, None),      // VCFPL
                };
                if m4 == 8 && opcode_fpr.is_some() && is_fpr(rd.to_reg()) && is_fpr(rn) {
                    put(
                        sink,
                        &enc_rrf_cde(opcode_fpr.unwrap(), rd.to_reg(), rn, mode, 0),
                    );
                } else {
                    put(sink, &enc_vrr_a(opcode, rd.to_reg(), rn, m3, m4, mode));
                }
            }
            &Inst::FpuConv128FromInt { op, mode, rd, rn } => {
                let rd1 = rd.hi;
                let rd2 = rd.lo;
                debug_assert_valid_fp_regpair!(rd1.to_reg(), rd2.to_reg());

                let mode = match mode {
                    FpuRoundMode::Current => 0,
                    FpuRoundMode::ToNearest => 1,
                    FpuRoundMode::ShorterPrecision => 3,
                    FpuRoundMode::ToNearestTiesToEven => 4,
                    FpuRoundMode::ToZero => 5,
                    FpuRoundMode::ToPosInfinity => 6,
                    FpuRoundMode::ToNegInfinity => 7,
                };
                let opcode = match op {
                    FpuConv128Op::SInt32 => 0xb396, // CXFBRA
                    FpuConv128Op::SInt64 => 0xb3a6, // CXGBRA
                    FpuConv128Op::UInt32 => 0xb392, // CXLFBR
                    FpuConv128Op::UInt64 => 0xb3a2, // CXLGBR
                };
                put(sink, &enc_rrf_cde(opcode, rd1.to_reg(), rn, mode, 0));
            }
            &Inst::FpuConv128ToInt { op, mode, rd, rn } => {
                let rn1 = rn.hi;
                let rn2 = rn.lo;
                debug_assert_valid_fp_regpair!(rn1, rn2);

                let mode = match mode {
                    FpuRoundMode::Current => 0,
                    FpuRoundMode::ToNearest => 1,
                    FpuRoundMode::ShorterPrecision => 3,
                    FpuRoundMode::ToNearestTiesToEven => 4,
                    FpuRoundMode::ToZero => 5,
                    FpuRoundMode::ToPosInfinity => 6,
                    FpuRoundMode::ToNegInfinity => 7,
                };
                let opcode = match op {
                    FpuConv128Op::SInt32 => 0xb39a, // CFXBRA
                    FpuConv128Op::SInt64 => 0xb3aa, // CGXBRA
                    FpuConv128Op::UInt32 => 0xb39e, // CLFXBR
                    FpuConv128Op::UInt64 => 0xb3ae, // CLGXBR
                };
                put(sink, &enc_rrf_cde(opcode, rd.to_reg(), rn1, mode, 0));
            }
            &Inst::FpuCmp32 { rn, rm } => {
                if is_fpr(rn) && is_fpr(rm) {
                    let opcode = 0xb309; // CEBR
                    put(sink, &enc_rre(opcode, rn, rm));
                } else {
                    let opcode = 0xe7cb; // WFC
                    put(sink, &enc_vrr_a(opcode, rn, rm, 2, 0, 0));
                }
            }
            &Inst::FpuCmp64 { rn, rm } => {
                if is_fpr(rn) && is_fpr(rm) {
                    let opcode = 0xb319; // CDBR
                    put(sink, &enc_rre(opcode, rn, rm));
                } else {
                    let opcode = 0xe7cb; // WFC
                    put(sink, &enc_vrr_a(opcode, rn, rm, 3, 0, 0));
                }
            }
            &Inst::FpuCmp128 { rn, rm } => {
                let opcode = 0xe7cb; // WFC
                put(sink, &enc_vrr_a(opcode, rn, rm, 4, 0, 0));
            }

            &Inst::VecRRR { op, rd, rn, rm } => {
                let (opcode, m4) = match op {
                    VecBinaryOp::Add8x16 => (0xe7f3, 0),       // VAB
                    VecBinaryOp::Add16x8 => (0xe7f3, 1),       // VAH
                    VecBinaryOp::Add32x4 => (0xe7f3, 2),       // VAF
                    VecBinaryOp::Add64x2 => (0xe7f3, 3),       // VAG
                    VecBinaryOp::Add128 => (0xe7f3, 4),        // VAQ
                    VecBinaryOp::Sub8x16 => (0xe7f7, 0),       // VSB
                    VecBinaryOp::Sub16x8 => (0xe7f7, 1),       // VSH
                    VecBinaryOp::Sub32x4 => (0xe7f7, 2),       // VSF
                    VecBinaryOp::Sub64x2 => (0xe7f7, 3),       // VSG
                    VecBinaryOp::Sub128 => (0xe7f7, 4),        // VSQ
                    VecBinaryOp::Mul8x16 => (0xe7a2, 0),       // VMLB
                    VecBinaryOp::Mul16x8 => (0xe7a2, 1),       // VMLHW
                    VecBinaryOp::Mul32x4 => (0xe7a2, 2),       // VMLF
                    VecBinaryOp::Mul64x2 => (0xe7a2, 3),       // VMLG
                    VecBinaryOp::Mul128 => (0xe7a2, 4),        // VMLQ
                    VecBinaryOp::UMulHi8x16 => (0xe7a1, 0),    // VMLHB
                    VecBinaryOp::UMulHi16x8 => (0xe7a1, 1),    // VMLHH
                    VecBinaryOp::UMulHi32x4 => (0xe7a1, 2),    // VMLHF
                    VecBinaryOp::UMulHi64x2 => (0xe7a1, 3),    // VMLHG
                    VecBinaryOp::UMulHi128 => (0xe7a1, 4),     // VMLHQ
                    VecBinaryOp::SMulHi8x16 => (0xe7a3, 0),    // VMHB
                    VecBinaryOp::SMulHi16x8 => (0xe7a3, 1),    // VMHH
                    VecBinaryOp::SMulHi32x4 => (0xe7a3, 2),    // VMHF
                    VecBinaryOp::SMulHi64x2 => (0xe7a3, 3),    // VMHG
                    VecBinaryOp::SMulHi128 => (0xe7a3, 4),     // VMHQ
                    VecBinaryOp::UMulEven8x16 => (0xe7a4, 0),  // VMLEB
                    VecBinaryOp::UMulEven16x8 => (0xe7a4, 1),  // VMLEH
                    VecBinaryOp::UMulEven32x4 => (0xe7a4, 2),  // VMLEF
                    VecBinaryOp::UMulEven64x2 => (0xe7a4, 3),  // VMLEG
                    VecBinaryOp::SMulEven8x16 => (0xe7a6, 0),  // VMEB
                    VecBinaryOp::SMulEven16x8 => (0xe7a6, 1),  // VMEH
                    VecBinaryOp::SMulEven32x4 => (0xe7a6, 2),  // VMEF
                    VecBinaryOp::SMulEven64x2 => (0xe7a6, 3),  // VMEG
                    VecBinaryOp::UMulOdd8x16 => (0xe7a5, 0),   // VMLOB
                    VecBinaryOp::UMulOdd16x8 => (0xe7a5, 1),   // VMLOH
                    VecBinaryOp::UMulOdd32x4 => (0xe7a5, 2),   // VMLOF
                    VecBinaryOp::UMulOdd64x2 => (0xe7a5, 3),   // VMLOG
                    VecBinaryOp::SMulOdd8x16 => (0xe7a7, 0),   // VMOB
                    VecBinaryOp::SMulOdd16x8 => (0xe7a7, 1),   // VMOH
                    VecBinaryOp::SMulOdd32x4 => (0xe7a7, 2),   // VMOF
                    VecBinaryOp::SMulOdd64x2 => (0xe7a7, 3),   // VMOG
                    VecBinaryOp::UDiv32x4 => (0xe7b0, 2),      // VDLF
                    VecBinaryOp::UDiv64x2 => (0xe7b0, 3),      // VDLG
                    VecBinaryOp::UDiv128 => (0xe7b0, 4),       // VDLQ
                    VecBinaryOp::SDiv32x4 => (0xe7b2, 2),      // VDF
                    VecBinaryOp::SDiv64x2 => (0xe7b2, 3),      // VDG
                    VecBinaryOp::SDiv128 => (0xe7b2, 4),       // VDQ
                    VecBinaryOp::URem32x4 => (0xe7b1, 2),      // VRLF
                    VecBinaryOp::URem64x2 => (0xe7b1, 3),      // VRLG
                    VecBinaryOp::URem128 => (0xe7b1, 4),       // VRLQ
                    VecBinaryOp::SRem32x4 => (0xe7b3, 2),      // VRF
                    VecBinaryOp::SRem64x2 => (0xe7b3, 3),      // VRG
                    VecBinaryOp::SRem128 => (0xe7b3, 4),       // VRQ
                    VecBinaryOp::UMax8x16 => (0xe7fd, 0),      // VMXLB
                    VecBinaryOp::UMax16x8 => (0xe7fd, 1),      // VMXLH
                    VecBinaryOp::UMax32x4 => (0xe7fd, 2),      // VMXLF
                    VecBinaryOp::UMax64x2 => (0xe7fd, 3),      // VMXLG
                    VecBinaryOp::UMax128 => (0xe7fd, 4),       // VMXLQ
                    VecBinaryOp::SMax8x16 => (0xe7ff, 0),      // VMXB
                    VecBinaryOp::SMax16x8 => (0xe7ff, 1),      // VMXH
                    VecBinaryOp::SMax32x4 => (0xe7ff, 2),      // VMXF
                    VecBinaryOp::SMax64x2 => (0xe7ff, 3),      // VMXG
                    VecBinaryOp::SMax128 => (0xe7ff, 4),       // VMXQ
                    VecBinaryOp::UMin8x16 => (0xe7fc, 0),      // VMNLB
                    VecBinaryOp::UMin16x8 => (0xe7fc, 1),      // VMNLH
                    VecBinaryOp::UMin32x4 => (0xe7fc, 2),      // VMNLF
                    VecBinaryOp::UMin64x2 => (0xe7fc, 3),      // VMNLG
                    VecBinaryOp::UMin128 => (0xe7fc, 4),       // VMNLQ
                    VecBinaryOp::SMin8x16 => (0xe7fe, 0),      // VMNB
                    VecBinaryOp::SMin16x8 => (0xe7fe, 1),      // VMNH
                    VecBinaryOp::SMin32x4 => (0xe7fe, 2),      // VMNF
                    VecBinaryOp::SMin64x2 => (0xe7fe, 3),      // VMNG
                    VecBinaryOp::SMin128 => (0xe7fe, 4),       // VMNQ
                    VecBinaryOp::UAvg8x16 => (0xe7f0, 0),      // VAVGLB
                    VecBinaryOp::UAvg16x8 => (0xe7f0, 1),      // VAVGLH
                    VecBinaryOp::UAvg32x4 => (0xe7f0, 2),      // VAVGLF
                    VecBinaryOp::UAvg64x2 => (0xe7f0, 3),      // VAVGLG
                    VecBinaryOp::UAvg128 => (0xe7f0, 4),       // VAVGLQ
                    VecBinaryOp::SAvg8x16 => (0xe7f2, 0),      // VAVGB
                    VecBinaryOp::SAvg16x8 => (0xe7f2, 1),      // VAVGH
                    VecBinaryOp::SAvg32x4 => (0xe7f2, 2),      // VAVGF
                    VecBinaryOp::SAvg64x2 => (0xe7f2, 3),      // VAVGG
                    VecBinaryOp::SAvg128 => (0xe7f2, 4),       // VAVGQ
                    VecBinaryOp::And128 => (0xe768, 0),        // VN
                    VecBinaryOp::Orr128 => (0xe76a, 0),        // VO
                    VecBinaryOp::Xor128 => (0xe76d, 0),        // VX
                    VecBinaryOp::NotAnd128 => (0xe76e, 0),     // VNN
                    VecBinaryOp::NotOrr128 => (0xe76b, 0),     // VNO
                    VecBinaryOp::NotXor128 => (0xe76c, 0),     // VNX
                    VecBinaryOp::AndNot128 => (0xe769, 0),     // VNC
                    VecBinaryOp::OrrNot128 => (0xe76f, 0),     // VOC
                    VecBinaryOp::BitPermute128 => (0xe785, 0), // VBPERM
                    VecBinaryOp::LShLByByte128 => (0xe775, 0), // VSLB
                    VecBinaryOp::LShRByByte128 => (0xe77d, 0), // VSRLB
                    VecBinaryOp::AShRByByte128 => (0xe77f, 0), // VSRAB
                    VecBinaryOp::LShLByBit128 => (0xe774, 0),  // VSL
                    VecBinaryOp::LShRByBit128 => (0xe77c, 0),  // VSRL
                    VecBinaryOp::AShRByBit128 => (0xe77e, 0),  // VSRA
                    VecBinaryOp::Pack16x8 => (0xe794, 1),      // VPKH
                    VecBinaryOp::Pack32x4 => (0xe794, 2),      // VPKF
                    VecBinaryOp::Pack64x2 => (0xe794, 3),      // VPKG
                    VecBinaryOp::PackUSat16x8 => (0xe795, 1),  // VPKLSH
                    VecBinaryOp::PackUSat32x4 => (0xe795, 2),  // VPKLSF
                    VecBinaryOp::PackUSat64x2 => (0xe795, 3),  // VPKLSG
                    VecBinaryOp::PackSSat16x8 => (0xe797, 1),  // VPKSH
                    VecBinaryOp::PackSSat32x4 => (0xe797, 2),  // VPKSF
                    VecBinaryOp::PackSSat64x2 => (0xe797, 3),  // VPKSG
                    VecBinaryOp::MergeLow8x16 => (0xe760, 0),  // VMRLB
                    VecBinaryOp::MergeLow16x8 => (0xe760, 1),  // VMRLH
                    VecBinaryOp::MergeLow32x4 => (0xe760, 2),  // VMRLF
                    VecBinaryOp::MergeLow64x2 => (0xe760, 3),  // VMRLG
                    VecBinaryOp::MergeHigh8x16 => (0xe761, 0), // VMRHB
                    VecBinaryOp::MergeHigh16x8 => (0xe761, 1), // VMRHH
                    VecBinaryOp::MergeHigh32x4 => (0xe761, 2), // VMRHF
                    VecBinaryOp::MergeHigh64x2 => (0xe761, 3), // VMRHG
                };

                let enc = &enc_vrr_c(opcode, rd.to_reg(), rn, rm, m4, 0, 0);
                let may_trap = match op {
                    VecBinaryOp::UDiv32x4
                    | VecBinaryOp::UDiv64x2
                    | VecBinaryOp::UDiv128
                    | VecBinaryOp::SDiv32x4
                    | VecBinaryOp::SDiv64x2
                    | VecBinaryOp::SDiv128
                    | VecBinaryOp::URem32x4
                    | VecBinaryOp::URem64x2
                    | VecBinaryOp::URem128
                    | VecBinaryOp::SRem32x4
                    | VecBinaryOp::SRem64x2
                    | VecBinaryOp::SRem128 => true,
                    _ => false,
                };
                if may_trap {
                    put_with_trap(sink, enc, TrapCode::INTEGER_DIVISION_BY_ZERO);
                } else {
                    put(sink, enc);
                }
            }
            &Inst::VecRR { op, rd, rn } => {
                let (opcode, m3) = match op {
                    VecUnaryOp::Abs8x16 => (0xe7df, 0),         // VLPB
                    VecUnaryOp::Abs16x8 => (0xe7df, 1),         // VLPH
                    VecUnaryOp::Abs32x4 => (0xe7df, 2),         // VLPF
                    VecUnaryOp::Abs64x2 => (0xe7df, 3),         // VLPG
                    VecUnaryOp::Abs128 => (0xe7df, 4),          // VLPQ
                    VecUnaryOp::Neg8x16 => (0xe7de, 0),         // VLCB
                    VecUnaryOp::Neg16x8 => (0xe7de, 1),         // VLCH
                    VecUnaryOp::Neg32x4 => (0xe7de, 2),         // VLCF
                    VecUnaryOp::Neg64x2 => (0xe7de, 3),         // VLCG
                    VecUnaryOp::Neg128 => (0xe7de, 4),          // VLCQ
                    VecUnaryOp::Popcnt8x16 => (0xe750, 0),      // VPOPCTB
                    VecUnaryOp::Popcnt16x8 => (0xe750, 1),      // VPOPCTH
                    VecUnaryOp::Popcnt32x4 => (0xe750, 2),      // VPOPCTF
                    VecUnaryOp::Popcnt64x2 => (0xe750, 3),      // VPOPCTG
                    VecUnaryOp::Clz8x16 => (0xe753, 0),         // VCLZB
                    VecUnaryOp::Clz16x8 => (0xe753, 1),         // VCLZH
                    VecUnaryOp::Clz32x4 => (0xe753, 2),         // VCLZF
                    VecUnaryOp::Clz64x2 => (0xe753, 3),         // VCLZG
                    VecUnaryOp::Clz128 => (0xe753, 4),          // VCLZQ
                    VecUnaryOp::Ctz8x16 => (0xe752, 0),         // VCTZB
                    VecUnaryOp::Ctz16x8 => (0xe752, 1),         // VCTZH
                    VecUnaryOp::Ctz32x4 => (0xe752, 2),         // VCTZF
                    VecUnaryOp::Ctz64x2 => (0xe752, 3),         // VCTZG
                    VecUnaryOp::Ctz128 => (0xe752, 4),          // VCTZQ
                    VecUnaryOp::UnpackULow8x16 => (0xe7d4, 0),  // VUPLLB
                    VecUnaryOp::UnpackULow16x8 => (0xe7d4, 1),  // VUPLLH
                    VecUnaryOp::UnpackULow32x4 => (0xe7d4, 2),  // VUPLLF
                    VecUnaryOp::UnpackULow64x2 => (0xe7d4, 3),  // VUPLLG
                    VecUnaryOp::UnpackUHigh8x16 => (0xe7d5, 0), // VUPLHB
                    VecUnaryOp::UnpackUHigh16x8 => (0xe7d5, 1), // VUPLHH
                    VecUnaryOp::UnpackUHigh32x4 => (0xe7d5, 2), // VUPLHF
                    VecUnaryOp::UnpackUHigh64x2 => (0xe7d5, 3), // VUPLHG
                    VecUnaryOp::UnpackSLow8x16 => (0xe7d6, 0),  // VUPLB
                    VecUnaryOp::UnpackSLow16x8 => (0xe7d6, 1),  // VUPLH
                    VecUnaryOp::UnpackSLow32x4 => (0xe7d6, 2),  // VUPLF
                    VecUnaryOp::UnpackSLow64x2 => (0xe7d6, 3),  // VUPLG
                    VecUnaryOp::UnpackSHigh8x16 => (0xe7d7, 0), // VUPHB
                    VecUnaryOp::UnpackSHigh16x8 => (0xe7d7, 1), // VUPHH
                    VecUnaryOp::UnpackSHigh32x4 => (0xe7d7, 2), // VUPHF
                    VecUnaryOp::UnpackSHigh64x2 => (0xe7d7, 3), // VUPHG
                };

                put(sink, &enc_vrr_a(opcode, rd.to_reg(), rn, m3, 0, 0));
            }
            &Inst::VecShiftRR {
                shift_op,
                rd,
                rn,
                shift_imm,
                shift_reg,
            } => {
                let (opcode, m4) = match shift_op {
                    VecShiftOp::RotL8x16 => (0xe733, 0), // VERLLB
                    VecShiftOp::RotL16x8 => (0xe733, 1), // VERLLH
                    VecShiftOp::RotL32x4 => (0xe733, 2), // VERLLF
                    VecShiftOp::RotL64x2 => (0xe733, 3), // VERLLG
                    VecShiftOp::LShL8x16 => (0xe730, 0), // VESLB
                    VecShiftOp::LShL16x8 => (0xe730, 1), // VESLH
                    VecShiftOp::LShL32x4 => (0xe730, 2), // VESLF
                    VecShiftOp::LShL64x2 => (0xe730, 3), // VESLG
                    VecShiftOp::LShR8x16 => (0xe738, 0), // VESRLB
                    VecShiftOp::LShR16x8 => (0xe738, 1), // VESRLH
                    VecShiftOp::LShR32x4 => (0xe738, 2), // VESRLF
                    VecShiftOp::LShR64x2 => (0xe738, 3), // VESRLG
                    VecShiftOp::AShR8x16 => (0xe73a, 0), // VESRAB
                    VecShiftOp::AShR16x8 => (0xe73a, 1), // VESRAH
                    VecShiftOp::AShR32x4 => (0xe73a, 2), // VESRAF
                    VecShiftOp::AShR64x2 => (0xe73a, 3), // VESRAG
                };
                put(
                    sink,
                    &enc_vrs_a(opcode, rd.to_reg(), shift_reg, shift_imm.into(), rn, m4),
                );
            }
            &Inst::VecSelect { rd, rn, rm, ra } => {
                let opcode = 0xe78d; // VSEL
                put(sink, &enc_vrr_e(opcode, rd.to_reg(), rn, rm, ra, 0, 0));
            }
            &Inst::VecPermute { rd, rn, rm, ra } => {
                let opcode = 0xe78c; // VPERM
                put(sink, &enc_vrr_e(opcode, rd.to_reg(), rn, rm, ra, 0, 0));
            }
            &Inst::VecBlend { rd, rn, rm, ra } => {
                let opcode = 0xe789; // VBLEND
                put(sink, &enc_vrr_d(opcode, rd.to_reg(), rn, rm, ra, 0, 0));
            }
            &Inst::VecEvaluate {
                imm,
                rd,
                rn,
                rm,
                ra,
            } => {
                let opcode = 0xe788; //VEVAL
                put(sink, &enc_vri_k(opcode, imm, rd.to_reg(), rn, rm, ra));
            }
            &Inst::VecPermuteDWImm {
                rd,
                rn,
                rm,
                idx1,
                idx2,
            } => {
                let m4 = (idx1 & 1) * 4 + (idx2 & 1);

                let opcode = 0xe784; // VPDI
                put(sink, &enc_vrr_c(opcode, rd.to_reg(), rn, rm, m4, 0, 0));
            }
            &Inst::VecIntCmp { op, rd, rn, rm } | &Inst::VecIntCmpS { op, rd, rn, rm } => {
                let (opcode, m4) = match op {
                    VecIntCmpOp::CmpEq8x16 => (0xe7f8, 0),  // VCEQB
                    VecIntCmpOp::CmpEq16x8 => (0xe7f8, 1),  // VCEQH
                    VecIntCmpOp::CmpEq32x4 => (0xe7f8, 2),  // VCEQF
                    VecIntCmpOp::CmpEq64x2 => (0xe7f8, 3),  // VCEQG
                    VecIntCmpOp::CmpEq128 => (0xe7f8, 4),   // VCEQQ
                    VecIntCmpOp::SCmpHi8x16 => (0xe7fb, 0), // VCHB
                    VecIntCmpOp::SCmpHi16x8 => (0xe7fb, 1), // VCHH
                    VecIntCmpOp::SCmpHi32x4 => (0xe7fb, 2), // VCHG
                    VecIntCmpOp::SCmpHi64x2 => (0xe7fb, 3), // VCHG
                    VecIntCmpOp::SCmpHi128 => (0xe7fb, 4),  // VCHQ
                    VecIntCmpOp::UCmpHi8x16 => (0xe7f9, 0), // VCHLB
                    VecIntCmpOp::UCmpHi16x8 => (0xe7f9, 1), // VCHLH
                    VecIntCmpOp::UCmpHi32x4 => (0xe7f9, 2), // VCHLG
                    VecIntCmpOp::UCmpHi64x2 => (0xe7f9, 3), // VCHLG
                    VecIntCmpOp::UCmpHi128 => (0xe7f9, 4),  // VCHLQ
                };
                let m5 = match self {
                    &Inst::VecIntCmp { .. } => 0,
                    &Inst::VecIntCmpS { .. } => 1,
                    _ => unreachable!(),
                };

                put(sink, &enc_vrr_b(opcode, rd.to_reg(), rn, rm, m4, m5));
            }
            &Inst::VecFloatCmp { op, rd, rn, rm } | &Inst::VecFloatCmpS { op, rd, rn, rm } => {
                let (opcode, m4) = match op {
                    VecFloatCmpOp::CmpEq32x4 => (0xe7e8, 2),   // VFCESB
                    VecFloatCmpOp::CmpEq64x2 => (0xe7e8, 3),   // VFCEDB
                    VecFloatCmpOp::CmpHi32x4 => (0xe7eb, 2),   // VFCHSB
                    VecFloatCmpOp::CmpHi64x2 => (0xe7eb, 3),   // VFCHDB
                    VecFloatCmpOp::CmpHiEq32x4 => (0xe7ea, 2), // VFCHESB
                    VecFloatCmpOp::CmpHiEq64x2 => (0xe7ea, 3), // VFCHEDB
                };
                let m6 = match self {
                    &Inst::VecFloatCmp { .. } => 0,
                    &Inst::VecFloatCmpS { .. } => 1,
                    _ => unreachable!(),
                };

                put(sink, &enc_vrr_c(opcode, rd.to_reg(), rn, rm, m4, 0, m6));
            }
            &Inst::VecIntEltCmp { op, rn, rm } => {
                let (opcode, m3) = match op {
                    VecIntEltCmpOp::SCmp128 => (0xe7db, 4), // VECQ
                    VecIntEltCmpOp::UCmp128 => (0xe7d9, 4), // VECLQ
                };

                put(sink, &enc_vrr_a(opcode, rn, rm, m3, 0, 0));
            }
            &Inst::VecInt128SCmpHi { tmp, rn, rm } | &Inst::VecInt128UCmpHi { tmp, rn, rm } => {
                // Synthetic instruction to compare 128-bit values.
                // Sets CC 1 if rn > rm, sets a different CC otherwise.

                // Use VECTOR ELEMENT COMPARE to compare the high parts.
                // Swap the inputs to get:
                //    CC 1 if high(rn) > high(rm)
                //    CC 2 if high(rn) < high(rm)
                //    CC 0 if high(rn) == high(rm)
                let (opcode, m3) = match self {
                    &Inst::VecInt128SCmpHi { .. } => (0xe7db, 3), // VECG
                    &Inst::VecInt128UCmpHi { .. } => (0xe7d9, 3), // VECLG
                    _ => unreachable!(),
                };
                put(sink, &enc_vrr_a(opcode, rm, rn, m3, 0, 0));

                // If CC != 0, we'd done, so jump over the next instruction.
                put(sink, &enc_ri_c(OPCODE_BCR, 7, 4 + 6));

                // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
                // Since we already know the high parts are equal, the CC
                // result will only depend on the low parts:
                //     CC 1 if low(rn) > low(rm)
                //     CC 3 if low(rn) <= low(rm)
                let inst = Inst::VecIntCmpS {
                    op: VecIntCmpOp::UCmpHi64x2,
                    // N.B.: This is the first write to tmp, and it happens
                    // after all uses of rn and rm.  If this were to ever
                    // change, tmp would have to become an early-def.
                    rd: tmp,
                    rn,
                    rm,
                };
                inst.emit(sink, emit_info, state);
            }

            &Inst::VecLoad { rd, ref mem }
            | &Inst::VecLoadRev { rd, ref mem }
            | &Inst::VecLoadByte16Rev { rd, ref mem }
            | &Inst::VecLoadByte32Rev { rd, ref mem }
            | &Inst::VecLoadByte64Rev { rd, ref mem }
            | &Inst::VecLoadElt16Rev { rd, ref mem }
            | &Inst::VecLoadElt32Rev { rd, ref mem }
            | &Inst::VecLoadElt64Rev { rd, ref mem } => {
                let mem = mem.clone();

                let (opcode, m3) = match self {
                    &Inst::VecLoad { .. } => (0xe706, 0),          // VL
                    &Inst::VecLoadRev { .. } => (0xe606, 4),       // VLBRQ
                    &Inst::VecLoadByte16Rev { .. } => (0xe606, 1), // VLBRH
                    &Inst::VecLoadByte32Rev { .. } => (0xe606, 2), // VLBRF
                    &Inst::VecLoadByte64Rev { .. } => (0xe606, 3), // VLBRG
                    &Inst::VecLoadElt16Rev { .. } => (0xe607, 1),  // VLERH
                    &Inst::VecLoadElt32Rev { .. } => (0xe607, 2),  // VLERF
                    &Inst::VecLoadElt64Rev { .. } => (0xe607, 3),  // VLERG
                    _ => unreachable!(),
                };
                mem_vrx_emit(rd.to_reg(), &mem, opcode, m3, true, sink, emit_info, state);
            }
            &Inst::VecStore { rd, ref mem }
            | &Inst::VecStoreRev { rd, ref mem }
            | &Inst::VecStoreByte16Rev { rd, ref mem }
            | &Inst::VecStoreByte32Rev { rd, ref mem }
            | &Inst::VecStoreByte64Rev { rd, ref mem }
            | &Inst::VecStoreElt16Rev { rd, ref mem }
            | &Inst::VecStoreElt32Rev { rd, ref mem }
            | &Inst::VecStoreElt64Rev { rd, ref mem } => {
                let mem = mem.clone();

                let (opcode, m3) = match self {
                    &Inst::VecStore { .. } => (0xe70e, 0),          // VST
                    &Inst::VecStoreRev { .. } => (0xe60e, 4),       // VSTBRQ
                    &Inst::VecStoreByte16Rev { .. } => (0xe60e, 1), // VSTBRH
                    &Inst::VecStoreByte32Rev { .. } => (0xe60e, 2), // VSTBRF
                    &Inst::VecStoreByte64Rev { .. } => (0xe60e, 3), // VSTBRG
                    &Inst::VecStoreElt16Rev { .. } => (0xe60f, 1),  // VSTERH
                    &Inst::VecStoreElt32Rev { .. } => (0xe60f, 2),  // VSTERF
                    &Inst::VecStoreElt64Rev { .. } => (0xe60f, 3),  // VSTERG
                    _ => unreachable!(),
                };
                mem_vrx_emit(rd, &mem, opcode, m3, true, sink, emit_info, state);
            }
            &Inst::VecLoadReplicate { size, rd, ref mem }
            | &Inst::VecLoadReplicateRev { size, rd, ref mem } => {
                let mem = mem.clone();

                let (opcode, m3) = match (self, size) {
                    (&Inst::VecLoadReplicate { .. }, 8) => (0xe705, 0), // VLREPB
                    (&Inst::VecLoadReplicate { .. }, 16) => (0xe705, 1), // VLREPH
                    (&Inst::VecLoadReplicate { .. }, 32) => (0xe705, 2), // VLREPF
                    (&Inst::VecLoadReplicate { .. }, 64) => (0xe705, 3), // VLREPG
                    (&Inst::VecLoadReplicateRev { .. }, 16) => (0xe605, 1), // VLREPBRH
                    (&Inst::VecLoadReplicateRev { .. }, 32) => (0xe605, 2), // VLREPBRF
                    (&Inst::VecLoadReplicateRev { .. }, 64) => (0xe605, 3), // VLREPBRG
                    _ => unreachable!(),
                };
                mem_vrx_emit(rd.to_reg(), &mem, opcode, m3, true, sink, emit_info, state);
            }

            &Inst::VecMov { rd, rn } => {
                put(sink, &enc_vrr_a(OPCODE_VLR, rd.to_reg(), rn, 0, 0, 0));
            }
            &Inst::VecCMov { rd, cond, ri, rm } => {
                debug_assert_eq!(rd.to_reg(), ri);

                put(sink, &enc_ri_c(OPCODE_BCR, cond.invert().bits(), 4 + 6));
                put(sink, &enc_vrr_a(OPCODE_VLR, rd.to_reg(), rm, 0, 0, 0));
            }
            &Inst::MovToVec128 { rd, rn, rm } => {
                let opcode = 0xe762; // VLVGP
                put(sink, &enc_vrr_f(opcode, rd.to_reg(), rn, rm));
            }
            &Inst::VecImmByteMask { rd, mask } => {
                let opcode = 0xe744; // VGBM
                put(sink, &enc_vri_a(opcode, rd.to_reg(), mask, 0));
            }
            &Inst::VecImmBitMask {
                size,
                rd,
                start_bit,
                end_bit,
            } => {
                let (opcode, m4) = match size {
                    8 => (0xe746, 0),  // VGMB
                    16 => (0xe746, 1), // VGMH
                    32 => (0xe746, 2), // VGMF
                    64 => (0xe746, 3), // VGMG
                    _ => unreachable!(),
                };
                put(
                    sink,
                    &enc_vri_b(opcode, rd.to_reg(), start_bit, end_bit, m4),
                );
            }
            &Inst::VecImmReplicate { size, rd, imm } => {
                let (opcode, m3) = match size {
                    8 => (0xe745, 0),  // VREPIB
                    16 => (0xe745, 1), // VREPIH
                    32 => (0xe745, 2), // VREPIF
                    64 => (0xe745, 3), // VREPIG
                    _ => unreachable!(),
                };
                put(sink, &enc_vri_a(opcode, rd.to_reg(), imm as u16, m3));
            }
            &Inst::VecLoadLane {
                size,
                rd,
                ri,
                ref mem,
                lane_imm,
            }
            | &Inst::VecLoadLaneRev {
                size,
                rd,
                ri,
                ref mem,
                lane_imm,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);
                let mem = mem.clone();

                let opcode_vrx = match (self, size) {
                    (&Inst::VecLoadLane { .. }, 8) => 0xe700,     // VLEB
                    (&Inst::VecLoadLane { .. }, 16) => 0xe701,    // VLEH
                    (&Inst::VecLoadLane { .. }, 32) => 0xe703,    // VLEF
                    (&Inst::VecLoadLane { .. }, 64) => 0xe702,    // VLEG
                    (&Inst::VecLoadLaneRev { .. }, 16) => 0xe601, // VLEBRH
                    (&Inst::VecLoadLaneRev { .. }, 32) => 0xe603, // VLEBRF
                    (&Inst::VecLoadLaneRev { .. }, 64) => 0xe602, // VLEBRG
                    _ => unreachable!(),
                };

                let rd = rd.to_reg();
                mem_vrx_emit(rd, &mem, opcode_vrx, lane_imm, true, sink, emit_info, state);
            }
            &Inst::VecLoadLaneUndef {
                size,
                rd,
                ref mem,
                lane_imm,
            }
            | &Inst::VecLoadLaneRevUndef {
                size,
                rd,
                ref mem,
                lane_imm,
            } => {
                let mem = mem.clone();

                let (opcode_vrx, opcode_rx, opcode_rxy) = match (self, size) {
                    (&Inst::VecLoadLaneUndef { .. }, 8) => (0xe700, None, None), // VLEB
                    (&Inst::VecLoadLaneUndef { .. }, 16) => (0xe701, None, None), // VLEH
                    (&Inst::VecLoadLaneUndef { .. }, 32) => (0xe703, Some(0x78), Some(0xed64)), // VLEF, LE(Y)
                    (&Inst::VecLoadLaneUndef { .. }, 64) => (0xe702, Some(0x68), Some(0xed65)), // VLEG, LD(Y)
                    (&Inst::VecLoadLaneRevUndef { .. }, 16) => (0xe601, None, None), // VLEBRH
                    (&Inst::VecLoadLaneRevUndef { .. }, 32) => (0xe603, None, None), // VLEBRF
                    (&Inst::VecLoadLaneRevUndef { .. }, 64) => (0xe602, None, None), // VLEBRG
                    _ => unreachable!(),
                };

                let rd = rd.to_reg();
                if lane_imm == 0 && is_fpr(rd) && opcode_rx.is_some() {
                    mem_emit(
                        rd, &mem, opcode_rx, opcode_rxy, None, true, sink, emit_info, state,
                    );
                } else {
                    mem_vrx_emit(rd, &mem, opcode_vrx, lane_imm, true, sink, emit_info, state);
                }
            }
            &Inst::VecStoreLane {
                size,
                rd,
                ref mem,
                lane_imm,
            }
            | &Inst::VecStoreLaneRev {
                size,
                rd,
                ref mem,
                lane_imm,
            } => {
                let mem = mem.clone();

                let (opcode_vrx, opcode_rx, opcode_rxy) = match (self, size) {
                    (&Inst::VecStoreLane { .. }, 8) => (0xe708, None, None), // VSTEB
                    (&Inst::VecStoreLane { .. }, 16) => (0xe709, None, None), // VSTEH
                    (&Inst::VecStoreLane { .. }, 32) => (0xe70b, Some(0x70), Some(0xed66)), // VSTEF, STE(Y)
                    (&Inst::VecStoreLane { .. }, 64) => (0xe70a, Some(0x60), Some(0xed67)), // VSTEG, STD(Y)
                    (&Inst::VecStoreLaneRev { .. }, 16) => (0xe609, None, None), // VSTEBRH
                    (&Inst::VecStoreLaneRev { .. }, 32) => (0xe60b, None, None), // VSTEBRF
                    (&Inst::VecStoreLaneRev { .. }, 64) => (0xe60a, None, None), // VSTEBRG
                    _ => unreachable!(),
                };

                if lane_imm == 0 && is_fpr(rd) && opcode_rx.is_some() {
                    mem_emit(
                        rd, &mem, opcode_rx, opcode_rxy, None, true, sink, emit_info, state,
                    );
                } else {
                    mem_vrx_emit(rd, &mem, opcode_vrx, lane_imm, true, sink, emit_info, state);
                }
            }
            &Inst::VecInsertLane {
                size,
                rd,
                ri,
                rn,
                lane_imm,
                lane_reg,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let (opcode_vrs, m4) = match size {
                    8 => (0xe722, 0),  // VLVGB
                    16 => (0xe722, 1), // VLVGH
                    32 => (0xe722, 2), // VLVGF
                    64 => (0xe722, 3), // VLVGG
                    _ => unreachable!(),
                };
                put(
                    sink,
                    &enc_vrs_b(opcode_vrs, rd.to_reg(), lane_reg, lane_imm.into(), rn, m4),
                );
            }
            &Inst::VecInsertLaneUndef {
                size,
                rd,
                rn,
                lane_imm,
                lane_reg,
            } => {
                let (opcode_vrs, m4, opcode_rre) = match size {
                    8 => (0xe722, 0, None),          // VLVGB
                    16 => (0xe722, 1, None),         // VLVGH
                    32 => (0xe722, 2, None),         // VLVGF
                    64 => (0xe722, 3, Some(0xb3c1)), // VLVGG, LDGR
                    _ => unreachable!(),
                };
                if opcode_rre.is_some()
                    && lane_imm == 0
                    && lane_reg == zero_reg()
                    && is_fpr(rd.to_reg())
                {
                    put(sink, &enc_rre(opcode_rre.unwrap(), rd.to_reg(), rn));
                } else {
                    put(
                        sink,
                        &enc_vrs_b(opcode_vrs, rd.to_reg(), lane_reg, lane_imm.into(), rn, m4),
                    );
                }
            }
            &Inst::VecExtractLane {
                size,
                rd,
                rn,
                lane_imm,
                lane_reg,
            } => {
                let (opcode_vrs, m4, opcode_rre) = match size {
                    8 => (0xe721, 0, None),          // VLGVB
                    16 => (0xe721, 1, None),         // VLGVH
                    32 => (0xe721, 2, None),         // VLGVF
                    64 => (0xe721, 3, Some(0xb3cd)), // VLGVG, LGDR
                    _ => unreachable!(),
                };
                if opcode_rre.is_some() && lane_imm == 0 && lane_reg == zero_reg() && is_fpr(rn) {
                    put(sink, &enc_rre(opcode_rre.unwrap(), rd.to_reg(), rn));
                } else {
                    put(
                        sink,
                        &enc_vrs_c(opcode_vrs, rd.to_reg(), lane_reg, lane_imm.into(), rn, m4),
                    );
                }
            }
            &Inst::VecInsertLaneImm {
                size,
                rd,
                ri,
                imm,
                lane_imm,
            } => {
                debug_assert_eq!(rd.to_reg(), ri);

                let opcode = match size {
                    8 => 0xe740,  // VLEIB
                    16 => 0xe741, // VLEIH
                    32 => 0xe743, // VLEIF
                    64 => 0xe742, // VLEIG
                    _ => unreachable!(),
                };
                put(sink, &enc_vri_a(opcode, rd.to_reg(), imm as u16, lane_imm));
            }
            &Inst::VecInsertLaneImmUndef {
                size,
                rd,
                imm,
                lane_imm,
            } => {
                let opcode = match size {
                    8 => 0xe740,  // VLEIB
                    16 => 0xe741, // VLEIH
                    32 => 0xe743, // VLEIF
                    64 => 0xe742, // VLEIG
                    _ => unreachable!(),
                };
                put(sink, &enc_vri_a(opcode, rd.to_reg(), imm as u16, lane_imm));
            }
            &Inst::VecReplicateLane {
                size,
                rd,
                rn,
                lane_imm,
            } => {
                let (opcode, m4) = match size {
                    8 => (0xe74d, 0),  // VREPB
                    16 => (0xe74d, 1), // VREPH
                    32 => (0xe74d, 2), // VREPF
                    64 => (0xe74d, 3), // VREPG
                    _ => unreachable!(),
                };
                put(
                    sink,
                    &enc_vri_c(opcode, rd.to_reg(), lane_imm.into(), rn, m4),
                );
            }

            &Inst::VecEltRev { lane_count, rd, rn } => {
                assert!(lane_count >= 2 && lane_count <= 16);
                let inst = Inst::VecPermuteDWImm {
                    rd,
                    rn,
                    rm: rn,
                    idx1: 1,
                    idx2: 0,
                };
                inst.emit(sink, emit_info, state);
                if lane_count >= 4 {
                    let inst = Inst::VecShiftRR {
                        shift_op: VecShiftOp::RotL64x2,
                        rd,
                        rn: rd.to_reg(),
                        shift_imm: 32,
                        shift_reg: zero_reg(),
                    };
                    inst.emit(sink, emit_info, state);
                }
                if lane_count >= 8 {
                    let inst = Inst::VecShiftRR {
                        shift_op: VecShiftOp::RotL32x4,
                        rd,
                        rn: rd.to_reg(),
                        shift_imm: 16,
                        shift_reg: zero_reg(),
                    };
                    inst.emit(sink, emit_info, state);
                }
                if lane_count >= 16 {
                    let inst = Inst::VecShiftRR {
                        shift_op: VecShiftOp::RotL16x8,
                        rd,
                        rn: rd.to_reg(),
                        shift_imm: 8,
                        shift_reg: zero_reg(),
                    };
                    inst.emit(sink, emit_info, state);
                }
            }

            &Inst::AllocateArgs { size } => {
                let inst = if let Ok(size) = i16::try_from(size) {
                    Inst::AluRSImm16 {
                        alu_op: ALUOp::Add64,
                        rd: writable_stack_reg(),
                        ri: stack_reg(),
                        imm: -size,
                    }
                } else {
                    Inst::AluRUImm32 {
                        alu_op: ALUOp::SubLogical64,
                        rd: writable_stack_reg(),
                        ri: stack_reg(),
                        imm: size,
                    }
                };
                inst.emit(sink, emit_info, state);
                assert_eq!(state.nominal_sp_offset, 0);
                state.nominal_sp_offset += size;
            }
            &Inst::Call { link, ref info } => {
                let start = sink.cur_offset();

                let enc: &[u8] = match &info.dest {
                    CallInstDest::Direct { name } => {
                        let offset = sink.cur_offset() + 2;
                        sink.add_reloc_at_offset(offset, Reloc::S390xPLTRel32Dbl, name, 2);
                        let opcode = 0xc05; // BRASL
                        &enc_ril_b(opcode, link.to_reg(), 0)
                    }
                    CallInstDest::Indirect { reg } => {
                        let opcode = 0x0d; // BASR
                        &enc_rr(opcode, link.to_reg(), *reg)
                    }
                };
                if let Some(s) = state.take_stack_map() {
                    let offset = sink.cur_offset() + enc.len() as u32;
                    sink.push_user_stack_map(state, offset, s);
                }
                put(sink, enc);

                if let Some(try_call) = info.try_call_info.as_ref() {
                    sink.add_try_call_site(
                        Some(state.frame_layout.sp_to_fp()),
                        try_call.exception_handlers(&state.frame_layout),
                    );
                } else {
                    sink.add_call_site();
                }

                state.nominal_sp_offset -= info.callee_pop_size;
                assert_eq!(state.nominal_sp_offset, 0);

                if info.patchable {
                    sink.add_patchable_call_site(sink.cur_offset() - start);
                } else {
                    state.outgoing_sp_offset = info.callee_pop_size;
                    for inst in S390xMachineDeps::gen_retval_loads(info) {
                        inst.emit(sink, emit_info, state);
                    }
                    state.outgoing_sp_offset = 0;
                }

                // If this is a try-call, jump to the continuation
                // (normal-return) block.
                if let Some(try_call) = info.try_call_info.as_ref() {
                    let jmp = Inst::Jump {
                        dest: try_call.continuation,
                    };
                    jmp.emit(sink, emit_info, state);
                }
            }
            &Inst::ReturnCall { ref info } => {
                let (epilogue_insts, temp_dest) = S390xMachineDeps::gen_tail_epilogue(
                    state.frame_layout(),
                    info.callee_pop_size,
                    &info.dest,
                );
                for inst in epilogue_insts {
                    inst.emit(sink, emit_info, state);
                }

                let enc: &[u8] = match &info.dest {
                    CallInstDest::Direct { name } => {
                        let offset = sink.cur_offset() + 2;
                        sink.add_reloc_at_offset(offset, Reloc::S390xPLTRel32Dbl, name, 2);
                        let opcode = 0xc04; // BCRL
                        &enc_ril_c(opcode, 15, 0)
                    }
                    CallInstDest::Indirect { reg } => {
                        let opcode = 0x07; // BCR
                        &enc_rr(opcode, gpr(15), temp_dest.unwrap_or(*reg))
                    }
                };
                put(sink, enc);
                sink.add_call_site();
            }
            &Inst::ElfTlsGetOffset { ref symbol, .. } => {
                let opcode = 0xc05; // BRASL

                // Add relocation for target function. This has to be done
                // *before* the S390xTlsGdCall, to ensure linker relaxation
                // works correctly.
                let dest = ExternalName::LibCall(LibCall::ElfTlsGetOffset);
                let offset = sink.cur_offset() + 2;
                sink.add_reloc_at_offset(offset, Reloc::S390xPLTRel32Dbl, &dest, 2);
                match &**symbol {
                    SymbolReloc::TlsGd { name } => sink.add_reloc(Reloc::S390xTlsGdCall, name, 0),
                    _ => unreachable!(),
                }

                put(sink, &enc_ril_b(opcode, gpr(14), 0));
                sink.add_call_site();
            }
            &Inst::Args { .. } => {}
            &Inst::Rets { .. } => {}
            &Inst::Ret { link } => {
                let opcode = 0x07; // BCR
                put(sink, &enc_rr(opcode, gpr(15), link));
            }
            &Inst::Jump { dest } => {
                let off = sink.cur_offset();
                // Indicate that the jump uses a label, if so, so that a fixup can occur later.
                sink.use_label_at_offset(off, dest, LabelUse::BranchRIL);
                sink.add_uncond_branch(off, off + 6, dest);
                // Emit the jump itself.
                let opcode = 0xc04; // BCRL
                put(sink, &enc_ril_c(opcode, 15, 0));
            }
            &Inst::IndirectBr { rn, .. } => {
                let opcode = 0x07; // BCR
                put(sink, &enc_rr(opcode, gpr(15), rn));
            }
            &Inst::CondBr {
                taken,
                not_taken,
                cond,
            } => {
                let opcode = 0xc04; // BCRL

                // Conditional part first.
                let cond_off = sink.cur_offset();
                sink.use_label_at_offset(cond_off, taken, LabelUse::BranchRIL);
                let inverted = &enc_ril_c(opcode, cond.invert().bits(), 0);
                sink.add_cond_branch(cond_off, cond_off + 6, taken, inverted);
                put(sink, &enc_ril_c(opcode, cond.bits(), 0));

                // Unconditional part next.
                let uncond_off = sink.cur_offset();
                sink.use_label_at_offset(uncond_off, not_taken, LabelUse::BranchRIL);
                sink.add_uncond_branch(uncond_off, uncond_off + 6, not_taken);
                put(sink, &enc_ril_c(opcode, 15, 0));
            }
            &Inst::Nop0 => {}
            &Inst::Nop2 => {
                put(sink, &enc_e(0x0707));
            }
            &Inst::Debugtrap => {
                put(sink, &enc_e(0x0001));
            }
            &Inst::Trap { trap_code } => {
                put_with_trap(sink, &enc_e(0x0000), trap_code);
            }
            &Inst::TrapIf { cond, trap_code } => {
                // We implement a TrapIf as a conditional branch into the middle
                // of the branch (BRCL) instruction itself - those middle two bytes
                // are zero, which matches the trap instruction itself.
                let opcode = 0xc04; // BCRL
                let enc = &enc_ril_c(opcode, cond.bits(), 2);
                debug_assert!(enc.len() == 6 && enc[2] == 0 && enc[3] == 0);
                // The trap must be placed on the last byte of the embedded trap
                // instruction, so we need to emit the encoding in two parts.
                put_with_trap(sink, &enc[0..4], trap_code);
                put(sink, &enc[4..6]);
            }
            &Inst::JTSequence {
                ridx,
                default,
                default_cond,
                ref targets,
            } => {
                let table_label = sink.get_label();

                // This sequence is *one* instruction in the vcode, and is expanded only here at
                // emission time, because we cannot allow the regalloc to insert spills/reloads in
                // the middle; we depend on hardcoded PC-rel addressing below.

                // Branch to the default target if the given default condition is true.
                let opcode = 0xc04; // BCRL
                sink.use_label_at_offset(sink.cur_offset(), default, LabelUse::BranchRIL);
                put(sink, &enc_ril_c(opcode, default_cond.bits(), 0));

                // Set temp register to address of jump table.
                let rtmp = writable_spilltmp_reg();
                let inst = Inst::LoadAddr {
                    rd: rtmp,
                    mem: MemArg::Label {
                        target: table_label,
                    },
                };
                inst.emit(sink, emit_info, state);

                // Set temp to target address by adding the value of the jump table entry.
                let inst = Inst::AluRX {
                    alu_op: ALUOp::Add64Ext32,
                    rd: rtmp,
                    ri: rtmp.to_reg(),
                    mem: MemArg::reg_plus_reg(rtmp.to_reg(), ridx, MemFlags::trusted()),
                };
                inst.emit(sink, emit_info, state);

                // Branch to computed address. (`targets` here is only used for successor queries
                // and is not needed for emission.)
                let inst = Inst::IndirectBr {
                    rn: rtmp.to_reg(),
                    targets: vec![],
                };
                inst.emit(sink, emit_info, state);

                // Emit jump table (table of 32-bit offsets).
                sink.bind_label(table_label, &mut state.ctrl_plane);
                let jt_off = sink.cur_offset();
                for &target in targets.iter() {
                    let word_off = sink.cur_offset();
                    let off_into_table = word_off - jt_off;
                    sink.use_label_at_offset(word_off, target, LabelUse::PCRel32);
                    sink.put4(off_into_table.swap_bytes());
                }
            }

            Inst::StackProbeLoop {
                probe_count,
                guard_size,
            } => {
                // Emit the loop start label
                let loop_start = sink.get_label();
                sink.bind_label(loop_start, state.ctrl_plane_mut());

                // aghi %r15, -GUARD_SIZE
                let inst = Inst::AluRSImm16 {
                    alu_op: ALUOp::Add64,
                    rd: writable_stack_reg(),
                    ri: stack_reg(),
                    imm: -guard_size,
                };
                inst.emit(sink, emit_info, state);

                // mvi 0(%r15), 0
                let inst = Inst::StoreImm8 {
                    imm: 0,
                    mem: MemArg::reg(stack_reg(), MemFlags::trusted()),
                };
                inst.emit(sink, emit_info, state);

                // brct PROBE_COUNT, LOOP_START
                let opcode = 0xa76; // BRCT
                sink.use_label_at_offset(sink.cur_offset(), loop_start, LabelUse::BranchRI);
                put(sink, &enc_ri_b(opcode, probe_count.to_reg(), 0));
            }

            &Inst::Unwind { ref inst } => {
                sink.add_unwind(inst.clone());
            }

            &Inst::DummyUse { .. } => {}

            &Inst::LabelAddress { dst, label } => {
                let inst = Inst::LoadAddr {
                    rd: dst,
                    mem: MemArg::Label { target: label },
                };
                inst.emit(sink, emit_info, state);
            }

            &Inst::SequencePoint { .. } => {
                // Nothing.
            }
        }

        state.clear_post_insn();
    }
}