llvm-native-core 0.1.16

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! X86 XOP & 3DNow! Encoding — AMD XOP prefix generation for Bulldozer/
//! Piledriver/Steamroller/Excavator XOP instructions, AMD 3DNow! encoding
//! (0F 0F opcode map with immediate byte), PREFETCH/PREFETCHW encoding,
//! FEMMS instruction, and 3DNow! register pairing.
//!
//! ## XOP Encoding Overview
//!
//! XOP (eXtended Operations) is an AMD instruction set extension introduced
//! with the Bulldozer microarchitecture. It uses a 3-byte prefix similar
//! to VEX3 but with the first byte 0x8F instead of 0xC4.
//!
//! ### XOP Byte Layout
//! ```
//! Byte 0: [1 0 0 0 1 1 1 1] = 0x8F
//! Byte 1: [R X B m m m m m]   (same layout as VEX3 byte1)
//! Byte 2: [W v v v v L p p]   (same layout as VEX3 byte2)
//! ```
//!
//! ### XOP Opcode Maps
//! - Map 8 (mmmmm=01000): Integer horizontal add/subtract, permute, shift
//! - Map 9 (mmmmm=01001): Fraction extraction, comparison, permutation
//! - Map A (mmmmm=01010): Reserved for future use
//!
//! ### Supported Processors
//! - AMD Bulldozer (Family 15h)
//! - AMD Piledriver (Family 15h, model 10h-1Fh)
//! - AMD Steamroller (Family 15h, model 30h-3Fh)
//! - AMD Excavator (Family 15h, model 60h-7Fh, Family 16h)
//!
//! ## 3DNow! Encoding Overview
//!
//! AMD 3DNow! is a SIMD extension for MMX registers, using the 0F 0F opcode
//! prefix followed by an immediate byte that selects the specific operation.
//!
//! ### 3DNow! Instruction Format
//! ```
//! [0F] [0F] [ModR/M] [Immediate] [Displacement]
//! ```
//!
//! The immediate byte selects one of ~21 operations:
//! - PI2FD, PI2FW, PF2ID, PF2IW
//! - PFACC, PFADD, PFCMPEQ, PFCMPGE, PFCMPGT
//! - PFMAX, PFMIN, PFMUL, PFNACC, PFPNACC
//! - PFRCP, PFRCPIT1, PFRCPIT2, PFRSQIT1, PFRSQRT
//! - PFSUB, PFSUBR, PMULHRW, PAVGUSB
//!
//! Special instructions:
//! - FEMMS: Fast Entry/Exit Multimedia State (0F 0E, no ModR/M)
//! - PREFETCH/PREFETCHW: Prefetch with write intent (0F 0D /r)
//!
//! ### 3DNow! Register Pairing
//! 3DNow! operates on MMX registers (MM0-MM7), which are 64-bit. Some
//! operations treat register pairs as 128-bit operands for certain
//! packed operations.
//!
//! Clean-room behavioral reconstruction from:
//! - AMD64 Architecture Programmer's Manual, Volume 4 (128-bit SSE5/XOP)
//! - AMD64 Architecture Programmer's Manual, Volume 5 (3DNow!)
//! - AMD 3DNow! Technology Manual
//! - Zero LLVM source code consultation
//! - Black-box oracle interrogation

use std::collections::HashMap;
use std::fmt;

use super::x86_vex_encoding::{
    vex_invert_reg, vex_recover_reg, VexMandatoryPrefix, VexVectorLength, VEX_PP_NONE,
    VEX_REG_HIGH_BIT, VEX_REG_MASK,
};

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP Prefix Constants                                    ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// XOP prefix identifier byte (always 0x8F).
pub const XOP_PREFIX: u8 = 0x8F;

/// XOP opcode map 8 (integer horizontal operations, permute, shift).
pub const XOP_MAP8: u8 = 0x08;

/// XOP opcode map 9 (fraction extraction, comparison, permutation).
pub const XOP_MAP9: u8 = 0x09;

/// XOP opcode map A (reserved).
pub const XOP_MAPA: u8 = 0x0A;

/// XOP byte1 field masks.
const XOP_BYTE1_R_MASK: u8 = 0x80;
const XOP_BYTE1_X_MASK: u8 = 0x40;
const XOP_BYTE1_B_MASK: u8 = 0x20;
const XOP_BYTE1_MMMMM_MASK: u8 = 0x1F;

/// XOP byte2 field masks.
const XOP_BYTE2_W_MASK: u8 = 0x80;
const XOP_BYTE2_VVVV_MASK: u8 = 0x78;
const XOP_BYTE2_L_MASK: u8 = 0x04;
const XOP_BYTE2_PP_MASK: u8 = 0x03;

/// Maximum MMX/XMM/YMM register for XOP.
pub const XOP_MAX_REG: u8 = 15;

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    3DNow! Constants                                        ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// 3DNow! opcode prefix: first byte of 0F 0F.
pub const TDNOW_ESCAPE_0F: u8 = 0x0F;

/// 3DNow! second escape byte (also 0x0F).
pub const TDNOW_ESCAPE_SECOND: u8 = 0x0F;

/// 3DNow! immediate byte opcodes.
pub mod tdnow_opcodes {
    /// Packed 32-bit integer to floating-point conversion.
    pub const PI2FD: u8 = 0x0D;
    /// Packed 16-bit integer to floating-point conversion.
    pub const PI2FW: u8 = 0x0C;
    /// Packed floating-point to 32-bit integer conversion.
    pub const PF2ID: u8 = 0x1D;
    /// Packed floating-point to 16-bit integer conversion.
    pub const PF2IW: u8 = 0x1C;
    /// Packed floating-point accumulate.
    pub const PFACC: u8 = 0xAE;
    /// Packed floating-point addition.
    pub const PFADD: u8 = 0x9E;
    /// Packed floating-point compare equal.
    pub const PFCMPEQ: u8 = 0xB0;
    /// Packed floating-point compare greater or equal.
    pub const PFCMPGE: u8 = 0x90;
    /// Packed floating-point compare greater than.
    pub const PFCMPGT: u8 = 0xA0;
    /// Packed floating-point maximum.
    pub const PFMAX: u8 = 0xA4;
    /// Packed floating-point minimum.
    pub const PFMIN: u8 = 0x94;
    /// Packed floating-point multiplication.
    pub const PFMUL: u8 = 0xB4;
    /// Packed floating-point negative accumulate.
    pub const PFNACC: u8 = 0x8A;
    /// Packed floating-point positive-negative accumulate.
    pub const PFPNACC: u8 = 0x8E;
    /// Packed floating-point reciprocal approximation.
    pub const PFRCP: u8 = 0x96;
    /// Packed floating-point reciprocal iteration 1.
    pub const PFRCPIT1: u8 = 0xA6;
    /// Packed floating-point reciprocal iteration 2.
    pub const PFRCPIT2: u8 = 0xB6;
    /// Packed floating-point reciprocal square root iteration 1.
    pub const PFRSQIT1: u8 = 0xA7;
    /// Packed floating-point reciprocal square root approximation.
    pub const PFRSQRT: u8 = 0x97;
    /// Packed floating-point subtraction.
    pub const PFSUB: u8 = 0x9A;
    /// Packed floating-point reverse subtraction.
    pub const PFSUBR: u8 = 0xAA;
    /// Packed multiply high, rounded word.
    pub const PMULHRW: u8 = 0xB7;
    /// Packed average unsigned byte.
    pub const PAVGUSB: u8 = 0xBF;
}

/// FEMMS opcode.
pub const FEMMS_OPCODE: [u8; 2] = [0x0F, 0x0E];

/// PREFETCH / PREFETCHW opcode prefix.
pub const PREFETCH_OPCODE_PREFIX: [u8; 2] = [0x0F, 0x0D];

/// PREFETCHW opcode variant (ModR/M reg field = 1).
pub const PREFETCHW_REG_FIELD: u8 = 0x01;

/// 3DNow! MMX register count.
pub const TDNOW_MMX_REG_COUNT: u8 = 8;

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP Opcode Map Enumeration                              ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// XOP opcode map (mmmmm field values 8, 9, A).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum XopOpcodeMap {
    /// Map 8: Integer horizontal operations, permute, shift (VPHADDBD, VPROTB, etc.)
    Map8 = 0x08,
    /// Map 9: Fraction extraction, comparison, permutation (VFRCZPS, VPCMOV, etc.)
    Map9 = 0x09,
    /// Map A: Reserved.
    MapA = 0x0A,
}

impl XopOpcodeMap {
    /// Return the mmmmm field value.
    pub const fn mmmmm(&self) -> u8 {
        *self as u8
    }

    /// Create from mmmmm field.
    pub const fn from_mmmmm(mmmmm: u8) -> Option<Self> {
        match mmmmm {
            0x08 => Some(Self::Map8),
            0x09 => Some(Self::Map9),
            0x0A => Some(Self::MapA),
            _ => None,
        }
    }

    /// Human-readable name.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Map8 => "XOP8",
            Self::Map9 => "XOP9",
            Self::MapA => "XOPA",
        }
    }
}

impl fmt::Display for XopOpcodeMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP Prefix Configuration                                ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// XOP prefix configuration — similar to VEX3 but with 0x8F prefix byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct XopPrefixConfig {
    /// XOP.R: 1's complement of ModR/M reg extension.
    pub r: bool,
    /// XOP.X: 1's complement of SIB index extension.
    pub x: bool,
    /// XOP.B: 1's complement of ModR/M r/m extension.
    pub b: bool,
    /// XOP.mmmmm: opcode map (8, 9, or A).
    pub mmmmm: u8,
    /// XOP.W: 64-bit operand size.
    pub w: bool,
    /// XOP.vvvv: 1's complement of source register.
    pub vvvv: u8,
    /// XOP.L: vector length (0=128, 1=256).
    pub l: bool,
    /// XOP.pp: implied mandatory prefix.
    pub pp: u8,
}

impl Default for XopPrefixConfig {
    fn default() -> Self {
        Self {
            r: false,
            x: false,
            b: false,
            mmmmm: XOP_MAP8,
            w: false,
            vvvv: 0,
            l: false,
            pp: VEX_PP_NONE,
        }
    }
}

impl XopPrefixConfig {
    /// Create a new XopPrefixConfig.
    pub const fn new() -> Self {
        Self {
            r: false,
            x: false,
            b: false,
            mmmmm: XOP_MAP8,
            w: false,
            vvvv: 0,
            l: false,
            pp: VEX_PP_NONE,
        }
    }

    /// Set the opcode map.
    pub fn with_map(mut self, map: XopOpcodeMap) -> Self {
        self.mmmmm = map.mmmmm();
        self
    }

    /// Set the mandatory prefix.
    pub fn with_prefix(mut self, pfx: VexMandatoryPrefix) -> Self {
        self.pp = pfx.pp_bits();
        self
    }

    /// Set vector length.
    pub fn with_vector_length(mut self, vl: VexVectorLength) -> Self {
        self.l = vl.l_bit();
        self
    }

    /// Set the vvvv source register (inverted).
    pub fn with_vvvv(mut self, reg: u8) -> Self {
        self.vvvv = vex_invert_reg(reg & VEX_REG_MASK);
        self
    }

    /// Set destination register (affects R).
    pub fn with_dest_reg(mut self, reg: u8) -> Self {
        self.r = (reg & VEX_REG_HIGH_BIT) != 0;
        self
    }

    /// Set base/memory register (affects B).
    pub fn with_base_reg(mut self, reg: u8) -> Self {
        self.b = (reg & VEX_REG_HIGH_BIT) != 0;
        self
    }

    /// Set SIB index register (affects X).
    pub fn with_index_reg(mut self, reg: u8) -> Self {
        self.x = (reg & VEX_REG_HIGH_BIT) != 0;
        self
    }

    /// Set W bit.
    pub fn with_w(mut self, w: bool) -> Self {
        self.w = w;
        self
    }

    /// Build from register numbers.
    pub fn from_registers(
        map: XopOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        vvvv_reg: u8,
        dest_reg: u8,
        src_or_base_reg: u8,
        sib_index: Option<u8>,
        w: bool,
    ) -> Self {
        let mut cfg = Self::new()
            .with_map(map)
            .with_prefix(prefix)
            .with_vector_length(vl)
            .with_vvvv(vvvv_reg)
            .with_dest_reg(dest_reg)
            .with_base_reg(src_or_base_reg)
            .with_w(w);

        if let Some(idx) = sib_index {
            cfg = cfg.with_index_reg(idx);
        }

        cfg
    }

    /// Prefix byte count (always 3 for XOP).
    pub const fn prefix_byte_count(&self) -> u8 {
        3
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP Prefix Builder                                      ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// XOP prefix encoder — builds 3-byte XOP sequences.
pub struct XopPrefixBuilder;

impl XopPrefixBuilder {
    /// Build a 3-byte XOP prefix.
    ///
    /// XOP layout: [8F] [RXBmmmmm] [WvvvvLpp]
    #[inline]
    pub fn build(
        r: bool,
        x: bool,
        b: bool,
        mmmmm: u8,
        w: bool,
        vvvv: u8,
        l: bool,
        pp: u8,
    ) -> [u8; 3] {
        let byte1: u8 = ((!r as u8) << 7)
            | ((!x as u8) << 6)
            | ((!b as u8) << 5)
            | (mmmmm & XOP_BYTE1_MMMMM_MASK);
        let byte2: u8 = ((w as u8) << 7)
            | ((vvvv & VEX_REG_MASK) << 3)
            | ((l as u8) << 2)
            | (pp & XOP_BYTE2_PP_MASK);
        [XOP_PREFIX, byte1, byte2]
    }

    /// Build XOP prefix from config.
    #[inline]
    pub fn build_from_config(config: &XopPrefixConfig) -> [u8; 3] {
        Self::build(
            config.r,
            config.x,
            config.b,
            config.mmmmm,
            config.w,
            config.vvvv,
            config.l,
            config.pp,
        )
    }

    /// Build XOP prefix as Vec.
    pub fn build_vec(config: &XopPrefixConfig) -> Vec<u8> {
        Self::build_from_config(config).to_vec()
    }

    /// Build XOP prefix from register numbers directly.
    pub fn build_from_regs(
        map: XopOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
        w: bool,
    ) -> [u8; 3] {
        let cfg =
            XopPrefixConfig::from_registers(map, prefix, vl, src1_reg, dest_reg, src2_reg, None, w);
        Self::build_from_config(&cfg)
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP Prefix Decoder                                      ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Decoded XOP prefix fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct XopDecodedPrefix {
    pub r: bool,
    pub x: bool,
    pub b: bool,
    pub mmmmm: u8,
    pub w: bool,
    pub vvvv: u8,
    pub l: bool,
    pub pp: u8,
}

impl XopDecodedPrefix {
    /// Decode XOP from bytes [0x8F, byte1, byte2].
    pub fn decode(byte1: u8, byte2: u8) -> Self {
        Self {
            r: (byte1 & XOP_BYTE1_R_MASK) == 0,
            x: (byte1 & XOP_BYTE1_X_MASK) == 0,
            b: (byte1 & XOP_BYTE1_B_MASK) == 0,
            mmmmm: byte1 & XOP_BYTE1_MMMMM_MASK,
            w: (byte2 & XOP_BYTE2_W_MASK) != 0,
            vvvv: (byte2 >> 3) & VEX_REG_MASK,
            l: (byte2 & XOP_BYTE2_L_MASK) != 0,
            pp: byte2 & XOP_BYTE2_PP_MASK,
        }
    }

    /// Decode from byte slice.
    pub fn decode_from_slice(bytes: &[u8]) -> Option<(Self, usize)> {
        if bytes.len() < 3 || bytes[0] != XOP_PREFIX {
            return None;
        }
        Some((Self::decode(bytes[1], bytes[2]), 3))
    }

    /// Get the effective register from R bit.
    pub fn effective_reg_r(&self, reg: u8) -> u8 {
        if self.r {
            reg & 0x07
        } else {
            reg | VEX_REG_HIGH_BIT
        }
    }

    /// Get the effective register from X bit.
    pub fn effective_reg_x(&self, reg: u8) -> u8 {
        if self.x {
            reg & 0x07
        } else {
            reg | VEX_REG_HIGH_BIT
        }
    }

    /// Get the effective register from B bit.
    pub fn effective_reg_b(&self, reg: u8) -> u8 {
        if self.b {
            reg & 0x07
        } else {
            reg | VEX_REG_HIGH_BIT
        }
    }

    /// Get true vvvv register.
    pub fn true_vvvv(&self) -> u8 {
        vex_recover_reg(self.vvvv)
    }

    /// Get the opcode map.
    pub fn opcode_map(&self) -> Option<XopOpcodeMap> {
        XopOpcodeMap::from_mmmmm(self.mmmmm)
    }

    /// Get the mandatory prefix.
    pub fn mandatory_prefix(&self) -> VexMandatoryPrefix {
        VexMandatoryPrefix::from_pp(self.pp).unwrap_or(VexMandatoryPrefix::None)
    }

    /// Get the vector length.
    pub fn vector_length(&self) -> VexVectorLength {
        VexVectorLength::from_l_bit(self.l)
    }

    /// Convert to XopPrefixConfig.
    pub fn to_config(&self) -> XopPrefixConfig {
        XopPrefixConfig {
            r: self.r,
            x: self.x,
            b: self.b,
            mmmmm: self.mmmmm,
            w: self.w,
            vvvv: self.vvvv,
            l: self.l,
            pp: self.pp,
        }
    }
}

impl fmt::Display for XopDecodedPrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "XOP R={} X={} B={} mmmmm={:05b} W={} vvvv={:04b} L={} pp={:02b}",
            self.r as u8,
            self.x as u8,
            self.b as u8,
            self.mmmmm,
            self.w as u8,
            self.vvvv,
            self.l as u8,
            self.pp,
        )
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP Instruction Catalog                                ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Complete XOP instruction catalog with opcodes and descriptions.
#[derive(Debug, Clone)]
pub struct XopInstructionCatalog;

impl XopInstructionCatalog {
    /// Map 8 instructions (integer horizontal ops, permute, shift).
    pub fn map8_instructions() -> Vec<(&'static str, u8, &'static str)> {
        vec![
            (
                "vphaddbd",
                0xC2,
                "Packed Horizontal Add Bytes to Doubleword",
            ),
            ("vphaddbq", 0xC3, "Packed Horizontal Add Bytes to Quadword"),
            (
                "vphaddwd",
                0xC6,
                "Packed Horizontal Add Words to Doubleword",
            ),
            ("vphaddwq", 0xC7, "Packed Horizontal Add Words to Quadword"),
            (
                "vphadddq",
                0xCB,
                "Packed Horizontal Add Doubleword to Quadword",
            ),
            (
                "vphaddubd",
                0xD2,
                "Packed Horizontal Add Unsigned Bytes to Doubleword",
            ),
            (
                "vphaddubq",
                0xD3,
                "Packed Horizontal Add Unsigned Bytes to Quadword",
            ),
            (
                "vphadduwd",
                0xD6,
                "Packed Horizontal Add Unsigned Words to Doubleword",
            ),
            (
                "vphadduwq",
                0xD7,
                "Packed Horizontal Add Unsigned Words to Quadword",
            ),
            (
                "vphaddudq",
                0xDB,
                "Packed Horizontal Add Unsigned Doubleword to Quadword",
            ),
            (
                "vphsubbw",
                0xE2,
                "Packed Horizontal Subtract Bytes to Words",
            ),
            (
                "vphsubdq",
                0xE3,
                "Packed Horizontal Subtract Doubleword to Quadword",
            ),
            (
                "vphsubwd",
                0xE6,
                "Packed Horizontal Subtract Words to Doubleword",
            ),
            (
                "vpmacssww",
                0x82,
                "Packed Multiply-Accumulate Signed Signed Words to Words",
            ),
            (
                "vpmacsswd",
                0x86,
                "Packed Multiply-Accumulate Signed Signed Words to Doubleword",
            ),
            (
                "vpmacssdql",
                0x9A,
                "Packed Multiply-Accumulate Signed Signed Doubleword to Quadword Low",
            ),
            (
                "vpmacssdqh",
                0x9E,
                "Packed Multiply-Accumulate Signed Signed Doubleword to Quadword High",
            ),
            (
                "vpmacssdd",
                0x8A,
                "Packed Multiply-Accumulate Signed Signed Doubleword to Doubleword",
            ),
            (
                "vpmacsww",
                0x92,
                "Packed Multiply-Accumulate Signed Words to Words",
            ),
            (
                "vpmacswd",
                0x96,
                "Packed Multiply-Accumulate Signed Words to Doubleword",
            ),
            (
                "vpmacsdql",
                0xB2,
                "Packed Multiply-Accumulate Signed Doubleword to Quadword Low",
            ),
            (
                "vpmacsdqh",
                0xB6,
                "Packed Multiply-Accumulate Signed Doubleword to Quadword High",
            ),
            (
                "vpmacsdd",
                0x9E,
                "Packed Multiply-Accumulate Signed Doubleword to Doubleword",
            ),
            (
                "vpmadcsswd",
                0xA2,
                "Packed Multiply-Add and Accumulate Signed Signed Words to Doubleword",
            ),
            (
                "vpmadcswd",
                0xB2,
                "Packed Multiply-Add and Accumulate Signed Words to Doubleword",
            ),
        ]
    }

    /// Map 8 shift/permute instructions.
    pub fn map8_shift_instructions() -> Vec<(&'static str, u8, &'static str)> {
        vec![
            ("vprotb", 0x90, "Packed Rotate Bytes"),
            ("vprotw", 0x91, "Packed Rotate Words"),
            ("vprotd", 0x92, "Packed Rotate Doublewords"),
            ("vprotq", 0x93, "Packed Rotate Quadwords"),
            ("vpshab", 0x98, "Packed Shift Arithmetic Bytes"),
            ("vpshaw", 0x99, "Packed Shift Arithmetic Words"),
            ("vpshad", 0x9A, "Packed Shift Arithmetic Doublewords"),
            ("vpshaq", 0x9B, "Packed Shift Arithmetic Quadwords"),
            ("vpshlb", 0x94, "Packed Shift Logical Bytes"),
            ("vpshlw", 0x95, "Packed Shift Logical Words"),
            ("vpshld", 0x96, "Packed Shift Logical Doublewords"),
            ("vpshlq", 0x97, "Packed Shift Logical Quadwords"),
        ]
    }

    /// Map 9 instructions (fraction extraction, comparison, permute).
    pub fn map9_instructions() -> Vec<(&'static str, u8, &'static str)> {
        vec![
            ("vfrczps", 0x80, "Fraction Extraction Packed Single"),
            ("vfrczpd", 0x81, "Fraction Extraction Packed Double"),
            ("vfrczss", 0x82, "Fraction Extraction Scalar Single"),
            ("vfrczsd", 0x83, "Fraction Extraction Scalar Double"),
            ("vpcmov", 0xA0, "Packed Conditional Move"),
            ("vpperm", 0xA1, "Packed Permute Bytes"),
            ("vpcomb", 0x8C, "Packed Compare Bytes"),
            ("vpcomw", 0x8D, "Packed Compare Words"),
            ("vpcomd", 0x8E, "Packed Compare Doublewords"),
            ("vpcomq", 0x8F, "Packed Compare Quadwords"),
            ("vpcomub", 0xCC, "Packed Compare Unsigned Bytes"),
            ("vpcomuw", 0xCD, "Packed Compare Unsigned Words"),
            ("vpcomud", 0xCE, "Packed Compare Unsigned Doublewords"),
            ("vpcomuq", 0xCF, "Packed Compare Unsigned Quadwords"),
        ]
    }

    /// Get a human-readable mnemonic for a (map, opcode) pair.
    pub fn lookup(map: u8, opcode: u8) -> Option<&'static str> {
        match map {
            8 => {
                for (name, op, _) in Self::map8_instructions()
                    .iter()
                    .chain(Self::map8_shift_instructions().iter())
                {
                    if *op == opcode {
                        return Some(name);
                    }
                }
                None
            }
            9 => {
                for (name, op, _) in Self::map9_instructions() {
                    if op == opcode as u8 {
                        return Some(name);
                    }
                }
                None
            }
            _ => None,
        }
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP Encoded Instruction                                 ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Complete XOP-encoded instruction.
#[derive(Debug, Clone)]
pub struct XopEncodedInstruction {
    /// XOP prefix bytes (always 3).
    pub xop_prefix: Vec<u8>,
    /// Opcode byte.
    pub opcode: Vec<u8>,
    /// ModR/M byte.
    pub modrm: Option<u8>,
    /// SIB byte.
    pub sib: Option<u8>,
    /// Displacement bytes.
    pub displacement: Vec<u8>,
    /// Immediate bytes.
    pub immediate: Vec<u8>,
    /// XOP map used.
    pub map: XopOpcodeMap,
    /// Mnemonic from catalog.
    pub mnemonic: Option<&'static str>,
}

impl XopEncodedInstruction {
    /// Create a new XOP instruction.
    pub fn new(map: XopOpcodeMap) -> Self {
        Self {
            xop_prefix: Vec::new(),
            opcode: Vec::new(),
            modrm: None,
            sib: None,
            displacement: Vec::new(),
            immediate: Vec::new(),
            map,
            mnemonic: None,
        }
    }

    /// Assemble the full instruction bytes.
    pub fn assemble(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(self.total_length() as usize);
        bytes.extend_from_slice(&self.xop_prefix);
        bytes.extend_from_slice(&self.opcode);
        if let Some(modrm) = self.modrm {
            bytes.push(modrm);
        }
        if let Some(sib) = self.sib {
            bytes.push(sib);
        }
        bytes.extend_from_slice(&self.displacement);
        bytes.extend_from_slice(&self.immediate);
        bytes
    }

    /// Total instruction length.
    pub fn total_length(&self) -> u16 {
        let mut len: u16 = self.xop_prefix.len() as u16;
        len += self.opcode.len() as u16;
        if self.modrm.is_some() {
            len += 1;
        }
        if self.sib.is_some() {
            len += 1;
        }
        len += self.displacement.len() as u16;
        len += self.immediate.len() as u16;
        len
    }

    /// Check if instruction length is valid.
    pub fn is_valid(&self) -> bool {
        self.total_length() <= 15
    }
}

impl fmt::Display for XopEncodedInstruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let bytes = self.assemble();
        write!(f, "XOP[{}] ", bytes.len())?;
        for b in &bytes {
            write!(f, "{:02X} ", b)?;
        }
        Ok(())
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    3DNow! Instruction Encoding                             ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// 3DNow! instruction representation.
#[derive(Debug, Clone)]
pub struct TdNowInstruction {
    /// 3DNow! immediate byte (opcode selector).
    pub imm8: u8,
    /// Mnemonic name.
    pub mnemonic: &'static str,
    /// Description.
    pub description: &'static str,
    /// Whether this instruction operates on register pairs.
    pub uses_pairing: bool,
}

/// 3DNow! instruction catalog.
pub struct TdNowCatalog;

impl TdNowCatalog {
    /// All 3DNow! instructions (immediate byte → mnemonic).
    pub fn all_instructions() -> Vec<TdNowInstruction> {
        vec![
            TdNowInstruction {
                imm8: tdnow_opcodes::PI2FD,
                mnemonic: "pi2fd",
                description: "Packed 32-bit Integer to Float",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PI2FW,
                mnemonic: "pi2fw",
                description: "Packed 16-bit Integer to Float",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PF2ID,
                mnemonic: "pf2id",
                description: "Packed Float to 32-bit Integer",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PF2IW,
                mnemonic: "pf2iw",
                description: "Packed Float to 16-bit Integer",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFACC,
                mnemonic: "pfacc",
                description: "Packed Float Accumulate",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFADD,
                mnemonic: "pfadd",
                description: "Packed Float Add",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFCMPEQ,
                mnemonic: "pfcmpeq",
                description: "Packed Float Compare Equal",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFCMPGE,
                mnemonic: "pfcmpge",
                description: "Packed Float Compare >= ",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFCMPGT,
                mnemonic: "pfcmpgt",
                description: "Packed Float Compare >",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFMAX,
                mnemonic: "pfmax",
                description: "Packed Float Maximum",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFMIN,
                mnemonic: "pfmin",
                description: "Packed Float Minimum",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFMUL,
                mnemonic: "pfmul",
                description: "Packed Float Multiply",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFNACC,
                mnemonic: "pfnacc",
                description: "Packed Float Negative Accumulate",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFPNACC,
                mnemonic: "pfpnacc",
                description: "Packed Float Pos-Neg Accumulate",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFRCP,
                mnemonic: "pfrcp",
                description: "Packed Float Reciprocal Approx",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFRCPIT1,
                mnemonic: "pfrcpit1",
                description: "Packed Float Reciprocal Iter1",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFRCPIT2,
                mnemonic: "pfrcpit2",
                description: "Packed Float Reciprocal Iter2",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFRSQIT1,
                mnemonic: "pfrsqit1",
                description: "Packed Float RSQRT Iter1",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFRSQRT,
                mnemonic: "pfrsqrt",
                description: "Packed Float RSQRT Approx",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFSUB,
                mnemonic: "pfsub",
                description: "Packed Float Subtract",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PFSUBR,
                mnemonic: "pfsubr",
                description: "Packed Float Reverse Subtract",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PMULHRW,
                mnemonic: "pmulhrw",
                description: "Packed Multiply High Round Word",
                uses_pairing: false,
            },
            TdNowInstruction {
                imm8: tdnow_opcodes::PAVGUSB,
                mnemonic: "pavgusb",
                description: "Packed Average Unsigned Byte",
                uses_pairing: false,
            },
        ]
    }

    /// Look up a 3DNow! instruction by immediate byte.
    pub fn lookup(imm8: u8) -> Option<TdNowInstruction> {
        Self::all_instructions()
            .into_iter()
            .find(|inst| inst.imm8 == imm8)
    }

    /// Check if a byte is a valid 3DNow! immediate opcode.
    pub fn is_valid_tdnow_opcode(imm8: u8) -> bool {
        Self::lookup(imm8).is_some()
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    3DNow! Encoded Instruction                              ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Complete 3DNow! encoded instruction.
#[derive(Debug, Clone)]
pub struct TdNowEncodedInstruction {
    /// Instruction bytes (0F 0F ModR/M imm8 [disp]).
    pub bytes: Vec<u8>,
    /// ModR/M byte.
    pub modrm: Option<u8>,
    /// 3DNow! immediate opcode selector.
    pub imm8: u8,
    /// Displacement bytes.
    pub displacement: Vec<u8>,
    /// Mnemonic.
    pub mnemonic: Option<&'static str>,
}

impl TdNowEncodedInstruction {
    /// Create a new 3DNow! instruction.
    pub fn new(imm8: u8) -> Self {
        Self {
            bytes: Vec::new(),
            modrm: None,
            imm8,
            displacement: Vec::new(),
            mnemonic: TdNowCatalog::lookup(imm8).map(|i| i.mnemonic),
        }
    }

    /// Assemble the full instruction.
    pub fn assemble(&self) -> Vec<u8> {
        let mut bytes = vec![TDNOW_ESCAPE_0F, TDNOW_ESCAPE_SECOND];
        if let Some(modrm) = self.modrm {
            bytes.push(modrm);
        }
        bytes.push(self.imm8);
        bytes.extend_from_slice(&self.displacement);
        bytes
    }

    /// Total instruction length.
    pub fn total_length(&self) -> u16 {
        let mut len: u16 = 2; // 0F 0F
        if self.modrm.is_some() {
            len += 1;
        }
        len += 1; // imm8
        len += self.displacement.len() as u16;
        len
    }

    /// Check if valid (<= 15 bytes).
    pub fn is_valid(&self) -> bool {
        self.total_length() <= 15
    }

    /// Get the 3DNow! mnemonic.
    pub fn mnemonic_str(&self) -> &str {
        self.mnemonic.unwrap_or("???")
    }
}

impl fmt::Display for TdNowEncodedInstruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let bytes = self.assemble();
        write!(f, "3DNow! ")?;
        for b in &bytes {
            write!(f, "{:02X} ", b)?;
        }
        Ok(())
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    FEMMS Encoding                                          ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// FEMMS (Fast Entry/Exit Multimedia State) encoder.
///
/// FEMMS is a faster version of EMMS that only clears the FPU tag word
/// without saving/restoring the full MMX state, making it more efficient
/// for transitions between MMX/3DNow! and x87 FPU code.
#[derive(Debug, Clone)]
pub struct FemmsEncoder;

impl FemmsEncoder {
    /// FEMMS opcode bytes.
    pub const OPCODE: [u8; 2] = FEMMS_OPCODE;

    /// Encode FEMMS (0F 0E, no ModR/M, no operands).
    pub fn encode() -> Vec<u8> {
        Self::OPCODE.to_vec()
    }

    /// FEMMS instruction length.
    pub const LENGTH: u8 = 2;

    /// Check if bytes represent FEMMS.
    pub fn is_femms(bytes: &[u8]) -> bool {
        bytes.len() >= 2 && bytes[0] == 0x0F && bytes[1] == 0x0E
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    PREFETCH / PREFETCHW Encoding                           ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// PREFETCH and PREFETCHW encoder.
///
/// PREFETCH (0F 0D /0) — prefetch data into cache (level controlled by ModR/M reg field).
/// PREFETCHW (0F 0D /1) — prefetch data with write intent.
#[derive(Debug, Clone)]
pub struct PrefetchEncoder;

impl PrefetchEncoder {
    /// PREFETCH opcode prefix (0F 0D).
    pub const PREFIX: [u8; 2] = PREFETCH_OPCODE_PREFIX;

    /// PREFETCH variants by ModR/M reg field:
    /// reg=0: PREFETCH (temporal, all cache levels)
    /// reg=1: PREFETCHW (prefetch with write intent)
    /// reg=2: PREFETCHT0 (temporal, L1 only)
    /// reg=3: PREFETCHT1 (temporal, L2 only)
    /// reg=4: PREFETCHT2 (temporal, L3 only)
    /// reg=5: PREFETCHNTA (non-temporal, all cache levels)

    /// PREFETCH level variants.
    pub const PREFETCH_VARIANTS: [(&str, u8); 8] = [
        ("prefetch", 0),    // reg=0: PREFETCH
        ("prefetchw", 1),   // reg=1: PREFETCHW
        ("prefetcht0", 2),  // reg=2: PREFETCHT0 (L1)
        ("prefetcht1", 3),  // reg=3: PREFETCHT1 (L2)
        ("prefetcht2", 4),  // reg=4: PREFETCHT2 (L3)
        ("prefetchnta", 5), // reg=5: PREFETCHNTA
        ("prefetch", 6),    // reg=6: reserved (treated as PREFETCH)
        ("prefetch", 7),    // reg=7: reserved (treated as PREFETCH)
    ];

    /// Encode PREFETCH/PREFETCHW with a memory operand.
    ///
    /// Format: 0F 0D /r [ModR/M] [SIB] [disp]
    /// ModR/M reg field selects the prefetch variant.
    pub fn encode(reg_field: u8, modrm_byte: u8, sib: Option<u8>, disp: &[u8]) -> Vec<u8> {
        let mut bytes = vec![0x0F, 0x0D];
        let modrm = (modrm_byte & 0xC7) | ((reg_field & 0x07) << 3);
        bytes.push(modrm);
        if let Some(s) = sib {
            bytes.push(s);
        }
        bytes.extend_from_slice(disp);
        bytes
    }

    /// Encode PREFETCHT0 (temporal prefetch to L1).
    pub fn encode_prefetcht0(modrm_byte: u8, sib: Option<u8>, disp: &[u8]) -> Vec<u8> {
        Self::encode(2, modrm_byte, sib, disp)
    }

    /// Encode PREFETCHT1 (temporal prefetch to L2).
    pub fn encode_prefetcht1(modrm_byte: u8, sib: Option<u8>, disp: &[u8]) -> Vec<u8> {
        Self::encode(3, modrm_byte, sib, disp)
    }

    /// Encode PREFETCHT2 (temporal prefetch to L3).
    pub fn encode_prefetcht2(modrm_byte: u8, sib: Option<u8>, disp: &[u8]) -> Vec<u8> {
        Self::encode(4, modrm_byte, sib, disp)
    }

    /// Encode PREFETCHNTA (non-temporal prefetch).
    pub fn encode_prefetchnta(modrm_byte: u8, sib: Option<u8>, disp: &[u8]) -> Vec<u8> {
        Self::encode(5, modrm_byte, sib, disp)
    }

    /// Encode PREFETCHW (prefetch with write intent).
    pub fn encode_prefetchw(modrm_byte: u8, sib: Option<u8>, disp: &[u8]) -> Vec<u8> {
        Self::encode(1, modrm_byte, sib, disp)
    }

    /// Get the mnemonic for a given ModR/M reg field.
    pub fn variant_name(reg_field: u8) -> &'static str {
        Self::PREFETCH_VARIANTS
            .iter()
            .find(|&&(_, r)| r == (reg_field & 0x07))
            .map(|&(name, _)| name)
            .unwrap_or("prefetch")
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    3DNow! Register Pairing                                 ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// 3DNow! register pairing for 64-bit → 128-bit operations.
///
/// Some 3DNow! instructions operate on pairs of MMX registers logically
/// treated as a single 128-bit value. This is relevant for instructions
/// that process 4 single-precision floats (2 per MMX register).
#[derive(Debug, Clone)]
pub struct TdNowRegisterPairing;

impl TdNowRegisterPairing {
    /// Maximum MMX register index.
    pub const MAX_MMX_REG: u8 = 7;

    /// MMX register count.
    pub const MMX_REG_COUNT: u8 = 8;

    /// Check if a register is a valid MMX register (0-7).
    pub fn is_valid_mmx_reg(reg: u8) -> bool {
        reg <= Self::MAX_MMX_REG
    }

    /// Form a register pair (reg, reg+1). Returns None if reg is out of
    /// pairing range.
    pub fn form_pair(low_reg: u8) -> Option<(u8, u8)> {
        if low_reg < Self::MAX_MMX_REG {
            Some((low_reg, low_reg + 1))
        } else {
            None
        }
    }

    /// Check if two registers form a valid sequential pair.
    pub fn is_valid_pair(low: u8, high: u8) -> bool {
        high == low + 1 && low < Self::MAX_MMX_REG
    }

    /// Validate that a given register number can be used in a pair.
    pub fn can_form_pair(reg: u8) -> bool {
        reg < Self::MAX_MMX_REG
    }

    /// Get all valid register pairs.
    pub fn all_pairs() -> Vec<(u8, u8)> {
        (0..7).map(|r| (r, r + 1)).collect()
    }

    /// Register pair name (e.g., "mm0/mm1").
    pub fn pair_name(low: u8, high: u8) -> String {
        format!("mm{}/mm{}", low, high)
    }

    /// Check if an instruction is known to use register pairing.
    /// Most 3DNow! instructions operate on individual MMX registers,
    /// but certain enhanced 3DNow! extensions treat them as pairs.
    pub fn instruction_uses_pairing(_imm8: u8) -> bool {
        // Most 3DNow! instructions do NOT use pairing.
        // Enhanced 3DNow! (Athlon) has a few paired operations.
        // For simplicity: PFACC and PFPNACC are sometimes documented
        // with pair semantics.
        false
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    Main X86XOP3DNowEncoding Struct                         ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Main entry point for X86 XOP and 3DNow! encoding.
///
/// `X86XOP3DNowEncoding` provides the complete interface for AMD XOP prefix
/// generation (3-byte XOP for Bulldozer/Piledriver/Steamroller/Excavator),
/// AMD 3DNow! encoding (0F 0F opcode map with immediate byte), PREFETCH/
/// PREFETCHW encoding, FEMMS, and 3DNow! register pairing.
#[derive(Debug, Clone, Default)]
pub struct X86XOP3DNowEncoding {
    /// XOP instruction catalog lookup.
    pub xop_catalog: HashMap<(u8, u8), &'static str>,
    /// 3DNow! instruction catalog lookup.
    pub tdnow_catalog: HashMap<u8, TdNowInstruction>,
    /// Default XOP vector length.
    pub default_xop_vl: VexVectorLength,
}

impl X86XOP3DNowEncoding {
    /// Create a new instance with populated catalogs.
    pub fn new() -> Self {
        let mut xop_catalog = HashMap::new();
        for (name, op, _) in XopInstructionCatalog::map8_instructions() {
            xop_catalog.insert((XOP_MAP8, op), name);
        }
        for (name, op, _) in XopInstructionCatalog::map8_shift_instructions() {
            xop_catalog.insert((XOP_MAP8, op), name);
        }
        for (name, op, _) in XopInstructionCatalog::map9_instructions() {
            xop_catalog.insert((XOP_MAP9, op), name);
        }

        let mut tdnow_catalog = HashMap::new();
        for inst in TdNowCatalog::all_instructions() {
            tdnow_catalog.insert(inst.imm8, inst);
        }

        Self {
            xop_catalog,
            tdnow_catalog,
            default_xop_vl: VexVectorLength::L128,
        }
    }

    // ── XOP Methods ──────────────────────────────────────────────────────────

    /// Build an XopPrefixConfig.
    pub fn xop_config(
        &self,
        map: XopOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
        w: bool,
    ) -> XopPrefixConfig {
        XopPrefixConfig::from_registers(map, prefix, vl, src1_reg, dest_reg, src2_reg, None, w)
    }

    /// Encode an XOP prefix.
    pub fn encode_xop_prefix(&self, config: &XopPrefixConfig) -> Vec<u8> {
        XopPrefixBuilder::build_vec(config)
    }

    /// Encode a full XOP instruction (reg, reg, reg).
    pub fn encode_xop_rrr(
        &self,
        map: XopOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        opcode: u8,
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
    ) -> XopEncodedInstruction {
        let config = self.xop_config(map, prefix, vl, dest_reg, src1_reg, src2_reg, false);
        let xop_bytes = XopPrefixBuilder::build_vec(&config);
        let modrm = 0xC0 | ((dest_reg & 0x07) << 3) | (src2_reg & 0x07);
        let mnemonic = self.xop_catalog.get(&(map.mmmmm(), opcode)).copied();

        XopEncodedInstruction {
            xop_prefix: xop_bytes,
            opcode: vec![opcode],
            modrm: Some(modrm),
            sib: None,
            displacement: vec![],
            immediate: vec![],
            map,
            mnemonic,
        }
    }

    /// Encode an XOP instruction with immediate byte.
    pub fn encode_xop_with_imm(
        &self,
        map: XopOpcodeMap,
        prefix: VexMandatoryPrefix,
        vl: VexVectorLength,
        opcode: u8,
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
        imm8: u8,
    ) -> XopEncodedInstruction {
        let mut instr = self.encode_xop_rrr(map, prefix, vl, opcode, dest_reg, src1_reg, src2_reg);
        instr.immediate = vec![imm8];
        instr
    }

    /// Encode a specific named XOP instruction by mnemonic.
    pub fn encode_named_xop(
        &self,
        mnemonic: &str,
        dest_reg: u8,
        src1_reg: u8,
        src2_reg: u8,
    ) -> Option<XopEncodedInstruction> {
        // Search catalog for the mnemonic
        for (&(map_val, opcode), &name) in &self.xop_catalog {
            if name == mnemonic {
                let map = XopOpcodeMap::from_mmmmm(map_val)?;
                return Some(self.encode_xop_rrr(
                    map,
                    VexMandatoryPrefix::None,
                    self.default_xop_vl,
                    opcode,
                    dest_reg,
                    src1_reg,
                    src2_reg,
                ));
            }
        }
        None
    }

    /// Look up an XOP instruction by map and opcode.
    pub fn lookup_xop(&self, map: u8, opcode: u8) -> Option<&'static str> {
        XopInstructionCatalog::lookup(map, opcode)
    }

    /// Decode an XOP prefix from bytes.
    pub fn decode_xop(&self, bytes: &[u8]) -> Option<(XopDecodedPrefix, usize)> {
        XopDecodedPrefix::decode_from_slice(bytes)
    }

    /// Compute XOP instruction length.
    pub fn xop_instruction_length(
        opcode_size: u8,
        has_modrm: bool,
        has_sib: bool,
        disp_size: u8,
        imm_size: u8,
    ) -> u16 {
        let prefix: u16 = 3;
        let op: u16 = opcode_size as u16;
        let modrm: u16 = if has_modrm { 1 } else { 0 };
        let sib: u16 = if has_sib { 1 } else { 0 };
        let disp: u16 = disp_size as u16;
        let imm: u16 = imm_size as u16;
        prefix + op + modrm + sib + disp + imm
    }

    // ── 3DNow! Methods ────────────────────────────────────────────────────────

    /// Encode a 3DNow! instruction.
    pub fn encode_tdnow(
        &self,
        imm8: u8,
        dest_reg: u8,
        src_reg_or_mem: u8,
        is_memory: bool,
        disp: Option<i32>,
    ) -> TdNowEncodedInstruction {
        let mut instr = TdNowEncodedInstruction::new(imm8);

        let modrm = if is_memory {
            // Mod=00 (unless displacement), reg=dest (ignored for some), rm=mem
            if let Some(d) = disp {
                if d >= -128 && d <= 127 {
                    // disp8
                    instr.displacement = vec![d as u8];
                    0x40 | ((dest_reg & 0x07) << 3) | (src_reg_or_mem & 0x07)
                } else {
                    // disp32
                    instr.displacement = d.to_le_bytes().to_vec();
                    0x80 | ((dest_reg & 0x07) << 3) | (src_reg_or_mem & 0x07)
                }
            } else {
                // No displacement
                0x00 | ((dest_reg & 0x07) << 3) | (src_reg_or_mem & 0x07)
            }
        } else {
            // Register direct: Mod=11
            0xC0 | ((dest_reg & 0x07) << 3) | (src_reg_or_mem & 0x07)
        };
        instr.modrm = Some(modrm);
        instr.bytes = instr.assemble();

        instr
    }

    /// Encode a 3DNow! register-register instruction.
    pub fn encode_tdnow_rr(&self, imm8: u8, dest_mm: u8, src_mm: u8) -> TdNowEncodedInstruction {
        self.encode_tdnow(imm8, dest_mm, src_mm, false, None)
    }

    /// Encode FEMMS.
    pub fn encode_femms(&self) -> Vec<u8> {
        FemmsEncoder::encode()
    }

    /// Encode PREFETCH.
    pub fn encode_prefetch(
        &self,
        variant: u8,
        mem_base: u8,
        sib: Option<u8>,
        disp: &[u8],
    ) -> Vec<u8> {
        let modrm = if disp.is_empty() {
            0x00 | (mem_base & 0x07)
        } else if disp.len() == 1 {
            0x40 | (mem_base & 0x07)
        } else {
            0x80 | (mem_base & 0x07)
        };
        PrefetchEncoder::encode(variant, modrm, sib, disp)
    }

    /// Look up a 3DNow! instruction by immediate byte.
    pub fn lookup_tdnow(&self, imm8: u8) -> Option<&TdNowInstruction> {
        self.tdnow_catalog.get(&imm8)
    }

    /// Check if an immediate byte is a valid 3DNow! opcode.
    pub fn is_valid_tdnow_opcode(&self, imm8: u8) -> bool {
        self.tdnow_catalog.contains_key(&imm8)
    }

    /// Check if a byte sequence is a 3DNow! instruction prefix (0F 0F).
    pub fn is_tdnow_prefix(bytes: &[u8]) -> bool {
        bytes.len() >= 2 && bytes[0] == TDNOW_ESCAPE_0F && bytes[1] == TDNOW_ESCAPE_SECOND
    }

    // ── Register Pairing ──────────────────────────────────────────────────────

    /// Check MMX register validity.
    pub fn is_valid_mmx_reg(&self, reg: u8) -> bool {
        TdNowRegisterPairing::is_valid_mmx_reg(reg)
    }

    /// Form a register pair.
    pub fn form_pair(&self, low: u8) -> Option<(u8, u8)> {
        TdNowRegisterPairing::form_pair(low)
    }

    /// Get all valid MMX register pairs.
    pub fn all_pairs(&self) -> Vec<(u8, u8)> {
        TdNowRegisterPairing::all_pairs()
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    XOP/3DNow! Assembly Printer                             ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

/// Pretty-printer for XOP and 3DNow! instructions.
#[derive(Debug, Clone)]
pub struct XopTdNowAssemblyPrinter;

impl XopTdNowAssemblyPrinter {
    /// Format an XOP decoded prefix.
    pub fn format_xop_prefix(decoded: &XopDecodedPrefix) -> String {
        format!(
            "XOP R={} X={} B={} mmmmm={:05b} W={} vvvv={:04b} L={} pp={:02b}",
            decoded.r as u8,
            decoded.x as u8,
            decoded.b as u8,
            decoded.mmmmm,
            decoded.w as u8,
            decoded.vvvv,
            decoded.l as u8,
            decoded.pp,
        )
    }

    /// Format a 3DNow! instruction.
    pub fn format_tdnow(instr: &TdNowEncodedInstruction) -> String {
        let mnemonic = instr.mnemonic_str();
        let bytes = instr.assemble();
        let mut s = format!("3DNow! {} [", mnemonic);
        for (i, b) in bytes.iter().enumerate() {
            if i > 0 {
                s.push(' ');
            }
            s.push_str(&format!("{:02X}", b));
        }
        s.push(']');
        s
    }

    /// Print a 3DNow! instruction in Intel syntax.
    pub fn print_tdnow_intel(instr: &TdNowEncodedInstruction) -> String {
        let mnemonic = instr.mnemonic_str();
        if let Some(modrm) = instr.modrm {
            let dest = (modrm >> 3) & 0x07;
            let src = modrm & 0x07;
            let is_mem = (modrm >> 6) != 3;
            if is_mem {
                format!("{} mm{}, [mem]", mnemonic, dest)
            } else {
                format!("{} mm{}, mm{}", mnemonic, dest, src)
            }
        } else {
            format!("{} (no operands)", mnemonic)
        }
    }

    /// Print a PREFETCH instruction in Intel syntax.
    pub fn print_prefetch_intel(variant: u8, modrm: u8) -> String {
        let name = PrefetchEncoder::variant_name(variant);
        let base = modrm & 0x07;
        format!("{} [r{}]", name, base)
    }
}

// ╔══════════════════════════════════════════════════════════════════════════════╗
// ║                    Tests                                                    ║
// ╚══════════════════════════════════════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;

    // ── XOP Constants ──────────────────────────────────────────────────────────

    #[test]
    fn test_xop_constants() {
        assert_eq!(XOP_PREFIX, 0x8F);
        assert_eq!(XOP_MAP8, 0x08);
        assert_eq!(XOP_MAP9, 0x09);
        assert_eq!(XOP_MAPA, 0x0A);
    }

    // ── XOP Opcode Map ─────────────────────────────────────────────────────────

    #[test]
    fn test_xop_opcode_map() {
        assert_eq!(XopOpcodeMap::Map8.mmmmm(), 8);
        assert_eq!(XopOpcodeMap::Map9.mmmmm(), 9);
        assert_eq!(XopOpcodeMap::MapA.mmmmm(), 10);

        assert_eq!(XopOpcodeMap::from_mmmmm(8), Some(XopOpcodeMap::Map8));
        assert_eq!(XopOpcodeMap::from_mmmmm(9), Some(XopOpcodeMap::Map9));
        assert_eq!(XopOpcodeMap::from_mmmmm(10), Some(XopOpcodeMap::MapA));
        assert_eq!(XopOpcodeMap::from_mmmmm(1), None);
        assert_eq!(XopOpcodeMap::from_mmmmm(7), None);
    }

    // ── XopPrefixConfig ────────────────────────────────────────────────────────

    #[test]
    fn test_xop_prefix_config_default() {
        let cfg = XopPrefixConfig::default();
        assert_eq!(cfg.mmmmm, XOP_MAP8);
        assert_eq!(cfg.pp, VEX_PP_NONE);
        assert!(!cfg.w);
        assert!(!cfg.l);
    }

    #[test]
    fn test_xop_prefix_config_prefix_byte_count() {
        let cfg = XopPrefixConfig::new();
        assert_eq!(cfg.prefix_byte_count(), 3);
    }

    #[test]
    fn test_xop_prefix_config_from_registers() {
        let cfg = XopPrefixConfig::from_registers(
            XopOpcodeMap::Map9,
            VexMandatoryPrefix::P66,
            VexVectorLength::L128,
            1,        // vvvv
            8,        // dest (extended)
            9,        // base (extended)
            Some(10), // index (extended)
            true,
        );
        assert!(cfg.r); // dest >= 8
        assert!(cfg.x); // index >= 8
        assert!(cfg.b); // base >= 8
        assert!(cfg.w);
        assert_eq!(cfg.mmmmm, XOP_MAP9);
        assert_eq!(cfg.pp, VexMandatoryPrefix::P66.pp_bits());
    }

    // ── XopPrefixBuilder ───────────────────────────────────────────────────────

    #[test]
    fn test_build_xop_basic() {
        let bytes = XopPrefixBuilder::build(
            true,
            true,
            true,        // R, X, B = 1 (all standard)
            XOP_MAP8,    // map 8
            false,       // W = 0
            0x0E,        // vvvv = ~1
            false,       // L = 0 (128-bit)
            VEX_PP_NONE, // pp = none
        );
        assert_eq!(bytes[0], 0x8F);
        // byte1: ~R=0, ~X=0, ~B=0, mmmmm=8 => 0x08
        assert_eq!(bytes[1], 0x08);
        // byte2: W=0, vvvv=0xE<<3=0x70, L=0, pp=0 => 0x70
        assert_eq!(bytes[2], 0x70);
    }

    #[test]
    fn test_build_xop_with_w_and_l() {
        let bytes = XopPrefixBuilder::build(
            false, false, false,     // R, X, B = 0 (extended)
            XOP_MAP9,  // map 9
            true,      // W = 1
            0x07,      // vvvv = ~8
            true,      // L = 1 (256-bit)
            VEX_PP_66, // pp = 66
        );
        // byte1: ~R=1<<7 | ~X=1<<6 | ~B=1<<5 | 9 = 0xE9
        assert_eq!(bytes[1], 0xE9);
        // byte2: W=1<<7=0x80 | vvvv=7<<3=0x38 | L=1<<2=4 | pp=1 = 0xBD
        assert_eq!(bytes[2], 0xBD);
    }

    #[test]
    fn test_build_xop_from_config() {
        let cfg = XopPrefixConfig::new()
            .with_map(XopOpcodeMap::Map8)
            .with_prefix(VexMandatoryPrefix::P66)
            .with_vector_length(VexVectorLength::L128)
            .with_vvvv(1)
            .with_dest_reg(0)
            .with_base_reg(2);

        let bytes = XopPrefixBuilder::build_from_config(&cfg);
        assert_eq!(bytes[0], 0x8F);
        assert_eq!(bytes.len(), 3);
    }

    #[test]
    fn test_build_xop_from_regs() {
        let bytes = XopPrefixBuilder::build_from_regs(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            0,
            1,
            2,
            false,
        );
        assert_eq!(bytes[0], 0x8F);
        assert_eq!(bytes.len(), 3);
    }

    // ── XopDecodedPrefix ───────────────────────────────────────────────────────

    #[test]
    fn test_decode_xop() {
        let decoded = XopDecodedPrefix::decode(0x08, 0x70);
        assert!(decoded.r);
        assert!(decoded.x);
        assert!(decoded.b);
        assert_eq!(decoded.mmmmm, XOP_MAP8);
        assert!(!decoded.w);
        assert_eq!(decoded.vvvv, 0x0E);
        assert_eq!(decoded.true_vvvv(), 1);
        assert!(!decoded.l);
        assert_eq!(decoded.pp, VEX_PP_NONE);
    }

    #[test]
    fn test_decode_xop_extended() {
        let decoded = XopDecodedPrefix::decode(0xE9, 0xBD);
        assert!(!decoded.r);
        assert!(!decoded.x);
        assert!(!decoded.b);
        assert_eq!(decoded.mmmmm, XOP_MAP9);
        assert!(decoded.w);
        assert_eq!(decoded.vvvv, 0x07);
        assert_eq!(decoded.true_vvvv(), 8);
        assert!(decoded.l);
        assert_eq!(decoded.pp, VEX_PP_66);
    }

    #[test]
    fn test_decode_xop_from_slice() {
        let (d, len) = XopDecodedPrefix::decode_from_slice(&[0x8F, 0x08, 0x70]).unwrap();
        assert_eq!(len, 3);

        assert!(XopDecodedPrefix::decode_from_slice(&[0xC4, 0x08, 0x70]).is_none()); // VEX, not XOP
        assert!(XopDecodedPrefix::decode_from_slice(&[]).is_none());
    }

    // ── XOP Instruction Catalog ────────────────────────────────────────────────

    #[test]
    fn test_xop_catalog_map8() {
        let insts = XopInstructionCatalog::map8_instructions();
        assert!(insts.len() >= 20);
        assert!(insts.iter().any(|(name, _, _)| *name == "vphaddbd"));
    }

    #[test]
    fn test_xop_catalog_map8_shifts() {
        let insts = XopInstructionCatalog::map8_shift_instructions();
        assert!(insts.len() >= 10);
        assert!(insts.iter().any(|(name, _, _)| *name == "vprotb"));
    }

    #[test]
    fn test_xop_catalog_map9() {
        let insts = XopInstructionCatalog::map9_instructions();
        assert!(insts.len() >= 10);
        assert!(insts.iter().any(|(name, _, _)| *name == "vpcmov"));
    }

    #[test]
    fn test_xop_catalog_lookup() {
        assert_eq!(XopInstructionCatalog::lookup(8, 0xC2), Some("vphaddbd"));
        assert_eq!(XopInstructionCatalog::lookup(8, 0x90), Some("vprotb"));
        assert_eq!(XopInstructionCatalog::lookup(9, 0xA0), Some("vpcmov"));
        assert_eq!(XopInstructionCatalog::lookup(8, 0x00), None);
        assert_eq!(XopInstructionCatalog::lookup(1, 0x00), None);
    }

    // ── 3DNow! Constants ───────────────────────────────────────────────────────

    #[test]
    fn test_tdnow_constants() {
        assert_eq!(TDNOW_ESCAPE_0F, 0x0F);
        assert_eq!(TDNOW_ESCAPE_SECOND, 0x0F);
        assert_eq!(FEMMS_OPCODE, [0x0F, 0x0E]);
    }

    #[test]
    fn test_tdnow_opcodes() {
        assert_eq!(tdnow_opcodes::PFADD, 0x9E);
        assert_eq!(tdnow_opcodes::PFMUL, 0xB4);
        assert_eq!(tdnow_opcodes::PFSUB, 0x9A);
        assert_eq!(tdnow_opcodes::PAVGUSB, 0xBF);
    }

    // ── 3DNow! Catalog ─────────────────────────────────────────────────────────

    #[test]
    fn test_tdnow_catalog_size() {
        assert_eq!(TdNowCatalog::all_instructions().len(), 23);
    }

    #[test]
    fn test_tdnow_catalog_lookup() {
        let inst = TdNowCatalog::lookup(tdnow_opcodes::PFADD).unwrap();
        assert_eq!(inst.mnemonic, "pfadd");
        assert_eq!(inst.description, "Packed Float Add");

        let inst = TdNowCatalog::lookup(tdnow_opcodes::PFRCP).unwrap();
        assert_eq!(inst.mnemonic, "pfrcp");

        assert!(TdNowCatalog::lookup(0x00).is_none());
    }

    #[test]
    fn test_tdnow_is_valid_opcode() {
        assert!(TdNowCatalog::is_valid_tdnow_opcode(tdnow_opcodes::PFADD));
        assert!(!TdNowCatalog::is_valid_tdnow_opcode(0x00));
        assert!(!TdNowCatalog::is_valid_tdnow_opcode(0xFF));
    }

    // ── FEMMS Encoder ──────────────────────────────────────────────────────────

    #[test]
    fn test_femms_encode() {
        let bytes = FemmsEncoder::encode();
        assert_eq!(bytes, vec![0x0F, 0x0E]);
        assert_eq!(FemmsEncoder::LENGTH, 2);
    }

    #[test]
    fn test_femms_detect() {
        assert!(FemmsEncoder::is_femms(&[0x0F, 0x0E]));
        assert!(!FemmsEncoder::is_femms(&[0x0F, 0x0F]));
        assert!(!FemmsEncoder::is_femms(&[0x0F]));
    }

    // ── PREFETCH Encoder ───────────────────────────────────────────────────────

    #[test]
    fn test_prefetch_encode() {
        let bytes = PrefetchEncoder::encode(0, 0x00, None, &[]);
        assert_eq!(bytes, vec![0x0F, 0x0D, 0x00]);
    }

    #[test]
    fn test_prefetchw_encode() {
        // PREFETCHW: reg=1
        let bytes = PrefetchEncoder::encode(1, 0x00, None, &[]);
        assert_eq!(bytes, vec![0x0F, 0x0D, 0x08]); // reg=1 << 3 = 8
    }

    #[test]
    fn test_prefetch_variant_names() {
        assert_eq!(PrefetchEncoder::variant_name(0), "prefetch");
        assert_eq!(PrefetchEncoder::variant_name(1), "prefetchw");
        assert_eq!(PrefetchEncoder::variant_name(2), "prefetcht0");
        assert_eq!(PrefetchEncoder::variant_name(3), "prefetcht1");
        assert_eq!(PrefetchEncoder::variant_name(4), "prefetcht2");
        assert_eq!(PrefetchEncoder::variant_name(5), "prefetchnta");
    }

    #[test]
    fn test_prefetch_with_disp() {
        // PREFETCHT0 [eax+4]
        let bytes = PrefetchEncoder::encode_prefetcht0(0x00, None, &[0x04]);
        assert_eq!(&bytes[0..2], &[0x0F, 0x0D]);
        // reg=2<<3 = 0x10, mod=01 (disp8), rm=0
        assert_eq!(bytes[2], 0x50);
        assert_eq!(bytes[3], 0x04);
    }

    // ── 3DNow! Register Pairing ────────────────────────────────────────────────

    #[test]
    fn test_tdnow_register_pairing() {
        assert!(TdNowRegisterPairing::is_valid_mmx_reg(0));
        assert!(TdNowRegisterPairing::is_valid_mmx_reg(7));
        assert!(!TdNowRegisterPairing::is_valid_mmx_reg(8));

        assert_eq!(TdNowRegisterPairing::form_pair(0), Some((0, 1)));
        assert_eq!(TdNowRegisterPairing::form_pair(6), Some((6, 7)));
        assert_eq!(TdNowRegisterPairing::form_pair(7), None);

        assert!(TdNowRegisterPairing::is_valid_pair(0, 1));
        assert!(!TdNowRegisterPairing::is_valid_pair(0, 2));
        assert!(!TdNowRegisterPairing::is_valid_pair(7, 8));
    }

    #[test]
    fn test_tdnow_register_pairing_all() {
        let pairs = TdNowRegisterPairing::all_pairs();
        assert_eq!(pairs.len(), 7);
        assert_eq!(pairs[0], (0, 1));
        assert_eq!(pairs[6], (6, 7));
    }

    #[test]
    fn test_tdnow_pair_name() {
        assert_eq!(TdNowRegisterPairing::pair_name(0, 1), "mm0/mm1");
        assert_eq!(TdNowRegisterPairing::pair_name(3, 4), "mm3/mm4");
    }

    // ── TdNowEncodedInstruction ────────────────────────────────────────────────

    #[test]
    fn test_tdnow_encoded_instruction_new() {
        let instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        assert_eq!(instr.imm8, tdnow_opcodes::PFADD);
        assert_eq!(instr.mnemonic, Some("pfadd"));
    }

    #[test]
    fn test_tdnow_assemble_rr() {
        // pfadd mm0, mm1: 0F 0F /r C0 (Mod=11, reg=0, rm=1) C0 | 0<<3 | 1 = 0xC1
        let mut instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        instr.modrm = Some(0xC0 | ((0 & 0x07) << 3) | (1 & 0x07));
        instr.bytes = instr.assemble();
        assert_eq!(instr.bytes, vec![0x0F, 0x0F, 0xC1, tdnow_opcodes::PFADD]);
    }

    #[test]
    fn test_tdnow_total_length() {
        let instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        assert_eq!(instr.total_length(), 3); // 2(prefix) + 1(imm8) = 3
    }

    // ── X86XOP3DNowEncoding ────────────────────────────────────────────────────

    #[test]
    fn test_xop3dnow_encoding_new() {
        let enc = X86XOP3DNowEncoding::new();
        assert!(!enc.xop_catalog.is_empty());
        assert_eq!(enc.tdnow_catalog.len(), 23);
        assert_eq!(enc.default_xop_vl, VexVectorLength::L128);
    }

    #[test]
    fn test_encode_xop_rrr() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_xop_rrr(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            0xC2, // vphaddbd
            0,
            1,
            2,
        );
        assert_eq!(instr.opcode, vec![0xC2]);
        assert!(instr.modrm.is_some());
        assert_eq!(instr.xop_prefix.len(), 3);
        assert!(instr.is_valid());
        assert_eq!(instr.mnemonic, Some("vphaddbd"));
    }

    #[test]
    fn test_encode_xop_with_imm() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_xop_with_imm(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            0x90, // vprotb
            0,
            1,
            2,
            3, // rotate by 3
        );
        assert_eq!(instr.immediate, vec![3]);
    }

    #[test]
    fn test_encode_named_xop() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_named_xop("vprotb", 0, 1, 2).unwrap();
        assert_eq!(instr.opcode, vec![0x90]);
        assert_eq!(instr.mnemonic, Some("vprotb"));

        // Non-existent mnemonic
        assert!(enc.encode_named_xop("nonexistent", 0, 1, 2).is_none());
    }

    #[test]
    fn test_encode_tdnow_rr() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_tdnow_rr(tdnow_opcodes::PFADD, 0, 1);
        assert_eq!(instr.imm8, tdnow_opcodes::PFADD);
        assert!(instr.modrm.is_some());
        // Mod=11, reg=0<<3=0, rm=1 -> 0xC0 | 0 | 1 = 0xC1
        assert_eq!(instr.modrm.unwrap(), 0xC1);
    }

    #[test]
    fn test_encode_femms() {
        let enc = X86XOP3DNowEncoding::new();
        let bytes = enc.encode_femms();
        assert_eq!(bytes, vec![0x0F, 0x0E]);
    }

    #[test]
    fn test_encode_prefetch() {
        let enc = X86XOP3DNowEncoding::new();
        let bytes = enc.encode_prefetch(1, 0, None, &[]); // PREFETCHW
        assert_eq!(bytes, vec![0x0F, 0x0D, 0x08]); // reg=1 << 3 = 8
    }

    #[test]
    fn test_lookup_tdnow() {
        let enc = X86XOP3DNowEncoding::new();
        let inst = enc.lookup_tdnow(tdnow_opcodes::PFMUL).unwrap();
        assert_eq!(inst.mnemonic, "pfmul");

        assert!(enc.lookup_tdnow(0x00).is_none());
    }

    #[test]
    fn test_is_valid_tdnow_opcode() {
        let enc = X86XOP3DNowEncoding::new();
        assert!(enc.is_valid_tdnow_opcode(tdnow_opcodes::PFSUB));
        assert!(!enc.is_valid_tdnow_opcode(0xFF));
    }

    #[test]
    fn test_is_tdnow_prefix() {
        assert!(X86XOP3DNowEncoding::is_tdnow_prefix(&[0x0F, 0x0F, 0x9E]));
        assert!(!X86XOP3DNowEncoding::is_tdnow_prefix(&[0x0F, 0x0E]));
        assert!(!X86XOP3DNowEncoding::is_tdnow_prefix(&[0x0F]));
    }

    #[test]
    fn test_form_pair() {
        let enc = X86XOP3DNowEncoding::new();
        assert_eq!(enc.form_pair(0), Some((0, 1)));
        assert_eq!(enc.form_pair(6), Some((6, 7)));
        assert_eq!(enc.form_pair(7), None);
    }

    #[test]
    fn test_all_pairs() {
        let enc = X86XOP3DNowEncoding::new();
        let pairs = enc.all_pairs();
        assert_eq!(pairs.len(), 7);
    }

    #[test]
    fn test_xop_instruction_length() {
        // XOP(3) + opcode(1) + ModR/M(1) = 5
        let len = X86XOP3DNowEncoding::xop_instruction_length(1, true, false, 0, 0);
        assert_eq!(len, 5);

        // XOP(3) + opcode(1) + ModR/M(1) + SIB(1) + disp32(4) + imm8(1) = 11
        let len = X86XOP3DNowEncoding::xop_instruction_length(1, true, true, 4, 1);
        assert_eq!(len, 11);
    }

    // ── XopTdNowAssemblyPrinter ────────────────────────────────────────────────

    #[test]
    fn test_assembly_printer_xop() {
        let decoded = XopDecodedPrefix::decode(0x08, 0x70);
        let s = XopTdNowAssemblyPrinter::format_xop_prefix(&decoded);
        assert!(s.contains("XOP"));
        assert!(s.contains("R="));
        assert!(s.contains("mmmmm="));
    }

    #[test]
    fn test_assembly_printer_tdnow() {
        let instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        let s = XopTdNowAssemblyPrinter::format_tdnow(&instr);
        assert!(s.contains("3DNow!"));
        assert!(s.contains("pfadd"));
    }

    #[test]
    fn test_assembly_printer_tdnow_intel() {
        let mut instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        instr.modrm = Some(0xC0 | ((0 & 0x07) << 3) | (1 & 0x07));
        let s = XopTdNowAssemblyPrinter::print_tdnow_intel(&instr);
        assert!(s.contains("pfadd"));
        assert!(s.contains("mm0"));
        assert!(s.contains("mm1"));
    }

    #[test]
    fn test_assembly_printer_prefetch() {
        let s = XopTdNowAssemblyPrinter::print_prefetch_intel(1, 0x00);
        assert!(s.contains("prefetchw"));
        assert!(s.contains("[r0]"));
    }

    // ── Integration Tests ──────────────────────────────────────────────────────

    #[test]
    fn test_roundtrip_xop_encode_decode() {
        let bytes = XopPrefixBuilder::build_from_regs(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            0,
            1,
            2,
            false,
        );
        let (decoded, len) = XopDecodedPrefix::decode_from_slice(&bytes).unwrap();
        assert_eq!(len, 3);
        assert_eq!(decoded.mmmmm, XOP_MAP8);
        assert_eq!(decoded.true_vvvv(), 1);
    }

    #[test]
    fn test_full_xop_instruction_assemble() {
        let config = XopPrefixConfig::new()
            .with_map(XopOpcodeMap::Map8)
            .with_vvvv(1)
            .with_dest_reg(0)
            .with_base_reg(2);

        let mut instr = XopEncodedInstruction::new(XopOpcodeMap::Map8);
        instr.xop_prefix = XopPrefixBuilder::build_vec(&config);
        instr.opcode = vec![0xC2]; // vphaddbd
        instr.modrm = Some(0xC0 | ((0 & 0x07) << 3) | (2 & 0x07));

        let assembled = instr.assemble();
        // 3(XOP) + 1(opcode) + 1(ModR/M) = 5
        assert_eq!(assembled.len(), 5);
        assert!(instr.is_valid());
    }

    #[test]
    fn test_full_tdnow_assemble() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_tdnow_rr(tdnow_opcodes::PFMUL, 2, 3);

        let assembled = instr.assemble();
        // 2(0F0F) + 1(ModR/M) + 1(imm8) = 4
        assert_eq!(assembled.len(), 4);
        assert!(instr.is_valid());
    }

    #[test]
    fn test_all_tdnow_opcodes_valid() {
        for inst in TdNowCatalog::all_instructions() {
            assert!(inst.imm8 != 0, "Zero immediate for {}", inst.mnemonic);
        }
    }

    #[test]
    fn test_all_xop_catalog_entries() {
        let enc = X86XOP3DNowEncoding::new();
        // All map 8 entries
        for (name, op, _) in XopInstructionCatalog::map8_instructions() {
            let result = enc.encode_named_xop(name, 0, 1, 2);
            assert!(
                result.is_some(),
                "Failed to encode XOP instruction: {}",
                name
            );
            let instr = result.unwrap();
            assert_eq!(instr.opcode[0], op);
        }
    }

    #[test]
    fn test_no_duplicate_tdnow_immediates() {
        let insts = TdNowCatalog::all_instructions();
        let mut seen = std::collections::HashSet::new();
        for inst in &insts {
            assert!(
                seen.insert(inst.imm8),
                "Duplicate 3DNow! immediate: {:02X}",
                inst.imm8
            );
        }
    }

    #[test]
    fn test_xop_map9_vpcmov() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_named_xop("vpcmov", 0, 1, 2).unwrap();
        assert_eq!(instr.opcode, vec![0xA0]);
        assert_eq!(instr.map, XopOpcodeMap::Map9);
    }

    // ── Expanded XOP Tests ────────────────────────────────────────────────────

    #[test]
    fn test_xop_all_map8_mnemonics_encode() {
        let enc = X86XOP3DNowEncoding::new();
        for (name, _, _) in XopInstructionCatalog::map8_instructions() {
            let result = enc.encode_named_xop(name, 0, 1, 2);
            assert!(
                result.is_some(),
                "XOP Map8 mnemonic should encode: {}",
                name
            );
        }
        for (name, _, _) in XopInstructionCatalog::map8_shift_instructions() {
            let result = enc.encode_named_xop(name, 0, 1, 2);
            assert!(
                result.is_some(),
                "XOP Map8 shift mnemonic should encode: {}",
                name
            );
        }
    }

    #[test]
    fn test_xop_all_map9_mnemonics_encode() {
        let enc = X86XOP3DNowEncoding::new();
        for (name, _, _) in XopInstructionCatalog::map9_instructions() {
            let result = enc.encode_named_xop(name, 0, 1, 2);
            assert!(
                result.is_some(),
                "XOP Map9 mnemonic should encode: {}",
                name
            );
        }
    }

    #[test]
    fn test_xop_map8_vphaddbd_opcode() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_named_xop("vphaddbd", 0, 1, 2).unwrap();
        assert_eq!(instr.opcode, vec![0xC2]);
        assert_eq!(instr.map, XopOpcodeMap::Map8);
    }

    #[test]
    fn test_xop_map8_vprotb_opcode() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_named_xop("vprotb", 0, 1, 2).unwrap();
        assert_eq!(instr.opcode, vec![0x90]);
    }

    #[test]
    fn test_xop_map9_vfrczps_opcode() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_named_xop("vfrczps", 0, 1, 2).unwrap();
        assert_eq!(instr.opcode, vec![0x80]);
        assert_eq!(instr.map, XopOpcodeMap::Map9);
    }

    #[test]
    fn test_xop_map9_vpcomb_opcode() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_named_xop("vpcomb", 0, 1, 2).unwrap();
        assert_eq!(instr.opcode, vec![0x8C]);
        assert_eq!(instr.map, XopOpcodeMap::Map9);
    }

    #[test]
    fn test_xop_with_extended_registers() {
        let cfg = XopPrefixConfig::from_registers(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            10, // vvvv = xmm10
            12, // dest = xmm12
            14, // base = xmm14
            None,
            true, // W=1
        );
        assert!(cfg.r); // dest >= 8
        assert!(cfg.b); // base >= 8
        assert!(cfg.w);
        // vvvv = ~10 = 5
        assert_eq!(cfg.vvvv, 5);
    }

    #[test]
    fn test_xop_with_l256() {
        let cfg = XopPrefixConfig::new().with_vector_length(VexVectorLength::L256);
        assert!(cfg.l);
    }

    #[test]
    fn test_xop_config_all_maps() {
        for map in [XopOpcodeMap::Map8, XopOpcodeMap::Map9, XopOpcodeMap::MapA] {
            let cfg = XopPrefixConfig::new().with_map(map);
            assert_eq!(cfg.mmmmm, map.mmmmm());
        }
    }

    #[test]
    fn test_xop_prefix_decode_roundtrip() {
        let original = XopPrefixConfig::from_registers(
            XopOpcodeMap::Map9,
            VexMandatoryPrefix::PF2,
            VexVectorLength::L256,
            3,
            8,
            9,
            Some(10),
            true,
        );
        let bytes = XopPrefixBuilder::build_vec(&original);
        let (decoded, _) = XopDecodedPrefix::decode_from_slice(&bytes).unwrap();
        let reconstructed = decoded.to_config();

        assert_eq!(reconstructed.r, original.r);
        assert_eq!(reconstructed.x, original.x);
        assert_eq!(reconstructed.b, original.b);
        assert_eq!(reconstructed.mmmmm, original.mmmmm);
        assert_eq!(reconstructed.w, original.w);
        assert_eq!(reconstructed.vvvv, original.vvvv);
        assert_eq!(reconstructed.l, original.l);
        assert_eq!(reconstructed.pp, original.pp);
    }

    // ── Expanded 3DNow! Tests ─────────────────────────────────────────────────

    #[test]
    fn test_tdnow_encode_all_opcodes() {
        let enc = X86XOP3DNowEncoding::new();
        for inst in TdNowCatalog::all_instructions() {
            let instr = enc.encode_tdnow_rr(inst.imm8, 0, 1);
            assert!(instr.is_valid());
            assert_eq!(instr.imm8, inst.imm8);
        }
    }

    #[test]
    fn test_tdnow_encode_memory_operand() {
        let enc = X86XOP3DNowEncoding::new();
        // pfadd mm0, [eax] — no displacement
        let instr = enc.encode_tdnow(tdnow_opcodes::PFADD, 0, 0, true, None);
        assert!(instr.is_valid());
        assert!(instr.modrm.is_some());
        // Mod=00, reg=0, rm=0 => 0x00
        assert_eq!(instr.modrm.unwrap(), 0x00);
        assert!(instr.displacement.is_empty());
    }

    #[test]
    fn test_tdnow_encode_memory_with_disp8() {
        let enc = X86XOP3DNowEncoding::new();
        // pfadd mm0, [eax + 4]
        let instr = enc.encode_tdnow(tdnow_opcodes::PFADD, 0, 0, true, Some(4));
        assert!(instr.is_valid());
        // Mod=01 (disp8), reg=0<<3=0, rm=0 => 0x40 | 0 = 0x40
        assert_eq!(instr.modrm.unwrap(), 0x40);
        assert_eq!(instr.displacement, vec![4u8]);
    }

    #[test]
    fn test_tdnow_encode_memory_with_disp32() {
        let enc = X86XOP3DNowEncoding::new();
        // pfadd mm0, [eax + 1024]
        let instr = enc.encode_tdnow(tdnow_opcodes::PFADD, 0, 0, true, Some(1024));
        assert!(instr.is_valid());
        // Mod=10 (disp32), reg=0, rm=0 => 0x80 | 0 = 0x80
        assert_eq!(instr.modrm.unwrap(), 0x80);
        assert_eq!(instr.displacement, 1024i32.to_le_bytes().to_vec());
    }

    #[test]
    fn test_tdnow_encode_memory_negative_disp8() {
        let enc = X86XOP3DNowEncoding::new();
        // pfadd mm0, [eax - 4]
        let instr = enc.encode_tdnow(tdnow_opcodes::PFADD, 0, 0, true, Some(-4));
        assert!(instr.is_valid());
        assert_eq!(instr.modrm.unwrap(), 0x40);
        assert_eq!(instr.displacement, vec![(-4i8) as u8]);
    }

    #[test]
    fn test_tdnow_mnemonic_lookup_all() {
        for inst in TdNowCatalog::all_instructions() {
            let looked_up = TdNowCatalog::lookup(inst.imm8);
            assert!(looked_up.is_some());
            assert_eq!(looked_up.unwrap().mnemonic, inst.mnemonic);
        }
    }

    #[test]
    fn test_tdnow_display() {
        let instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        let s = format!("{}", instr);
        assert!(s.contains("3DNow!"));
    }

    #[test]
    fn test_tdnow_invalid_opcode_lookup() {
        let enc = X86XOP3DNowEncoding::new();
        assert!(!enc.is_valid_tdnow_opcode(0x00));
        assert!(!enc.is_valid_tdnow_opcode(0xFF));
        assert!(!enc.is_valid_tdnow_opcode(0x42));
    }

    // ── Prefetch Expanded Tests ──────────────────────────────────────────────

    #[test]
    fn test_prefetch_all_variants() {
        for (name, reg) in PrefetchEncoder::PREFETCH_VARIANTS.iter() {
            let bytes = PrefetchEncoder::encode(*reg, 0x00, None, &[]);
            assert_eq!(bytes[0], 0x0F);
            assert_eq!(bytes[1], 0x0D);
            // ModR/M reg field should match
            let reg_in_modrm = (bytes[2] >> 3) & 0x07;
            assert_eq!(reg_in_modrm, *reg, "Reg field mismatch for {}", name);
        }
    }

    #[test]
    fn test_prefetch_with_sib() {
        // PREFETCHT0 [eax + ecx*4]
        let sib = 0x81; // scale=2 (4), index=1 (ecx), base=0 (eax)
        let bytes = PrefetchEncoder::encode_prefetcht0(0x04, Some(sib), &[]);
        assert_eq!(bytes[0], 0x0F);
        assert_eq!(bytes[1], 0x0D);
        // Mod=00, reg=2<<3=0x10, rm=4 (SIB follows)
        assert_eq!(bytes[2], 0x14);
        assert_eq!(bytes[3], sib);
    }

    #[test]
    fn test_prefetch_variant_names_all() {
        for reg in 0..8u8 {
            let name = PrefetchEncoder::variant_name(reg);
            assert!(!name.is_empty());
        }
    }

    #[test]
    fn test_prefetch_encode_convenience() {
        let bytes_t0 = PrefetchEncoder::encode_prefetcht0(0x00, None, &[]);
        assert_eq!(&bytes_t0[0..2], &[0x0F, 0x0D]);
        assert_eq!((bytes_t0[2] >> 3) & 0x07, 2);

        let bytes_t1 = PrefetchEncoder::encode_prefetcht1(0x00, None, &[]);
        assert_eq!((bytes_t1[2] >> 3) & 0x07, 3);

        let bytes_t2 = PrefetchEncoder::encode_prefetcht2(0x00, None, &[]);
        assert_eq!((bytes_t2[2] >> 3) & 0x07, 4);

        let bytes_nta = PrefetchEncoder::encode_prefetchnta(0x00, None, &[]);
        assert_eq!((bytes_nta[2] >> 3) & 0x07, 5);

        let bytes_w = PrefetchEncoder::encode_prefetchw(0x00, None, &[]);
        assert_eq!((bytes_w[2] >> 3) & 0x07, 1);
    }

    // ── XopEncodedInstruction Expanded Tests ──────────────────────────────────

    #[test]
    fn test_xop_encoded_instruction_display() {
        let mut instr = XopEncodedInstruction::new(XopOpcodeMap::Map8);
        instr.xop_prefix = vec![0x8F, 0x08, 0x70];
        instr.opcode = vec![0xC2];
        instr.modrm = Some(0xC0);
        let s = format!("{}", instr);
        assert!(s.contains("XOP"));
        assert!(s.contains("8F"));
    }

    #[test]
    fn test_xop_encoded_instruction_assemble_roundtrip() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_xop_rrr(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            0xC2,
            0,
            1,
            2,
        );
        let assembled = instr.assemble();
        // Now decode back from the assembled bytes
        assert!(assembled.len() >= 4);
        // First byte should be XOP prefix
        assert_eq!(assembled[0], XOP_PREFIX);
    }

    #[test]
    fn test_xop_catalog_if_let_lookup() {
        // Test that lookup doesn't panic on unexpected inputs
        assert!(XopInstructionCatalog::lookup(0, 0x00).is_none());
        assert!(XopInstructionCatalog::lookup(255, 0x00).is_none());
        assert!(XopInstructionCatalog::lookup(8, 255).is_none());
    }

    // ── XopDecodedPrefix Expanded Tests ───────────────────────────────────────

    #[test]
    fn test_xop_decoded_effective_regs() {
        let decoded = XopDecodedPrefix::decode(0x08, 0x70);
        // R=1 (reg < 8): effective reg of 3 = 3
        assert_eq!(decoded.effective_reg_r(3), 3);

        let decoded = XopDecodedPrefix::decode(0xE8, 0x70);
        // R=0 (reg >= 8): effective reg of 3 = 11
        assert_eq!(decoded.effective_reg_r(3), 11);
    }

    #[test]
    fn test_xop_decoded_display() {
        let d = XopDecodedPrefix::decode(0x08, 0x70);
        let s = format!("{}", d);
        assert!(s.contains("XOP"));
        assert!(s.contains("R="));
        assert!(s.contains("mmmmm="));
    }

    #[test]
    fn test_xop_opcode_map_display() {
        assert_eq!(format!("{}", XopOpcodeMap::Map8), "XOP8");
        assert_eq!(format!("{}", XopOpcodeMap::Map9), "XOP9");
        assert_eq!(format!("{}", XopOpcodeMap::MapA), "XOPA");
    }

    // ── TdNowEncodedInstruction Expanded Tests ────────────────────────────────

    #[test]
    fn test_tdnow_encoded_instruction_defaults() {
        let instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        assert_eq!(instr.imm8, tdnow_opcodes::PFADD);
        assert!(instr.modrm.is_none());
        assert!(instr.displacement.is_empty());
        assert_eq!(instr.mnemonic_str(), "pfadd");
    }

    #[test]
    fn test_tdnow_unknown_opcode_mnemonic() {
        let instr = TdNowEncodedInstruction::new(0xFF);
        assert_eq!(instr.mnemonic_str(), "???");
    }

    // ── Register Pairing Expanded Tests ───────────────────────────────────────

    #[test]
    fn test_register_pairing_can_form_pair() {
        for reg in 0..7u8 {
            assert!(TdNowRegisterPairing::can_form_pair(reg));
        }
        assert!(!TdNowRegisterPairing::can_form_pair(7));
        assert!(!TdNowRegisterPairing::can_form_pair(8));
    }

    #[test]
    fn test_register_pairing_is_valid_pair_edge() {
        assert!(TdNowRegisterPairing::is_valid_pair(0, 1));
        assert!(TdNowRegisterPairing::is_valid_pair(6, 7));
        assert!(!TdNowRegisterPairing::is_valid_pair(0, 0));
        assert!(!TdNowRegisterPairing::is_valid_pair(1, 0));
        assert!(!TdNowRegisterPairing::is_valid_pair(7, 8));
        assert!(!TdNowRegisterPairing::is_valid_pair(3, 5));
    }

    // ── X86XOP3DNowEncoding Expanded Tests ────────────────────────────────────

    #[test]
    fn test_xop3dnow_encoding_defaults() {
        let enc = X86XOP3DNowEncoding::default();
        assert_eq!(enc.default_xop_vl, VexVectorLength::L128);
        assert!(enc.xop_catalog.is_empty());
        assert!(enc.tdnow_catalog.is_empty());
    }

    #[test]
    fn test_xop3dnow_lookup_tdnow_all() {
        let enc = X86XOP3DNowEncoding::new();
        assert_eq!(enc.tdnow_catalog.len(), 23);
        for imm8 in 0..=255u8 {
            let result = enc.lookup_tdnow(imm8);
            let is_valid = enc.is_valid_tdnow_opcode(imm8);
            assert_eq!(result.is_some(), is_valid);
        }
    }

    #[test]
    fn test_encode_named_xop_nonexistent() {
        let enc = X86XOP3DNowEncoding::new();
        assert!(enc.encode_named_xop("nonexistent_op", 0, 1, 2).is_none());
        assert!(enc.encode_named_xop("vaddps", 0, 1, 2).is_none());
    }

    #[test]
    fn test_xop_encode_map9_all() {
        let enc = X86XOP3DNowEncoding::new();
        for (name, op, _) in XopInstructionCatalog::map9_instructions() {
            let instr = enc.encode_named_xop(name, 0, 1, 2);
            assert!(instr.is_some(), "Should encode Map9: {}", name);
            assert_eq!(instr.unwrap().opcode[0], op);
        }
    }

    #[test]
    fn test_xop_instruction_length_variants() {
        // No ModR/M: XOP(3) + op(1) = 4
        let len = X86XOP3DNowEncoding::xop_instruction_length(1, false, false, 0, 0);
        assert_eq!(len, 4);

        // With SIB: XOP(3) + op(1) + ModR/M(1) + SIB(1) = 6
        let len = X86XOP3DNowEncoding::xop_instruction_length(1, true, true, 0, 0);
        assert_eq!(len, 6);

        // Full: XOP(3) + op(1) + ModR/M(1) + SIB(1) + disp32(4) + imm32(4) = 14
        let len = X86XOP3DNowEncoding::xop_instruction_length(1, true, true, 4, 4);
        assert_eq!(len, 14);

        // At limit: 15 bytes
        let len = X86XOP3DNowEncoding::xop_instruction_length(2, true, true, 4, 4);
        assert_eq!(len, 15);
    }

    // ── Assembly Printer Expanded Tests ──────────────────────────────────────

    #[test]
    fn test_assembly_printer_tdnow_memory() {
        let mut instr = TdNowEncodedInstruction::new(tdnow_opcodes::PFADD);
        instr.modrm = Some(0x00);
        let s = XopTdNowAssemblyPrinter::print_tdnow_intel(&instr);
        assert!(s.contains("pfadd"));
        assert!(s.contains("[mem]"));
    }

    #[test]
    fn test_assembly_printer_prefetch_all() {
        for reg in 0..8u8 {
            let s = XopTdNowAssemblyPrinter::print_prefetch_intel(reg, 0x00);
            assert!(!s.is_empty());
        }
    }

    // ── Integration Tests ──────────────────────────────────────────────────────

    #[test]
    fn test_integration_xop_encode_decode_cycle() {
        let enc = X86XOP3DNowEncoding::new();
        let instr = enc.encode_xop_rrr(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::P66,
            VexVectorLength::L128,
            0xC2,
            5,
            3,
            7,
        );
        let assembled = instr.assemble();
        assert_eq!(assembled[0], XOP_PREFIX);

        let (decoded, len) = XopDecodedPrefix::decode_from_slice(&assembled).unwrap();
        assert_eq!(len, 3);
        assert_eq!(decoded.mmmmm, XOP_MAP8);
        assert_eq!(decoded.pp, VexMandatoryPrefix::P66.pp_bits());
        assert!(!decoded.l);
    }

    #[test]
    fn test_integration_tdnow_full_cycle() {
        let enc = X86XOP3DNowEncoding::new();
        // Encode pfadd mm3, mm5
        let instr = enc.encode_tdnow_rr(tdnow_opcodes::PFADD, 3, 5);
        let bytes = instr.assemble();

        // 0F 0F ModRM imm8
        assert_eq!(bytes[0], 0x0F);
        assert_eq!(bytes[1], 0x0F);
        // Mod=11, reg=3<<3=0x18, rm=5 => 0xC0 | 0x18 | 0x05 = 0xDD
        assert_eq!(bytes[2], 0xDD);
        assert_eq!(bytes[3], tdnow_opcodes::PFADD);
    }

    #[test]
    fn test_integration_femms_prefetch_together() {
        let enc = X86XOP3DNowEncoding::new();

        let femms = enc.encode_femms();
        assert_eq!(femms.len(), 2);
        assert_eq!(femms, [0x0F, 0x0E]);

        let prefetchw = enc.encode_prefetch(1, 2, None, &[0x10]);
        assert_eq!(prefetchw[0], 0x0F);
        assert_eq!(prefetchw[1], 0x0D);
    }

    #[test]
    fn test_xop_rxb_roundtrip() {
        for r in [false, true] {
            for x in [false, true] {
                for b in [false, true] {
                    let bytes = XopPrefixBuilder::build(r, x, b, XOP_MAP8, false, 0x0F, false, 0);
                    let d = XopDecodedPrefix::decode(bytes[1], bytes[2]);
                    assert_eq!(d.r, r);
                    assert_eq!(d.x, x);
                    assert_eq!(d.b, b);
                }
            }
        }
    }

    #[test]
    fn test_xop_pp_roundtrip() {
        for pp in 0..4u8 {
            let bytes = XopPrefixBuilder::build(true, true, true, XOP_MAP8, false, 0x0F, false, pp);
            let d = XopDecodedPrefix::decode(bytes[1], bytes[2]);
            assert_eq!(d.pp, pp);
        }
    }

    #[test]
    fn test_xop_vvvv_roundtrip() {
        for reg in 0..16u8 {
            let inv = vex_invert_reg(reg);
            let bytes = XopPrefixBuilder::build(true, true, true, XOP_MAP8, false, inv, false, 0);
            let d = XopDecodedPrefix::decode(bytes[1], bytes[2]);
            assert_eq!(d.vvvv, inv);
            assert_eq!(d.true_vvvv(), reg);
        }
    }

    #[test]
    fn test_xop_wl_roundtrip() {
        for w in [false, true] {
            for l in [false, true] {
                let bytes = XopPrefixBuilder::build(true, true, true, XOP_MAP8, w, 0x0F, l, 0);
                let d = XopDecodedPrefix::decode(bytes[1], bytes[2]);
                assert_eq!(d.w, w);
                assert_eq!(d.l, l);
            }
        }
    }

    #[test]
    fn test_xop_length_max() {
        let len = X86XOP3DNowEncoding::xop_instruction_length(2, true, true, 4, 4);
        assert_eq!(len, 15);
    }

    #[test]
    fn test_tdnow_assemble_all_regs() {
        for dest in 0..8u8 {
            for src in 0..8u8 {
                let enc = X86XOP3DNowEncoding::new();
                let instr = enc.encode_tdnow_rr(tdnow_opcodes::PFADD, dest, src);
                let bytes = instr.assemble();
                assert_eq!(bytes[0], 0x0F);
                assert_eq!(bytes[1], 0x0F);
                let expected = 0xC0 | ((dest & 0x07) << 3) | (src & 0x07);
                assert_eq!(bytes[2], expected);
                assert_eq!(bytes[3], tdnow_opcodes::PFADD);
            }
        }
    }

    #[test]
    fn test_tdnow_multi_opcode_assemble() {
        for &op in &[
            tdnow_opcodes::PFADD,
            tdnow_opcodes::PFSUB,
            tdnow_opcodes::PFMUL,
            tdnow_opcodes::PFMAX,
        ] {
            let enc = X86XOP3DNowEncoding::new();
            let instr = enc.encode_tdnow_rr(op, 0, 1);
            let bytes = instr.assemble();
            assert_eq!(bytes[3], op);
        }
    }

    #[test]
    fn test_prefetch_disp32() {
        let bytes = PrefetchEncoder::encode_prefetcht0(0x05, None, &[0x00, 0x10, 0x00, 0x00]);
        assert_eq!(bytes.len(), 7);
        assert_eq!(&bytes[3..], &[0x00, 0x10, 0x00, 0x00]);
    }

    #[test]
    fn test_prefetch_negative_disp() {
        let bytes = PrefetchEncoder::encode_prefetchw(0x43, None, &[(-8i8) as u8]);
        assert_eq!(bytes[2], 0x4B);
        assert_eq!(bytes[3], (-8i8) as u8);
    }

    #[test]
    fn test_xop_empty_slice() {
        assert!(XopDecodedPrefix::decode_from_slice(&[]).is_none());
        assert!(XopDecodedPrefix::decode_from_slice(&[0x8F]).is_none());
    }

    #[test]
    fn test_xop_not_xop() {
        assert!(XopDecodedPrefix::decode_from_slice(&[0xC5, 0xF8, 0x00]).is_none());
        assert!(XopDecodedPrefix::decode_from_slice(&[0x62, 0xF1, 0x74]).is_none());
    }

    #[test]
    fn test_xop_instr_too_long() {
        let mut instr = XopEncodedInstruction::new(XopOpcodeMap::Map8);
        instr.xop_prefix = vec![0x8F, 0x08, 0x70];
        instr.opcode = vec![0xC2];
        instr.modrm = Some(0x00);
        instr.displacement = vec![0; 12];
        assert!(!instr.is_valid());
    }

    #[test]
    fn test_xop_catalog_total() {
        let enc = X86XOP3DNowEncoding::new();
        let expected = XopInstructionCatalog::map8_instructions().len()
            + XopInstructionCatalog::map8_shift_instructions().len()
            + XopInstructionCatalog::map9_instructions().len();
        assert_eq!(enc.xop_catalog.len(), expected);
    }

    #[test]
    fn test_tdnow_prefix_edge() {
        assert!(X86XOP3DNowEncoding::is_tdnow_prefix(&[0x0F, 0x0F]));
        assert!(!X86XOP3DNowEncoding::is_tdnow_prefix(&[0x0F]));
        assert!(!X86XOP3DNowEncoding::is_tdnow_prefix(&[]));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // 3DNow! Full Encoding Reference Table Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_tdnow_all_immediates_unique() {
        let insts = TdNowCatalog::all_instructions();
        let mut imms: Vec<u8> = insts.iter().map(|i| i.imm8).collect();
        imms.sort();
        imms.dedup();
        assert_eq!(imms.len(), insts.len());
    }

    #[test]
    fn test_tdnow_immediates_in_range() {
        for inst in TdNowCatalog::all_instructions() {
            assert!(inst.imm8 > 0, "imm8 must be non-zero for {}", inst.mnemonic);
            assert!(
                inst.imm8 < 0xFF,
                "imm8 must be < 0xFF for {}",
                inst.mnemonic
            );
        }
    }

    #[test]
    fn test_tdnow_all_mnemonics_lowercase() {
        for inst in TdNowCatalog::all_instructions() {
            assert_eq!(inst.mnemonic, inst.mnemonic.to_lowercase());
        }
    }

    #[test]
    fn test_tdnow_all_have_descriptions() {
        for inst in TdNowCatalog::all_instructions() {
            assert!(
                !inst.description.is_empty(),
                "{} has no description",
                inst.mnemonic
            );
        }
    }

    #[test]
    fn test_tdnow_femms_distinct_from_tdnow() {
        // FEMMS is 0F 0E, not 0F 0F
        assert!(FemmsEncoder::is_femms(&[0x0F, 0x0E]));
        assert!(!X86XOP3DNowEncoding::is_tdnow_prefix(&[0x0F, 0x0E]));
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // XOP Bulk Encoding Tests (every instruction)
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_xop_bulk_encode_map8_instructions() {
        let enc = X86XOP3DNowEncoding::new();
        for (name, op, _) in XopInstructionCatalog::map8_instructions() {
            let instr = enc.encode_named_xop(name, 0, 1, 2).unwrap();
            assert_eq!(instr.opcode, vec![op], "Wrong opcode for {}", name);
            assert_eq!(instr.map, XopOpcodeMap::Map8);
            assert!(instr.xop_prefix.len() == 3);
            assert!(instr.is_valid());
        }
    }

    #[test]
    fn test_xop_bulk_encode_map8_shifts() {
        let enc = X86XOP3DNowEncoding::new();
        for (name, op, _) in XopInstructionCatalog::map8_shift_instructions() {
            let instr = enc.encode_named_xop(name, 0, 1, 2).unwrap();
            assert_eq!(instr.opcode, vec![op], "Wrong opcode for {}", name);
            assert_eq!(instr.map, XopOpcodeMap::Map8);
            assert!(instr.is_valid());
        }
    }

    #[test]
    fn test_xop_bulk_encode_map9_instructions() {
        let enc = X86XOP3DNowEncoding::new();
        for (name, op, _) in XopInstructionCatalog::map9_instructions() {
            let instr = enc.encode_named_xop(name, 0, 1, 2).unwrap();
            assert_eq!(instr.opcode, vec![op], "Wrong opcode for {}", name);
            assert_eq!(instr.map, XopOpcodeMap::Map9);
            assert!(instr.is_valid());
        }
    }

    #[test]
    fn test_xop_bulk_encode_with_imm() {
        let enc = X86XOP3DNowEncoding::new();
        for imm in [0u8, 1, 7, 15, 255] {
            let instr = enc.encode_xop_with_imm(
                XopOpcodeMap::Map8,
                VexMandatoryPrefix::None,
                VexVectorLength::L128,
                0x90, // vprotb
                0,
                1,
                2,
                imm,
            );
            assert_eq!(instr.immediate, vec![imm]);
            assert!(instr.is_valid());
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // XOP + 3DNow! Cross-Compatibility Tests
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_xop_not_tdnow() {
        let xop_bytes = XopPrefixBuilder::build_from_regs(
            XopOpcodeMap::Map8,
            VexMandatoryPrefix::None,
            VexVectorLength::L128,
            0,
            1,
            2,
            false,
        );
        assert!(!X86XOP3DNowEncoding::is_tdnow_prefix(&xop_bytes));
    }

    #[test]
    fn test_tdnow_not_xop() {
        let tdnow_bytes = [
            TDNOW_ESCAPE_0F,
            TDNOW_ESCAPE_SECOND,
            0xC0,
            tdnow_opcodes::PFADD,
        ];
        assert!(XopDecodedPrefix::decode_from_slice(&tdnow_bytes).is_none());
    }

    #[test]
    fn test_encoding_catalog_consistency() {
        let enc = X86XOP3DNowEncoding::new();
        // Every XOP catalog entry should be encodable
        for (&(map_val, opcode), &name) in &enc.xop_catalog {
            let instr = enc.encode_named_xop(name, 0, 1, 2);
            assert!(instr.is_some(), "XOP should encode: {}", name);
            let instr = instr.unwrap();
            assert_eq!(instr.opcode[0], opcode);
            assert_eq!(instr.map.mmmmm(), map_val);
        }
    }

    #[test]
    fn test_xop_lookup_consistency() {
        // lookup_xop should match catalog
        let enc = X86XOP3DNowEncoding::new();
        for (&(map, opcode), &name) in &enc.xop_catalog {
            let looked_up = enc.lookup_xop(map, opcode);
            assert_eq!(looked_up, Some(name));
        }
    }

    #[test]
    fn test_xop_opcode_map_from_mmmmm_all() {
        for m in 0..=31u8 {
            let result = XopOpcodeMap::from_mmmmm(m);
            if m == XOP_MAP8 || m == XOP_MAP9 || m == XOP_MAPA {
                assert!(result.is_some(), "mmmmm={} should be valid", m);
            } else {
                assert!(result.is_none(), "mmmmm={} should be invalid", m);
            }
        }
    }
}