rvemu 0.0.11

RISC-V emulator core implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
//! The cpu module contains the privileged mode, registers, and CPU.

use std::cmp;
use std::cmp::PartialEq;
use std::collections::BTreeMap;
use std::fmt;
use std::num::FpCategory;

use crate::{
    bus::{Bus, DRAM_BASE},
    csr::*,
    devices::{
        plic::PLIC_SCLAIM,
        uart::UART_IRQ,
        virtio_blk::{Virtio, VIRTIO_IRQ},
    },
    dram::DRAM_SIZE,
    exception::Exception,
    interrupt::Interrupt,
};

/// The stack pointer.
const SP: u64 = 2;

/// The number of registers.
const REGISTERS_COUNT: usize = 32;

/// The page size (4 KiB) for the virtual memory system.
const PAGE_SIZE: u64 = 4096;

/// 8 bits. 1 byte.
pub const BYTE: u8 = 8;
/// 16 bits. 2 bytes.
pub const HALFWORD: u8 = 16;
/// 32 bits. 4 bytes.
pub const WORD: u8 = 32;
/// 64 bits. 8 bytes.
pub const DOUBLEWORD: u8 = 64;

macro_rules! inst_count {
    ($cpu:ident, $inst_name:expr) => {
        if $cpu.is_count {
            *$cpu.inst_counter.entry($inst_name.to_string()).or_insert(0) += 1;
        }
    };
}

/// Access type that is used in the virtual address translation process. It decides which exception
/// should raises (InstructionPageFault, LoadPageFault or StoreAMOPageFault).
#[derive(Debug, PartialEq, PartialOrd)]
pub enum AccessType {
    /// Raises the exception InstructionPageFault. It is used for an instruction fetch.
    Instruction,
    /// Raises the exception LoadPageFault.
    Load,
    /// Raises the exception StoreAMOPageFault.
    Store,
}

/// The privileged mode.
#[derive(Debug, PartialEq, PartialOrd, Eq, Copy, Clone)]
pub enum Mode {
    User = 0b00,
    Supervisor = 0b01,
    Machine = 0b11,
    Debug,
}

/// The integer registers.
#[derive(Debug)]
pub struct XRegisters {
    xregs: [u64; REGISTERS_COUNT],
}

impl XRegisters {
    /// Create a new `XRegisters` object.
    pub fn new() -> Self {
        let mut xregs = [0; REGISTERS_COUNT];
        // The stack pointer is set in the default maximum mamory size + the start address of dram.
        xregs[SP as usize] = DRAM_BASE + DRAM_SIZE;
        // From riscv-pk:
        // https://github.com/riscv/riscv-pk/blob/master/machine/mentry.S#L233-L235
        //   save a0 and a1; arguments from previous boot loader stage:
        //   // li x10, 0
        //   // li x11, 0
        //
        // void init_first_hart(uintptr_t hartid, uintptr_t dtb)
        //   x10 (a0): hartid
        //   x11 (a1): pointer to dtb
        //
        // So, we need to set registers register to the state as they are when a bootloader finished.
        xregs[10] = 0;
        xregs[11] = 0x1020;
        Self { xregs }
    }

    /// Read the value from a register.
    pub fn read(&self, index: u64) -> u64 {
        self.xregs[index as usize]
    }

    /// Write the value to a register.
    pub fn write(&mut self, index: u64, value: u64) {
        // Register x0 is hardwired with all bits equal to 0.
        if index != 0 {
            self.xregs[index as usize] = value;
        }
    }
}

impl fmt::Display for XRegisters {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let abi = [
            "zero", " ra ", " sp ", " gp ", " tp ", " t0 ", " t1 ", " t2 ", " s0 ", " s1 ", " a0 ",
            " a1 ", " a2 ", " a3 ", " a4 ", " a5 ", " a6 ", " a7 ", " s2 ", " s3 ", " s4 ", " s5 ",
            " s6 ", " s7 ", " s8 ", " s9 ", " s10", " s11", " t3 ", " t4 ", " t5 ", " t6 ",
        ];
        let mut output = String::from("");
        for i in (0..REGISTERS_COUNT).step_by(4) {
            output = format!(
                "{}\n{}",
                output,
                format!(
                    "x{:02}({})={:>#18x} x{:02}({})={:>#18x} x{:02}({})={:>#18x} x{:02}({})={:>#18x}",
                    i,
                    abi[i],
                    self.read(i as u64),
                    i + 1,
                    abi[i + 1],
                    self.read(i as u64 + 1),
                    i + 2,
                    abi[i + 2],
                    self.read(i as u64 + 2),
                    i + 3,
                    abi[i + 3],
                    self.read(i as u64 + 3),
                )
            );
        }
        write!(f, "{}", output)
    }
}

/// The floating-point registers.
#[derive(Debug)]
pub struct FRegisters {
    fregs: [f64; REGISTERS_COUNT],
}

impl FRegisters {
    /// Create a new `FRegisters` object.
    pub fn new() -> Self {
        Self {
            fregs: [0.0; REGISTERS_COUNT],
        }
    }

    /// Read the value from a regsiter.
    pub fn read(&self, index: u64) -> f64 {
        self.fregs[index as usize]
    }

    /// Write the value to a regsiter.
    pub fn write(&mut self, index: u64, value: f64) {
        self.fregs[index as usize] = value;
    }
}

impl fmt::Display for FRegisters {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let abi = [
            // ft0-7: FP temporaries
            " ft0", " ft1", " ft2", " ft3", " ft4", " ft5", " ft6", " ft7",
            // fs0-1: FP saved registers
            " fs0", " fs1", // fa0-1: FP arguments/return values
            " fa0", " fa1", // fa2–7: FP arguments
            " fa2", " fa3", " fa4", " fa5", " fa6", " fa7",
            // fs2–11: FP saved registers
            " fs2", " fs3", " fs4", " fs5", " fs6", " fs7", " fs8", " fs9", "fs10", "fs11",
            // ft8–11: FP temporaries
            " ft8", " ft9", "ft10", "ft11",
        ];
        let mut output = String::from("");
        for i in (0..REGISTERS_COUNT).step_by(4) {
            output = format!(
                "{}\n{}",
                output,
                format!(
                    "f{:02}({})={:>width$.prec$} f{:02}({})={:>width$.prec$} f{:02}({})={:>width$.prec$} f{:02}({})={:>width$.prec$}",
                    i,
                    abi[i],
                    self.read(i as u64),
                    i + 1,
                    abi[i + 1],
                    self.read(i as u64 + 1),
                    i + 2,
                    abi[i + 2],
                    self.read(i  as u64+ 2),
                    i + 3,
                    abi[i + 3],
                    self.read(i as u64 + 3),
                    width=18,
                    prec=8,
                )
            );
        }
        // Remove the first new line.
        output.remove(0);
        write!(f, "{}", output)
    }
}

/// The CPU to contain registers, a program counter, status, and a privileged mode.
pub struct Cpu {
    /// 64-bit integer registers.
    pub xregs: XRegisters,
    /// 64-bit floating-point registers.
    pub fregs: FRegisters,
    /// Program counter.
    pub pc: u64,
    /// Control and status registers (CSR).
    pub state: State,
    /// Privilege level.
    pub mode: Mode,
    /// Previous privilege level.
    pub prev_mode: Mode,
    /// System bus.
    pub bus: Bus,
    /// SV39 paging flag.
    enable_paging: bool,
    /// Physical page number (PPN) × PAGE_SIZE (4096).
    page_table: u64,
    /// A set of bytes that subsumes the bytes in the addressed word used in
    /// load-reserved/store-conditional instructions.
    reservation_set: Vec<u64>,
    /// Idle state. True when WFI is called, and becomes false when an interrupt happens.
    pub idle: bool,
    /// Counter of each instructions for debug.
    pub inst_counter: BTreeMap<String, u64>,
    /// The count flag. Count the number of each instruction executed.
    pub is_count: bool,
}

impl Cpu {
    /// Create a new `Cpu` object.
    pub fn new() -> Cpu {
        Cpu {
            xregs: XRegisters::new(),
            fregs: FRegisters::new(),
            pc: 0,
            state: State::new(),
            mode: Mode::Machine,
            prev_mode: Mode::Machine,
            bus: Bus::new(),
            enable_paging: false,
            page_table: 0,
            reservation_set: Vec::new(),
            idle: false,
            inst_counter: BTreeMap::new(),
            is_count: false,
        }
    }

    /// Reset CPU states.
    pub fn reset(&mut self) {
        self.pc = 0;
        self.mode = Mode::Machine;
        self.prev_mode = Mode::Machine;
        self.state.reset();
        for i in 0..REGISTERS_COUNT {
            self.xregs.write(i as u64, 0);
            self.fregs.write(i as u64, 0.0);
        }
    }

    /// Check interrupt flags for all devices that can interrupt.
    pub fn check_pending_interrupt(&mut self) -> Option<Interrupt> {
        // global interrupt: PLIC (Platform Local Interrupt Controller) dispatches global
        //                   interrupts to multiple harts.
        // local interrupt: CLINT (Core Local Interrupter) dispatches local interrupts to a hart
        //                  which directly connected to CLINT.

        // 3.1.6.1 Privilege and Global Interrupt-Enable Stack in mstatus register
        // "When a hart is executing in privilege mode x, interrupts are globally enabled when
        // xIE=1 and globally disabled when xIE=0."
        match self.mode {
            Mode::Machine => {
                // Check if the MIE bit is enabled.
                if (self.state.read(MSTATUS) >> 3) & 1 == 0 {
                    return None;
                }
            }
            Mode::Supervisor => {
                // Check if the SIE bit is enabled.
                if (self.state.read(SSTATUS) >> 1) & 1 == 0 {
                    return None;
                }
            }
            _ => {}
        }

        // TODO: Take interrupts based on priorities.

        // Check external interrupt for uart and virtio.
        let irq;
        if self.bus.uart.is_interrupting() {
            irq = UART_IRQ;
        } else if self.bus.virtio.is_interrupting() {
            // An interrupt is raised after a disk access is done.
            Virtio::disk_access(self).expect("failed to access the disk");
            irq = VIRTIO_IRQ;
        } else {
            irq = 0;
        }

        if irq != 0 {
            // TODO: assume that hart is 0
            // TODO: write a value to MCLAIM if the mode is machine
            self.bus
                .write(PLIC_SCLAIM, irq, WORD)
                .expect("failed to write an IRQ to the PLIC_SCLAIM");
            self.state.write(MIP, self.state.read(MIP) | SEIP_BIT);
        }

        // 3.1.9 Machine Interrupt Registers (mip and mie)
        // "An interrupt i will be taken if bit i is set in both mip and mie, and if interrupts are
        // globally enabled. By default, M-mode interrupts are globally enabled if the hart’s
        // current privilege mode is less than M, or if the current privilege mode is M and the MIE
        // bit in the mstatus register is set. If bit i in mideleg is set, however, interrupts are
        // considered to be globally enabled if the hart’s current privilege mode equals the
        // delegated privilege mode (S or U) and that mode’s interrupt enable bit (SIE or UIE in
        // mstatus) is set, or if the current privilege mode is less than the delegated privilege
        // mode."
        let pending = self.state.read(MIE) & self.state.read(MIP);

        if (pending & MEIP_BIT) != 0 {
            self.state.write(MIP, self.state.read(MIP) & !MEIP_BIT);
            return Some(Interrupt::MachineExternalInterrupt);
        }
        if (pending & MSIP_BIT) != 0 {
            self.state.write(MIP, self.state.read(MIP) & !MSIP_BIT);
            return Some(Interrupt::MachineSoftwareInterrupt);
        }
        if (pending & MTIP_BIT) != 0 {
            self.state.write(MIP, self.state.read(MIP) & !MTIP_BIT);
            return Some(Interrupt::MachineTimerInterrupt);
        }
        if (pending & SEIP_BIT) != 0 {
            self.state.write(MIP, self.state.read(MIP) & !SEIP_BIT);
            return Some(Interrupt::SupervisorExternalInterrupt);
        }
        if (pending & SSIP_BIT) != 0 {
            self.state.write(MIP, self.state.read(MIP) & !SSIP_BIT);
            return Some(Interrupt::SupervisorSoftwareInterrupt);
        }
        if (pending & STIP_BIT) != 0 {
            self.state.write(MIP, self.state.read(MIP) & !STIP_BIT);
            return Some(Interrupt::SupervisorTimerInterrupt);
        }

        return None;
    }

    /// Update the physical page number (PPN) and the addressing mode.
    fn update_paging(&mut self) {
        // Read the physical page number (PPN) of the root page table, i.e., its
        // supervisor physical address divided by 4 KiB.
        self.page_table = self.state.read_bits(SATP, ..44) * PAGE_SIZE;

        // Read the MODE field, which selects the current address-translation scheme.
        let mode = self.state.read_bits(SATP, 60..);

        // Enable the SV39 paging if the value of the mode field is 8.
        if mode == 8 {
            self.enable_paging = true;
        } else {
            self.enable_paging = false;
        }
    }

    /// Translate a virtual address to a physical address for the paged virtual-memory system.
    fn translate(&mut self, addr: u64, access_type: AccessType) -> Result<u64, Exception> {
        if !self.enable_paging || self.mode == Mode::Machine {
            return Ok(addr);
        }

        // 4.3.2 Virtual Address Translation Process
        // (The RISC-V Instruction Set Manual Volume II-Privileged Architecture_20190608)
        // A virtual address va is translated into a physical address pa as follows:
        let levels = 3;
        let vpn = [
            (addr >> 12) & 0x1ff,
            (addr >> 21) & 0x1ff,
            (addr >> 30) & 0x1ff,
        ];

        // 1. Let a be satp.ppn × PAGESIZE, and let i = LEVELS − 1. (For Sv32, PAGESIZE=212
        //    and LEVELS=2.)
        let mut a = self.page_table;
        let mut i: i64 = levels - 1;
        let mut pte;
        loop {
            // 2. Let pte be the value of the PTE at address a+va.vpn[i]×PTESIZE. (For Sv32,
            //    PTESIZE=4.) If accessing pte violates a PMA or PMP check, raise an access
            //    exception corresponding to the original access type.
            pte = self.bus.read(a + vpn[i as usize] * 8, DOUBLEWORD)?;

            // 3. If pte.v = 0, or if pte.r = 0 and pte.w = 1, stop and raise a page-fault
            //    exception corresponding to the original access type.
            let v = pte & 1;
            let r = (pte >> 1) & 1;
            let w = (pte >> 2) & 1;
            let x = (pte >> 3) & 1;
            if v == 0 || (r == 0 && w == 1) {
                match access_type {
                    AccessType::Instruction => return Err(Exception::InstructionPageFault),
                    AccessType::Load => return Err(Exception::LoadPageFault),
                    AccessType::Store => return Err(Exception::StoreAMOPageFault),
                }
            }

            // 4. Otherwise, the PTE is valid. If pte.r = 1 or pte.x = 1, go to step 5.
            //    Otherwise, this PTE is a pointer to the next level of the page table.
            //    Let i = i − 1. If i < 0, stop and raise a page-fault exception
            //    corresponding to the original access type. Otherwise,
            //    let a = pte.ppn × PAGESIZE and go to step 2.
            if r == 1 || x == 1 {
                break;
            }
            i -= 1;
            let ppn = (pte >> 10) & 0x0fff_ffff_ffff;
            a = ppn * PAGE_SIZE;
            if i < 0 {
                match access_type {
                    AccessType::Instruction => return Err(Exception::InstructionPageFault),
                    AccessType::Load => return Err(Exception::LoadPageFault),
                    AccessType::Store => return Err(Exception::StoreAMOPageFault),
                }
            }
        }
        // TODO: implement step 5
        // 5. A leaf PTE has been found. Determine if the requested memory access is
        //    allowed by the pte.r, pte.w, pte.x, and pte.u bits, given the current
        //    privilege mode and the value of the SUM and MXR fields of the mstatus
        //    register. If not, stop and raise a page-fault exception corresponding
        //    to the original access type.

        // 3.1.6.3 Memory Privilege in mstatus Register
        // "The MXR (Make eXecutable Readable) bit modifies the privilege with which loads access
        // virtual memory. When MXR=0, only loads from pages marked readable (R=1 in Figure 4.15)
        // will succeed. When MXR=1, loads from pages marked either readable or executable
        // (R=1 or X=1) will succeed. MXR has no effect when page-based virtual memory is not in
        // effect. MXR is hardwired to 0 if S-mode is not supported."

        // "The SUM (permit Supervisor User Memory access) bit modifies the privilege with which
        // S-mode loads and stores access virtual memory. When SUM=0, S-mode memory accesses to
        // pages that are accessible by U-mode (U=1 in Figure 4.15) will fault. When SUM=1, these
        // accesses are permitted.  SUM has no effect when page-based virtual memory is not in
        // effect. Note that, while SUM is ordinarily ignored when not executing in S-mode, it is
        // in effect when MPRV=1 and MPP=S. SUM is hardwired to 0 if S-mode is not supported."

        // 6. If i > 0 and pte.ppn[i−1:0] != 0, this is a misaligned superpage; stop and
        //    raise a page-fault exception corresponding to the original access type.
        let ppn = [
            (pte >> 10) & 0x1ff,
            (pte >> 19) & 0x1ff,
            (pte >> 28) & 0x03ff_ffff,
        ];
        if i > 0 {
            for j in (0..i).rev() {
                if ppn[j as usize] != 0 {
                    // A misaligned superpage.
                    match access_type {
                        AccessType::Instruction => return Err(Exception::InstructionPageFault),
                        AccessType::Load => return Err(Exception::LoadPageFault),
                        AccessType::Store => return Err(Exception::StoreAMOPageFault),
                    }
                }
            }
        }

        // 7. If pte.a = 0, or if the memory access is a store and pte.d = 0, either raise
        //    a page-fault exception corresponding to the original access type, or:
        //    • Set pte.a to 1 and, if the memory access is a store, also set pte.d to 1.
        //    • If this access violates a PMA or PMP check, raise an access exception
        //    corresponding to the original access type.
        //    • This update and the loading of pte in step 2 must be atomic; in particular,
        //    no intervening store to the PTE may be perceived to have occurred in-between.
        let a = (pte >> 6) & 1;
        let d = (pte >> 7) & 1;
        if a == 0 || (access_type == AccessType::Store && d == 0) {
            // Set pte.a to 1 and, if the memory access is a store, also set pte.d to 1.
            pte = pte
                | (1 << 6)
                | if access_type == AccessType::Store {
                    1 << 7
                } else {
                    0
                };

            // TODO: PMA or PMP check.

            // Update the value of address satp.ppn × PAGESIZE + va.vpn[i] × PTESIZE with new pte
            // value.
            // TODO: If this is enabled, running xv6 fails.
            //self.bus
            //.write64(self.page_table + vpn[i as usize] * 8, pte)?;
        }

        // 8. The translation is successful. The translated physical address is given as
        //    follows:
        //    • pa.pgoff = va.pgoff.
        //    • If i > 0, then this is a superpage translation and pa.ppn[i−1:0] =
        //    va.vpn[i−1:0].
        //    • pa.ppn[LEVELS−1:i] = pte.ppn[LEVELS−1:i].
        let offset = addr & 0xfff;
        match i {
            0 => {
                let ppn = (pte >> 10) & 0x0fff_ffff_ffff;
                Ok((ppn << 12) | offset)
            }
            1 => {
                // Superpage translation. A superpage is a memory page of larger size than an
                // ordinary page (4 KiB). It reduces TLB misses and improves performance.
                Ok((ppn[2] << 30) | (ppn[1] << 21) | (vpn[0] << 12) | offset)
            }
            2 => {
                // Superpage translation. A superpage is a memory page of larger size than an
                // ordinary page (4 KiB). It reduces TLB misses and improves performance.
                Ok((ppn[2] << 30) | (vpn[1] << 21) | (vpn[0] << 12) | offset)
            }
            _ => match access_type {
                AccessType::Instruction => return Err(Exception::InstructionPageFault),
                AccessType::Load => return Err(Exception::LoadPageFault),
                AccessType::Store => return Err(Exception::StoreAMOPageFault),
            },
        }
    }

    /// Read `size`-bit data from the system bus with the translation a virtual address to a physical address
    /// if it is enabled.
    fn read(&mut self, v_addr: u64, size: u8) -> Result<u64, Exception> {
        let p_addr = self.translate(v_addr, AccessType::Load)?;
        self.bus.read(p_addr, size)
    }

    /// Write `size`-bit data to the system bus with the translation a virtual address to a physical address
    /// if it is enabled.
    fn write(&mut self, v_addr: u64, value: u64, size: u8) -> Result<(), Exception> {
        // "The SC must fail if a write from some other device to the bytes accessed by the LR can
        // be observed to occur between the LR and SC."
        if self.reservation_set.contains(&v_addr) {
            self.reservation_set.retain(|&x| x != v_addr);
        }

        let p_addr = self.translate(v_addr, AccessType::Load)?;
        self.bus.write(p_addr, value, size)
    }

    /// Fetch the `size`-bit next instruction from the memory at the current program counter.
    pub fn fetch(&mut self, size: u8) -> Result<u64, Exception> {
        let p_pc = self.translate(self.pc, AccessType::Instruction)?;
        // The result of the read method can be `Exception::LoadAccessFault`. In fetch(), an error
        // should be `Exception::InstructionAccessFault`.
        let result = match size {
            HALFWORD => self.bus.read(p_pc, HALFWORD),
            WORD => self.bus.read(p_pc, WORD),
            _ => Err(Exception::InstructionAccessFault),
        };

        match result {
            Ok(value) => Ok(value),
            Err(_) => Err(Exception::InstructionAccessFault),
        }
    }

    /// Execute a cycle on peripheral devices.
    pub fn devices_increment(&mut self) {
        // TODO: mtime in Clint and TIME in CSR should be the same value.
        // Increment the timer register (mtimer) in Clint.
        self.bus.clint.increment(&mut self.state);
        // Increment the value in the TIME and CYCLE registers in CSR.
        self.state.increment_time();
    }

    /// Execute an instruction. Raises an exception if something is wrong, otherwise, returns
    /// the instruction executed in this cycle.
    pub fn execute(&mut self) -> Result<u64, Exception> {
        // WFI is called and pending interrupts don't exist.
        if self.idle {
            return Ok(0);
        }

        // Fetch.
        let inst16 = self.fetch(HALFWORD)?;
        let inst;
        match inst16 & 0b11 {
            0 | 1 | 2 => {
                if inst16 == 0 {
                    // Unimplemented instruction, since all bits are 0.
                    return Err(Exception::IllegalInstruction);
                }
                inst = self.execute_compressed()?
            }
            _ => inst = self.execute_general()?,
        }
        Ok(inst)
    }

    /// Execute a compressed instruction. Raised an exception if something is wrong, otherwise,
    /// returns a fetched instruction. It also increments the program counter by 2 bytes.
    pub fn execute_compressed(&mut self) -> Result<u64, Exception> {
        // 1. Fetch.
        let inst = self.fetch(HALFWORD)?;

        // Add 2 bytes to the program counter.
        self.pc += 2;

        // 2. Decode.
        let opcode = inst & 0x3;
        let funct3 = (inst >> 13) & 0x7;

        // 3. Execute.
        // Compressed instructions have 3-bit field for popular registers, which correspond to
        // registers x8 to x15.
        match opcode {
            0 => {
                // Quadrant 0.
                match funct3 {
                    0x0 => {
                        // c.addi4spn
                        // Expands to addi rd, x2, nzuimm, where rd=rd'+8.
                        inst_count!(self, "c.addi4spn");

                        let rd = ((inst >> 2) & 0x7) + 8;
                        // nzuimm[5:4|9:6|2|3] = inst[12:11|10:7|6|5]
                        let nzuimm = ((inst >> 1) & 0x3c0) // znuimm[9:6]
                            | ((inst >> 7) & 0x30) // znuimm[5:4]
                            | ((inst >> 2) & 0x8) // znuimm[3]
                            | ((inst >> 4) & 0x4); // znuimm[2]
                        if nzuimm == 0 {
                            return Err(Exception::IllegalInstruction);
                        }
                        self.xregs
                            .write(rd, self.xregs.read(2).wrapping_add(nzuimm));
                    }
                    0x1 => {
                        // c.fld
                        // Expands to fld rd, offset(rs1), where rd=rd'+8 and rs1=rs1'+8.
                        inst_count!(self, "c.fld");

                        let rd = ((inst >> 2) & 0x7) + 8;
                        let rs1 = ((inst >> 7) & 0x7) + 8;
                        // offset[5:3|7:6] = isnt[12:10|6:5]
                        let offset = ((inst << 1) & 0xc0) // imm[7:6]
                            | ((inst >> 7) & 0x38); // imm[5:3]
                        let val = f64::from_bits(
                            self.read(self.xregs.read(rs1).wrapping_add(offset), DOUBLEWORD)?,
                        );
                        self.fregs.write(rd, val);
                    }
                    0x2 => {
                        // c.lw
                        // Expands to lw rd, offset(rs1), where rd=rd'+8 and rs1=rs1'+8.
                        inst_count!(self, "c.lw");

                        let rd = ((inst >> 2) & 0x7) + 8;
                        let rs1 = ((inst >> 7) & 0x7) + 8;
                        // offset[5:3|2|6] = isnt[12:10|6|5]
                        let offset = ((inst << 1) & 0x40) // imm[6]
                            | ((inst >> 7) & 0x38) // imm[5:3]
                            | ((inst >> 4) & 0x4); // imm[2]
                        let addr = self.xregs.read(rs1).wrapping_add(offset);
                        let val = self.read(addr, WORD)?;
                        self.xregs.write(rd, val as i32 as i64 as u64);
                    }
                    0x3 => {
                        // c.ld
                        // Expands to ld rd, offset(rs1), where rd=rd'+8 and rs1=rs1'+8.
                        inst_count!(self, "c.ld");

                        let rd = ((inst >> 2) & 0x7) + 8;
                        let rs1 = ((inst >> 7) & 0x7) + 8;
                        // offset[5:3|7:6] = isnt[12:10|6:5]
                        let offset = ((inst << 1) & 0xc0) // imm[7:6]
                            | ((inst >> 7) & 0x38); // imm[5:3]
                        let addr = self.xregs.read(rs1).wrapping_add(offset);
                        let val = self.read(addr, DOUBLEWORD)?;
                        self.xregs.write(rd, val);
                    }
                    0x4 => {
                        // Reserved.
                        panic!("reserved");
                    }
                    0x5 => {
                        // c.fsd
                        // Expands to fsd rs2, offset(rs1), where rs2=rs2'+8 and rs1=rs1'+8.
                        inst_count!(self, "c.fsd");

                        let rs2 = ((inst >> 2) & 0x7) + 8;
                        let rs1 = ((inst >> 7) & 0x7) + 8;
                        // offset[5:3|7:6] = isnt[12:10|6:5]
                        let offset = ((inst << 1) & 0xc0) // imm[7:6]
                            | ((inst >> 7) & 0x38); // imm[5:3]
                        let addr = self.xregs.read(rs1).wrapping_add(offset);
                        self.write(addr, self.fregs.read(rs2).to_bits() as u64, DOUBLEWORD)?;
                    }
                    0x6 => {
                        // c.sw
                        // Expands to sw rs2, offset(rs1), where rs2=rs2'+8 and rs1=rs1'+8.
                        inst_count!(self, "c.sw");

                        let rs2 = ((inst >> 2) & 0x7) + 8;
                        let rs1 = ((inst >> 7) & 0x7) + 8;
                        // offset[5:3|2|6] = isnt[12:10|6|5]
                        let offset = ((inst << 1) & 0x40) // imm[6]
                            | ((inst >> 7) & 0x38) // imm[5:3]
                            | ((inst >> 4) & 0x4); // imm[2]
                        let addr = self.xregs.read(rs1).wrapping_add(offset);
                        self.write(addr, self.xregs.read(rs2), WORD)?;
                    }
                    0x7 => {
                        // c.sd
                        // Expands to sd rs2, offset(rs1), where rs2=rs2'+8 and rs1=rs1'+8.
                        inst_count!(self, "c.sd");

                        let rs2 = ((inst >> 2) & 0x7) + 8;
                        let rs1 = ((inst >> 7) & 0x7) + 8;
                        // offset[5:3|7:6] = isnt[12:10|6:5]
                        let offset = ((inst << 1) & 0xc0) // imm[7:6]
                            | ((inst >> 7) & 0x38); // imm[5:3]
                        let addr = self.xregs.read(rs1).wrapping_add(offset);
                        self.write(addr, self.xregs.read(rs2), DOUBLEWORD)?;
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            1 => {
                // Quadrant 1.
                match funct3 {
                    0x0 => {
                        // c.addi
                        // Expands to addi rd, rd, nzimm.
                        inst_count!(self, "c.addi");

                        let rd = (inst >> 7) & 0x1f;
                        // nzimm[5|4:0] = inst[12|6:2]
                        let mut nzimm = ((inst >> 7) & 0x20) | ((inst >> 2) & 0x1f);
                        // Sign-extended.
                        nzimm = match (nzimm & 0x20) == 0 {
                            true => nzimm,
                            false => (0xc0 | nzimm) as i8 as i64 as u64,
                        };
                        if rd != 0 {
                            self.xregs
                                .write(rd, self.xregs.read(rd).wrapping_add(nzimm));
                        }
                    }
                    0x1 => {
                        // c.addiw
                        // Expands to addiw rd, rd, imm
                        // "The immediate can be zero for C.ADDIW, where this corresponds to sext.w
                        // rd"
                        inst_count!(self, "c.addiw");

                        let rd = (inst >> 7) & 0x1f;
                        // imm[5|4:0] = inst[12|6:2]
                        let mut imm = ((inst >> 7) & 0x20) | ((inst >> 2) & 0x1f);
                        // Sign-extended.
                        imm = match (imm & 0x20) == 0 {
                            true => imm,
                            false => (0xc0 | imm) as i8 as i64 as u64,
                        };
                        if rd != 0 {
                            self.xregs.write(
                                rd,
                                self.xregs.read(rd).wrapping_add(imm) as i32 as i64 as u64,
                            );
                        }
                    }
                    0x2 => {
                        // c.li
                        // Expands to addi rd, x0, imm.
                        inst_count!(self, "c.li");

                        let rd = (inst >> 7) & 0x1f;
                        // imm[5|4:0] = inst[12|6:2]
                        let mut imm = ((inst >> 7) & 0x20) | ((inst >> 2) & 0x1f);
                        // Sign-extended.
                        imm = match (imm & 0x20) == 0 {
                            true => imm,
                            false => (0xc0 | imm) as i8 as i64 as u64,
                        };
                        if rd != 0 {
                            self.xregs.write(rd, imm);
                        }
                    }
                    0x3 => {
                        let rd = (inst >> 7) & 0x1f;
                        match rd {
                            0 => {}
                            2 => {
                                // c.addi16sp
                                // Expands to addi x2, x2, nzimm
                                inst_count!(self, "c.addi16sp");

                                // nzimm[9|4|6|8:7|5] = inst[12|6|5|4:3|2]
                                let mut nzimm = ((inst >> 3) & 0x200) // nzimm[9]
                                    | ((inst >> 2) & 0x10) // nzimm[4]
                                    | ((inst << 1) & 0x40) // nzimm[6]
                                    | ((inst << 4) & 0x180) // nzimm[8:7]
                                    | ((inst << 3) & 0x20); // nzimm[5]
                                nzimm = match (nzimm & 0x200) == 0 {
                                    true => nzimm,
                                    // Sign-extended.
                                    false => (0xfc00 | nzimm) as i16 as i32 as i64 as u64,
                                };
                                if nzimm != 0 {
                                    self.xregs.write(2, self.xregs.read(2).wrapping_add(nzimm));
                                }
                            }
                            _ => {
                                // c.lui
                                // Expands to lui rd, nzimm.
                                inst_count!(self, "c.lui");

                                // nzimm[17|16:12] = inst[12|6:2]
                                let mut nzimm = ((inst << 5) & 0x20000) | ((inst << 10) & 0x1f000);
                                // Sign-extended.
                                nzimm = match (nzimm & 0x20000) == 0 {
                                    true => nzimm,
                                    false => (0xfffc0000 | nzimm) as i32 as i64 as u64,
                                };
                                if nzimm != 0 {
                                    self.xregs.write(rd, nzimm);
                                }
                            }
                        }
                    }
                    0x4 => {
                        let funct2 = (inst >> 10) & 0x3;
                        match funct2 {
                            0x0 => {
                                // c.srli
                                // Expands to srli rd, rd, shamt, where rd=rd'+8.
                                inst_count!(self, "c.srli");

                                let rd = ((inst >> 7) & 0b111) + 8;
                                // shamt[5|4:0] = inst[12|6:2]
                                let shamt = ((inst >> 7) & 0x20) | ((inst >> 2) & 0x1f);
                                self.xregs.write(rd, self.xregs.read(rd) >> shamt);
                            }
                            0x1 => {
                                // c.srai
                                // Expands to srai rd, rd, shamt, where rd=rd'+8.
                                inst_count!(self, "c.srai");

                                let rd = ((inst >> 7) & 0b111) + 8;
                                // shamt[5|4:0] = inst[12|6:2]
                                let shamt = ((inst >> 7) & 0x20) | ((inst >> 2) & 0x1f);
                                self.xregs
                                    .write(rd, ((self.xregs.read(rd) as i64) >> shamt) as u64);
                            }
                            0x2 => {
                                // c.andi
                                // Expands to andi rd, rd, imm, where rd=rd'+8.
                                inst_count!(self, "c.andi");

                                let rd = ((inst >> 7) & 0b111) + 8;
                                // imm[5|4:0] = inst[12|6:2]
                                let mut imm = ((inst >> 7) & 0x20) | ((inst >> 2) & 0x1f);
                                // Sign-extended.
                                imm = match (imm & 0x20) == 0 {
                                    true => imm,
                                    false => (0xc0 | imm) as i8 as i64 as u64,
                                };
                                self.xregs.write(rd, self.xregs.read(rd) & imm);
                            }
                            0x3 => {
                                match ((inst >> 12) & 0b1, (inst >> 5) & 0b11) {
                                    (0x0, 0x0) => {
                                        // c.sub
                                        // Expands to sub rd, rd, rs2, rd=rd'+8 and rs2=rs2'+8.
                                        inst_count!(self, "c.sub");

                                        let rd = ((inst >> 7) & 0b111) + 8;
                                        let rs2 = ((inst >> 2) & 0b111) + 8;
                                        self.xregs.write(
                                            rd,
                                            self.xregs.read(rd).wrapping_sub(self.xregs.read(rs2)),
                                        );
                                    }
                                    (0x0, 0x1) => {
                                        // c.xor
                                        // Expands to xor rd, rd, rs2, rd=rd'+8 and rs2=rs2'+8.
                                        inst_count!(self, "c.xor");

                                        let rd = ((inst >> 7) & 0b111) + 8;
                                        let rs2 = ((inst >> 2) & 0b111) + 8;
                                        self.xregs
                                            .write(rd, self.xregs.read(rd) ^ self.xregs.read(rs2));
                                    }
                                    (0x0, 0x2) => {
                                        // c.or
                                        // Expands to or rd, rd, rs2, rd=rd'+8 and rs2=rs2'+8.
                                        inst_count!(self, "c.or");

                                        let rd = ((inst >> 7) & 0b111) + 8;
                                        let rs2 = ((inst >> 2) & 0b111) + 8;
                                        self.xregs
                                            .write(rd, self.xregs.read(rd) | self.xregs.read(rs2));
                                    }
                                    (0x0, 0x3) => {
                                        // c.and
                                        // Expands to and rd, rd, rs2, rd=rd'+8 and rs2=rs2'+8.
                                        inst_count!(self, "c.and");

                                        let rd = ((inst >> 7) & 0b111) + 8;
                                        let rs2 = ((inst >> 2) & 0b111) + 8;
                                        self.xregs
                                            .write(rd, self.xregs.read(rd) & self.xregs.read(rs2));
                                    }
                                    (0x1, 0x0) => {
                                        // c.subw
                                        // Expands to subw rd, rd, rs2, rd=rd'+8 and rs2=rs2'+8.
                                        inst_count!(self, "c.subw");

                                        let rd = ((inst >> 7) & 0b111) + 8;
                                        let rs2 = ((inst >> 2) & 0b111) + 8;
                                        self.xregs.write(
                                            rd,
                                            self.xregs.read(rd).wrapping_sub(self.xregs.read(rs2))
                                                as i32
                                                as i64
                                                as u64,
                                        );
                                    }
                                    (0x1, 0x1) => {
                                        // c.addw
                                        // Expands to addw rd, rd, rs2, rd=rd'+8 and rs2=rs2'+8.
                                        inst_count!(self, "c.addw");

                                        let rd = ((inst >> 7) & 0b111) + 8;
                                        let rs2 = ((inst >> 2) & 0b111) + 8;
                                        self.xregs.write(
                                            rd,
                                            self.xregs.read(rd).wrapping_add(self.xregs.read(rs2))
                                                as i32
                                                as i64
                                                as u64,
                                        );
                                    }
                                    _ => {
                                        return Err(Exception::IllegalInstruction);
                                    }
                                }
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x5 => {
                        // c.j
                        // Expands to jal x0, offset.
                        inst_count!(self, "c.j");

                        // offset[11|4|9:8|10|6|7|3:1|5] = inst[12|11|10:9|8|7|6|5:3|2]
                        let mut offset = ((inst >> 1) & 0x800) // offset[11]
                            | ((inst << 2) & 0x400) // offset[10]
                            | ((inst >> 1) & 0x300) // offset[9:8]
                            | ((inst << 1) & 0x80) // offset[7]
                            | ((inst >> 1) & 0x40) // offset[6]
                            | ((inst << 3) & 0x20) // offset[5]
                            | ((inst >> 7) & 0x10) // offset[4]
                            | ((inst >> 2) & 0xe); // offset[3:1]
                                                   // Sign-extended.
                        offset = match (offset & 0x800) == 0 {
                            true => offset,
                            false => (0xf000 | offset) as i16 as i64 as u64,
                        };
                        self.pc = self.pc.wrapping_add(offset).wrapping_sub(2);
                    }
                    0x6 => {
                        // c.beqz
                        // Expands to beq rs1, x0, offset, rs1=rs1'+8.
                        inst_count!(self, "c.beqz");

                        let rs1 = ((inst >> 7) & 0b111) + 8;
                        // offset[8|4:3|7:6|2:1|5] = inst[12|11:10|6:5|4:3|2]
                        let mut offset = ((inst >> 4) & 0x100) // offset[8]
                            | ((inst << 1) & 0xc0) // offset[7:6]
                            | ((inst << 3) & 0x20) // offset[5]
                            | ((inst >> 7) & 0x18) // offset[4:3]
                            | ((inst >> 2) & 0x6); // offset[2:1]
                                                   // Sign-extended.
                        offset = match (offset & 0x100) == 0 {
                            true => offset,
                            false => (0xfe00 | offset) as i16 as i64 as u64,
                        };
                        if self.xregs.read(rs1) == 0 {
                            self.pc = self.pc.wrapping_add(offset).wrapping_sub(2);
                        }
                    }
                    0x7 => {
                        // c.bnez
                        // Expands to bne rs1, x0, offset, rs1=rs1'+8.
                        inst_count!(self, "c.bnez");

                        let rs1 = ((inst >> 7) & 0b111) + 8;
                        // offset[8|4:3|7:6|2:1|5] = inst[12|11:10|6:5|4:3|2]
                        let mut offset = ((inst >> 4) & 0x100) // offset[8]
                            | ((inst << 1) & 0xc0) // offset[7:6]
                            | ((inst << 3) & 0x20) // offset[5]
                            | ((inst >> 7) & 0x18) // offset[4:3]
                            | ((inst >> 2) & 0x6); // offset[2:1]
                                                   // Sign-extended.
                        offset = match (offset & 0x100) == 0 {
                            true => offset,
                            false => (0xfe00 | offset) as i16 as i64 as u64,
                        };
                        if self.xregs.read(rs1) != 0 {
                            self.pc = self.pc.wrapping_add(offset).wrapping_sub(2);
                        }
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            2 => {
                // Quadrant 2.
                match funct3 {
                    0x0 => {
                        // c.slli
                        // Expands to slli rd, rd, shamt.
                        inst_count!(self, "c.slli");

                        let rd = (inst >> 7) & 0x1f;
                        // shamt[5|4:0] = inst[12|6:2]
                        let shamt = ((inst >> 7) & 0x20) | ((inst >> 2) & 0x1f);
                        if rd != 0 {
                            self.xregs.write(rd, self.xregs.read(rd) << shamt);
                        }
                    }
                    0x1 => {
                        // c.fldsp
                        // Expands to fld rd, offset(x2).
                        inst_count!(self, "c.fldsp");

                        let rd = (inst >> 7) & 0x1f;
                        // offset[5|4:3|8:6] = inst[12|6:5|4:2]
                        let offset = ((inst << 4) & 0x1c0) // offset[8:6]
                            | ((inst >> 7) & 0x20) // offset[5]
                            | ((inst >> 2) & 0x18); // offset[4:3]
                        let val =
                            f64::from_bits(self.read(self.xregs.read(2) + offset, DOUBLEWORD)?);
                        self.fregs.write(rd, val);
                    }
                    0x2 => {
                        // c.lwsp
                        // Expands to lw rd, offset(x2).
                        inst_count!(self, "c.lwsp");

                        let rd = (inst >> 7) & 0x1f;
                        // offset[5|4:2|7:6] = inst[12|6:4|3:2]
                        let offset = ((inst << 4) & 0xc0) // offset[7:6]
                            | ((inst >> 7) & 0x20) // offset[5]
                            | ((inst >> 2) & 0x1c); // offset[4:2]
                        let val = self.read(self.xregs.read(2).wrapping_add(offset), WORD)?;
                        self.xregs.write(rd, val as i32 as i64 as u64);
                    }
                    0x3 => {
                        // c.ldsp
                        // Expands to ld rd, offset(x2).
                        inst_count!(self, "c.ldsp");

                        let rd = (inst >> 7) & 0x1f;
                        // offset[5|4:3|8:6] = inst[12|6:5|4:2]
                        let offset = ((inst << 4) & 0x1c0) // offset[8:6]
                            | ((inst >> 7) & 0x20) // offset[5]
                            | ((inst >> 2) & 0x18); // offset[4:3]
                        let val = self.read(self.xregs.read(2).wrapping_add(offset), DOUBLEWORD)?;
                        self.xregs.write(rd, val);
                    }
                    0x4 => {
                        match ((inst >> 12) & 0x1, (inst >> 2) & 0x1f) {
                            (0, 0) => {
                                // c.jr
                                // Expands to jalr x0, 0(rs1).
                                inst_count!(self, "c.jr");

                                let rs1 = (inst >> 7) & 0x1f;
                                if rs1 != 0 {
                                    self.pc = self.xregs.read(rs1);
                                }
                            }
                            (0, _) => {
                                // c.mv
                                // Expands to add rd, x0, rs2.
                                inst_count!(self, "c.mv");

                                let rd = (inst >> 7) & 0x1f;
                                let rs2 = (inst >> 2) & 0x1f;
                                if rs2 != 0 {
                                    self.xregs.write(rd, self.xregs.read(rs2));
                                }
                            }
                            (1, 0) => {
                                let rd = (inst >> 7) & 0x1f;
                                if rd == 0 {
                                    // c.ebreak
                                    // Expands to ebreak.
                                    inst_count!(self, "c.ebreak");

                                    return Err(Exception::Breakpoint);
                                } else {
                                    // c.jalr
                                    // Expands to jalr x1, 0(rs1).
                                    inst_count!(self, "c.jalr");

                                    let rs1 = (inst >> 7) & 0x1f;
                                    // Don't add 2 because the pc already moved on.
                                    let t = self.pc;
                                    self.pc = self.xregs.read(rs1);
                                    self.xregs.write(1, t);
                                }
                            }
                            (1, _) => {
                                // c.add
                                // Expands to add rd, rd, rs2.
                                inst_count!(self, "c.add");

                                let rd = (inst >> 7) & 0x1f;
                                let rs2 = (inst >> 2) & 0x1f;
                                if rs2 != 0 {
                                    self.xregs.write(
                                        rd,
                                        self.xregs.read(rd).wrapping_add(self.xregs.read(rs2)),
                                    );
                                }
                            }
                            (_, _) => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x5 => {
                        // c.fsdsp
                        // Expands to fsd rs2, offset(x2).
                        inst_count!(self, "c.fsdsp");

                        let rs2 = (inst >> 2) & 0x1f;
                        // offset[5:3|8:6] = isnt[12:10|9:7]
                        let offset = ((inst >> 1) & 0x1c0) // offset[8:6]
                            | ((inst >> 7) & 0x38); // offset[5:3]
                        let addr = self.xregs.read(2).wrapping_add(offset);
                        self.write(addr, self.fregs.read(rs2).to_bits(), DOUBLEWORD)?;
                    }
                    0x6 => {
                        // c.swsp
                        // Expands to sw rs2, offset(x2).
                        inst_count!(self, "c.swsp");

                        let rs2 = (inst >> 2) & 0x1f;
                        // offset[5:2|7:6] = inst[12:9|8:7]
                        let offset = ((inst >> 1) & 0xc0) // offset[7:6]
                            | ((inst >> 7) & 0x3c); // offset[5:2]
                        let addr = self.xregs.read(2).wrapping_add(offset);
                        self.write(addr, self.xregs.read(rs2), WORD)?;
                    }
                    0x7 => {
                        // c.sdsp
                        // Expands to sd rs2, offset(x2).
                        inst_count!(self, "c.sdsp");

                        let rs2 = (inst >> 2) & 0x1f;
                        // offset[5:3|8:6] = isnt[12:10|9:7]
                        let offset = ((inst >> 1) & 0x1c0) // offset[8:6]
                            | ((inst >> 7) & 0x38); // offset[5:3]
                        let addr = self.xregs.read(2).wrapping_add(offset);
                        self.write(addr, self.xregs.read(rs2), DOUBLEWORD)?;
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            _ => {
                return Err(Exception::IllegalInstruction);
            }
        }
        Ok(inst)
    }

    /// Execute a general-purpose instruction. Raises an exception if something is wrong,
    /// otherwise, returns a fetched instruction. It also increments the program counter by 4 bytes.
    fn execute_general(&mut self) -> Result<u64, Exception> {
        // 1. Fetch.
        let inst = self.fetch(WORD)?;

        // Add 4 bytes to the program counter.
        self.pc += 4;

        // 2. Decode.
        let opcode = inst & 0x0000007f;
        let rd = (inst & 0x00000f80) >> 7;
        let rs1 = (inst & 0x000f8000) >> 15;
        let rs2 = (inst & 0x01f00000) >> 20;
        let funct3 = (inst & 0x00007000) >> 12;
        let funct7 = (inst & 0xfe000000) >> 25;

        // 3. Execute.
        match opcode {
            0x03 => {
                // RV32I and RV64I
                // imm[11:0] = inst[31:20]
                let offset = ((inst as i32 as i64) >> 20) as u64;
                let addr = self.xregs.read(rs1).wrapping_add(offset);
                match funct3 {
                    0x0 => {
                        // lb
                        inst_count!(self, "lb");

                        let val = self.read(addr, BYTE)?;
                        self.xregs.write(rd, val as i8 as i64 as u64);
                    }
                    0x1 => {
                        // lh
                        inst_count!(self, "lh");

                        let val = self.read(addr, HALFWORD)?;
                        self.xregs.write(rd, val as i16 as i64 as u64);
                    }
                    0x2 => {
                        // lw
                        inst_count!(self, "lw");

                        let val = self.read(addr, WORD)?;
                        self.xregs.write(rd, val as i32 as i64 as u64);
                    }
                    0x3 => {
                        // ld
                        inst_count!(self, "ld");

                        let val = self.read(addr, DOUBLEWORD)?;
                        self.xregs.write(rd, val);
                    }
                    0x4 => {
                        // lbu
                        inst_count!(self, "lbu");

                        let val = self.read(addr, BYTE)?;
                        self.xregs.write(rd, val);
                    }
                    0x5 => {
                        // lhu
                        inst_count!(self, "lhu");

                        let val = self.read(addr, HALFWORD)?;
                        self.xregs.write(rd, val);
                    }
                    0x6 => {
                        // lwu
                        inst_count!(self, "lwu");

                        let val = self.read(addr, WORD)?;
                        self.xregs.write(rd, val);
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x07 => {
                // RV32D and RV64D
                // imm[11:0] = inst[31:20]
                let offset = ((inst as i32 as i64) >> 20) as u64;
                let addr = self.xregs.read(rs1).wrapping_add(offset);
                match funct3 {
                    0x2 => {
                        // flw
                        inst_count!(self, "flw");

                        let val = f32::from_bits(self.read(addr, WORD)? as u32);
                        self.fregs.write(rd, val as f64);
                    }
                    0x3 => {
                        // fld
                        inst_count!(self, "fld");

                        let val = f64::from_bits(self.read(addr, DOUBLEWORD)?);
                        self.fregs.write(rd, val);
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x0f => {
                // RV32I and RV64I
                // fence instructions are not supportted yet because this emulator executes an
                // instruction sequentially on a single thread.
                // fence.i is a part of the Zifencei extension.
                match funct3 {
                    0x0 => {
                        // fence
                        inst_count!(self, "fence");
                    }
                    0x1 => {
                        // fence.i
                        inst_count!(self, "fence.i");
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x13 => {
                // RV32I and RV64I
                // imm[11:0] = inst[31:20]
                let imm = ((inst as i32 as i64) >> 20) as u64;
                let funct6 = funct7 >> 1;
                match funct3 {
                    0x0 => {
                        // addi
                        inst_count!(self, "addi");

                        self.xregs.write(rd, self.xregs.read(rs1).wrapping_add(imm));
                    }
                    0x1 => {
                        // slli
                        inst_count!(self, "slli");

                        // shamt size is 5 bits for RV32I and 6 bits for RV64I.
                        let shamt = (inst >> 20) & 0x3f;
                        self.xregs.write(rd, self.xregs.read(rs1) << shamt);
                    }
                    0x2 => {
                        // slti
                        inst_count!(self, "slti");

                        self.xregs.write(
                            rd,
                            if (self.xregs.read(rs1) as i64) < (imm as i64) {
                                1
                            } else {
                                0
                            },
                        );
                    }
                    0x3 => {
                        // sltiu
                        inst_count!(self, "sltiu");

                        self.xregs
                            .write(rd, if self.xregs.read(rs1) < imm { 1 } else { 0 });
                    }
                    0x4 => {
                        // xori
                        inst_count!(self, "xori");

                        self.xregs.write(rd, self.xregs.read(rs1) ^ imm);
                    }
                    0x5 => {
                        match funct6 {
                            0x00 => {
                                // srli
                                inst_count!(self, "srli");

                                // shamt size is 5 bits for RV32I and 6 bits for RV64I.
                                let shamt = (inst >> 20) & 0x3f;
                                self.xregs.write(rd, self.xregs.read(rs1) >> shamt);
                            }
                            0x10 => {
                                // srai
                                inst_count!(self, "srai");

                                // shamt size is 5 bits for RV32I and 6 bits for RV64I.
                                let shamt = (inst >> 20) & 0x3f;
                                self.xregs
                                    .write(rd, ((self.xregs.read(rs1) as i64) >> shamt) as u64);
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x6 => {
                        // ori
                        inst_count!(self, "ori");

                        self.xregs.write(rd, self.xregs.read(rs1) | imm);
                    }
                    0x7 => {
                        // andi
                        inst_count!(self, "andi");

                        self.xregs.write(rd, self.xregs.read(rs1) & imm);
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x17 => {
                // RV32I
                // auipc
                inst_count!(self, "auipc");

                // AUIPC forms a 32-bit offset from the 20-bit U-immediate, filling
                // in the lowest 12 bits with zeros.
                // imm[31:12] = inst[31:12]
                let imm = (inst & 0xfffff000) as i32 as i64 as u64;
                self.xregs
                    .write(rd, self.pc.wrapping_add(imm).wrapping_sub(4));
            }
            0x1b => {
                // RV64I
                // imm[11:0] = inst[31:20]
                let imm = ((inst as i32 as i64) >> 20) as u64;
                match funct3 {
                    0x0 => {
                        // addiw
                        inst_count!(self, "addiw");

                        self.xregs.write(
                            rd,
                            self.xregs.read(rs1).wrapping_add(imm) as i32 as i64 as u64,
                        );
                    }
                    0x1 => {
                        // slliw
                        inst_count!(self, "slliw");

                        // "SLLIW, SRLIW, and SRAIW encodings with imm[5] ̸= 0 are reserved."
                        let shamt = (imm & 0x1f) as u32;
                        self.xregs
                            .write(rd, (self.xregs.read(rs1) << shamt) as i32 as i64 as u64);
                    }
                    0x5 => {
                        match funct7 {
                            0x00 => {
                                // srliw
                                inst_count!(self, "srliw");

                                // "SLLIW, SRLIW, and SRAIW encodings with imm[5] ̸= 0 are reserved."
                                let shamt = (imm & 0x1f) as u32;
                                self.xregs.write(
                                    rd,
                                    ((self.xregs.read(rs1) as u32) >> shamt) as i32 as i64 as u64,
                                )
                            }
                            0x20 => {
                                // sraiw
                                inst_count!(self, "sraiw");

                                // "SLLIW, SRLIW, and SRAIW encodings with imm[5] ̸= 0 are reserved."
                                let shamt = (imm & 0x1f) as u32;
                                self.xregs.write(
                                    rd,
                                    ((self.xregs.read(rs1) as i32) >> shamt) as i64 as u64,
                                );
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x23 => {
                // RV32I
                // offset[11:5|4:0] = inst[31:25|11:7]
                let offset =
                    (((inst & 0xfe000000) as i32 as i64 >> 20) as u64) | ((inst >> 7) & 0x1f);
                let addr = self.xregs.read(rs1).wrapping_add(offset);
                match funct3 {
                    0x0 => {
                        // sb
                        inst_count!(self, "sb");

                        self.write(addr, self.xregs.read(rs2), BYTE)?
                    }
                    0x1 => {
                        // sh
                        inst_count!(self, "sh");

                        self.write(addr, self.xregs.read(rs2), HALFWORD)?
                    }
                    0x2 => {
                        // sw
                        inst_count!(self, "sw");

                        self.write(addr, self.xregs.read(rs2), WORD)?
                    }
                    0x3 => {
                        // sd
                        inst_count!(self, "sd");

                        self.write(addr, self.xregs.read(rs2), DOUBLEWORD)?
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x27 => {
                // RV32F and RV64F
                // offset[11:5|4:0] = inst[31:25|11:7]
                let offset = ((((inst as i32 as i64) >> 20) as u64) & 0xfe0) | ((inst >> 7) & 0x1f);
                let addr = self.xregs.read(rs1).wrapping_add(offset);
                match funct3 {
                    0x2 => {
                        // fsw
                        inst_count!(self, "fsw");

                        self.write(addr, (self.fregs.read(rs2) as f32).to_bits() as u64, WORD)?
                    }
                    0x3 => {
                        // fsd
                        inst_count!(self, "fsd");

                        self.write(addr, self.fregs.read(rs2).to_bits() as u64, DOUBLEWORD)?
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x2f => {
                // RV32A and RV64A
                let funct5 = (funct7 & 0b1111100) >> 2;
                // TODO: Handle `aq` and `rl`.
                let _aq = (funct7 & 0b0000010) >> 1; // acquire access
                let _rl = funct7 & 0b0000001; // release access
                match (funct3, funct5) {
                    (0x2, 0x00) => {
                        // amoadd.w
                        inst_count!(self, "amoadd.w");

                        let addr = self.xregs.read(rs1);
                        // "For AMOs, the A extension requires that the address held in rs1 be
                        // naturally aligned to the size of the operand (i.e., eight-byte aligned
                        // for 64-bit words and four-byte aligned for 32-bit words). If the
                        // address is not naturally aligned, an address-misaligned exception or
                        // an access-fault exception will be generated."
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(addr, t.wrapping_add(self.xregs.read(rs2)), WORD)?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x00) => {
                        // amoadd.d
                        inst_count!(self, "amoadd.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(addr, t.wrapping_add(self.xregs.read(rs2)), DOUBLEWORD)?;
                        self.xregs.write(rd, t);
                    }
                    (0x2, 0x01) => {
                        // amoswap.w
                        inst_count!(self, "amoswap.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(addr, self.xregs.read(rs2), WORD)?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x01) => {
                        // amoswap.d
                        inst_count!(self, "amoswap.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(addr, self.xregs.read(rs2), DOUBLEWORD)?;
                        self.xregs.write(rd, t);
                    }
                    (0x2, 0x02) => {
                        // lr.w
                        inst_count!(self, "lr.w");

                        let addr = self.xregs.read(rs1);
                        // "For LR and SC, the A extension requires that the address held in rs1 be
                        // naturally aligned to the size of the operand (i.e., eight-byte aligned
                        // for 64-bit words and four-byte aligned for 32-bit words)."
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let value = self.read(addr, WORD)?;
                        self.xregs.write(rd, value as i32 as i64 as u64);
                        self.reservation_set.push(addr);
                    }
                    (0x3, 0x02) => {
                        // lr.d
                        inst_count!(self, "lr.d");

                        let addr = self.xregs.read(rs1);
                        // "For LR and SC, the A extension requires that the address held in rs1 be
                        // naturally aligned to the size of the operand (i.e., eight-byte aligned for
                        // 64-bit words and four-byte aligned for 32-bit words)."
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let value = self.read(addr, DOUBLEWORD)?;
                        self.xregs.write(rd, value);
                        self.reservation_set.push(addr);
                    }
                    (0x2, 0x03) => {
                        // sc.w
                        inst_count!(self, "sc.w");

                        let addr = self.xregs.read(rs1);
                        // "For LR and SC, the A extension requires that the address held in rs1 be
                        // naturally aligned to the size of the operand (i.e., eight-byte aligned for
                        // 64-bit words and four-byte aligned for 32-bit words)."
                        if addr % 4 != 0 {
                            return Err(Exception::StoreAMOAddressMisaligned);
                        }
                        if self.reservation_set.contains(&addr) {
                            // "Regardless of success or failure, executing an SC.W instruction
                            // invalidates any reservation held by this hart. "
                            self.reservation_set.retain(|&x| x != addr);
                            self.write(addr, self.xregs.read(rs2), WORD)?;
                            self.xregs.write(rd, 0);
                        } else {
                            self.reservation_set.retain(|&x| x != addr);
                            self.xregs.write(rd, 1);
                        };
                    }
                    (0x3, 0x03) => {
                        // sc.d
                        inst_count!(self, "sc.d");

                        let addr = self.xregs.read(rs1);
                        // "For LR and SC, the A extension requires that the address held in rs1 be
                        // naturally aligned to the size of the operand (i.e., eight-byte aligned for
                        // 64-bit words and four-byte aligned for 32-bit words)."
                        if addr % 8 != 0 {
                            return Err(Exception::StoreAMOAddressMisaligned);
                        }
                        if self.reservation_set.contains(&addr) {
                            self.reservation_set.retain(|&x| x != addr);
                            self.write(addr, self.xregs.read(rs2), DOUBLEWORD)?;
                            self.xregs.write(rd, 0);
                        } else {
                            self.reservation_set.retain(|&x| x != addr);
                            self.xregs.write(rd, 1);
                        }
                    }
                    (0x2, 0x04) => {
                        // amoxor.w
                        inst_count!(self, "amoxor.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(
                            addr,
                            (t as i32 ^ (self.xregs.read(rs2) as i32)) as i64 as u64,
                            WORD,
                        )?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x04) => {
                        // amoxor.d
                        inst_count!(self, "amoxor.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(addr, t ^ self.xregs.read(rs2), DOUBLEWORD)?;
                        self.xregs.write(rd, t);
                    }
                    (0x2, 0x08) => {
                        // amoor.w
                        inst_count!(self, "amoor.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(
                            addr,
                            (t as i32 | (self.xregs.read(rs2) as i32)) as i64 as u64,
                            WORD,
                        )?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x08) => {
                        // amoor.d
                        inst_count!(self, "amoor.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(addr, t | self.xregs.read(rs2), DOUBLEWORD)?;
                        self.xregs.write(rd, t);
                    }
                    (0x2, 0x0c) => {
                        // amoand.w
                        inst_count!(self, "amoand.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(
                            addr,
                            (t as i32 & (self.xregs.read(rs2) as i32)) as u32 as u64,
                            WORD,
                        )?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x0c) => {
                        // amoand.d
                        inst_count!(self, "amoand.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(addr, t & self.xregs.read(rs2), DOUBLEWORD)?;
                        self.xregs.write(rd, t);
                    }
                    (0x2, 0x10) => {
                        // amomin.w
                        inst_count!(self, "amomin.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(
                            addr,
                            cmp::min(t as i32, self.xregs.read(rs2) as i32) as i64 as u64,
                            WORD,
                        )?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x10) => {
                        // amomin.d
                        inst_count!(self, "amomin.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(
                            addr,
                            cmp::min(t as i64, self.xregs.read(rs2) as i64) as u64,
                            DOUBLEWORD,
                        )?;
                        self.xregs.write(rd, t as u64);
                    }
                    (0x2, 0x14) => {
                        // amomax.w
                        inst_count!(self, "amomax.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(
                            addr,
                            cmp::max(t as i32, self.xregs.read(rs2) as i32) as i64 as u64,
                            WORD,
                        )?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x14) => {
                        // amomax.d
                        inst_count!(self, "amomax.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(
                            addr,
                            cmp::max(t as i64, self.xregs.read(rs2) as i64) as u64,
                            DOUBLEWORD,
                        )?;
                        self.xregs.write(rd, t);
                    }
                    (0x2, 0x18) => {
                        // amominu.w
                        inst_count!(self, "amominu.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(
                            addr,
                            cmp::min(t as u32, self.xregs.read(rs2) as u32) as u64,
                            WORD,
                        )?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x18) => {
                        // amominu.d
                        inst_count!(self, "amominu.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(addr, cmp::min(t, self.xregs.read(rs2)), DOUBLEWORD)?;
                        self.xregs.write(rd, t);
                    }
                    (0x2, 0x1c) => {
                        // amomaxu.w
                        inst_count!(self, "amomaxu.w");

                        let addr = self.xregs.read(rs1);
                        if addr % 4 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, WORD)?;
                        self.write(
                            addr,
                            cmp::max(t as u32, self.xregs.read(rs2) as u32) as u64,
                            WORD,
                        )?;
                        self.xregs.write(rd, t as i32 as i64 as u64);
                    }
                    (0x3, 0x1c) => {
                        // amomaxu.d
                        inst_count!(self, "amomaxu.d");

                        let addr = self.xregs.read(rs1);
                        if addr % 8 != 0 {
                            return Err(Exception::LoadAddressMisaligned);
                        }
                        let t = self.read(addr, DOUBLEWORD)?;
                        self.write(addr, cmp::max(t, self.xregs.read(rs2)), DOUBLEWORD)?;
                        self.xregs.write(rd, t);
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x33 => {
                // RV64I and RV64M
                match (funct3, funct7) {
                    (0x0, 0x00) => {
                        // add
                        inst_count!(self, "add");

                        self.xregs
                            .write(rd, self.xregs.read(rs1).wrapping_add(self.xregs.read(rs2)));
                    }
                    (0x0, 0x01) => {
                        // mul
                        inst_count!(self, "mul");

                        self.xregs.write(
                            rd,
                            (self.xregs.read(rs1) as i64).wrapping_mul(self.xregs.read(rs2) as i64)
                                as u64,
                        );
                    }
                    (0x0, 0x20) => {
                        // sub
                        inst_count!(self, "sub");

                        self.xregs
                            .write(rd, self.xregs.read(rs1).wrapping_sub(self.xregs.read(rs2)));
                    }
                    (0x1, 0x00) => {
                        // sll
                        inst_count!(self, "sll");

                        // "SLL, SRL, and SRA perform logical left, logical right, and arithmetic
                        // right shifts on the value in register rs1 by the shift amount held in
                        // register rs2. In RV64I, only the low 6 bits of rs2 are considered for the
                        // shift amount."
                        let shamt = self.xregs.read(rs2) & 0x3f;
                        self.xregs.write(rd, self.xregs.read(rs1) << shamt);
                    }
                    (0x1, 0x01) => {
                        // mulh
                        inst_count!(self, "mulh");

                        // signed × signed
                        self.xregs.write(
                            rd,
                            ((self.xregs.read(rs1) as i64 as i128)
                                .wrapping_mul(self.xregs.read(rs2) as i64 as i128)
                                >> 64) as u64,
                        );
                    }
                    (0x2, 0x00) => {
                        // slt
                        inst_count!(self, "slt");

                        self.xregs.write(
                            rd,
                            if (self.xregs.read(rs1) as i64) < (self.xregs.read(rs2) as i64) {
                                1
                            } else {
                                0
                            },
                        );
                    }
                    (0x2, 0x01) => {
                        // mulhsu
                        inst_count!(self, "mulhsu");

                        // signed × unsigned
                        self.xregs.write(
                            rd,
                            ((self.xregs.read(rs1) as i64 as i128 as u128)
                                .wrapping_mul(self.xregs.read(rs2) as u128)
                                >> 64) as u64,
                        );
                    }
                    (0x3, 0x00) => {
                        // sltu
                        inst_count!(self, "sltu");

                        self.xregs.write(
                            rd,
                            if self.xregs.read(rs1) < self.xregs.read(rs2) {
                                1
                            } else {
                                0
                            },
                        );
                    }
                    (0x3, 0x01) => {
                        // mulhu
                        inst_count!(self, "mulhu");

                        // unsigned × unsigned
                        self.xregs.write(
                            rd,
                            ((self.xregs.read(rs1) as u128)
                                .wrapping_mul(self.xregs.read(rs2) as u128)
                                >> 64) as u64,
                        );
                    }
                    (0x4, 0x00) => {
                        // xor
                        inst_count!(self, "xor");

                        self.xregs
                            .write(rd, self.xregs.read(rs1) ^ self.xregs.read(rs2));
                    }
                    (0x4, 0x01) => {
                        // div
                        inst_count!(self, "div");

                        let dividend = self.xregs.read(rs1) as i64;
                        let divisor = self.xregs.read(rs2) as i64;
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // Set DZ (Divide by Zero) flag to 1.
                                self.state.write_bit(FCSR, 3, 1);
                                // "The quotient of division by zero has all bits set"
                                u64::MAX
                            } else if dividend == i64::MIN && divisor == -1 {
                                // Overflow
                                // "The quotient of a signed division with overflow is equal to the
                                // dividend"
                                dividend as u64
                            } else {
                                // "division of rs1 by rs2, rounding towards zero"
                                dividend.wrapping_div(divisor) as u64
                            },
                        );
                    }
                    (0x5, 0x00) => {
                        // srl
                        inst_count!(self, "srl");

                        // "SLL, SRL, and SRA perform logical left, logical right, and arithmetic
                        // right shifts on the value in register rs1 by the shift amount held in
                        // register rs2. In RV64I, only the low 6 bits of rs2 are considered for the
                        // shift amount."
                        let shamt = self.xregs.read(rs2) & 0x3f;
                        self.xregs.write(rd, self.xregs.read(rs1) >> shamt);
                    }
                    (0x5, 0x01) => {
                        // divu
                        inst_count!(self, "divu");

                        let dividend = self.xregs.read(rs1);
                        let divisor = self.xregs.read(rs2);
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // Set DZ (Divide by Zero) flag to 1.
                                self.state.write_bit(FCSR, 3, 1);
                                // "The quotient of division by zero has all bits set"
                                u64::MAX
                            } else {
                                // "division of rs1 by rs2, rounding towards zero"
                                dividend.wrapping_div(divisor)
                            },
                        );
                    }
                    (0x5, 0x20) => {
                        // sra
                        inst_count!(self, "sra");

                        // "SLL, SRL, and SRA perform logical left, logical right, and arithmetic
                        // right shifts on the value in register rs1 by the shift amount held in
                        // register rs2. In RV64I, only the low 6 bits of rs2 are considered for the
                        // shift amount."
                        let shamt = self.xregs.read(rs2) & 0x3f;
                        self.xregs
                            .write(rd, ((self.xregs.read(rs1) as i64) >> shamt) as u64);
                    }
                    (0x6, 0x00) => {
                        // or
                        inst_count!(self, "or");

                        self.xregs
                            .write(rd, self.xregs.read(rs1) | self.xregs.read(rs2));
                    }
                    (0x6, 0x01) => {
                        // rem
                        inst_count!(self, "rem");

                        let dividend = self.xregs.read(rs1) as i64;
                        let divisor = self.xregs.read(rs2) as i64;
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // "the remainder of division by zero equals the dividend"
                                dividend as u64
                            } else if dividend == i64::MIN && divisor == -1 {
                                // Overflow
                                // "the remainder is zero"
                                0
                            } else {
                                // "provide the remainder of the corresponding division
                                // operation"
                                dividend.wrapping_rem(divisor) as u64
                            },
                        );
                    }
                    (0x7, 0x00) => {
                        // and
                        inst_count!(self, "and");

                        self.xregs
                            .write(rd, self.xregs.read(rs1) & self.xregs.read(rs2));
                    }
                    (0x7, 0x01) => {
                        // remu
                        inst_count!(self, "remu");

                        let dividend = self.xregs.read(rs1);
                        let divisor = self.xregs.read(rs2);
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // "the remainder of division by zero equals the dividend"
                                dividend
                            } else {
                                // "provide the remainder of the corresponding division
                                // operation"
                                dividend.wrapping_rem(divisor)
                            },
                        );
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                };
            }
            0x37 => {
                // RV32I
                // lui
                inst_count!(self, "lui");

                // "LUI places the U-immediate value in the top 20 bits of the destination
                // register rd, filling in the lowest 12 bits with zeros."
                self.xregs
                    .write(rd, (inst & 0xfffff000) as i32 as i64 as u64);
            }
            0x3b => {
                // RV64I and RV64M
                match (funct3, funct7) {
                    (0x0, 0x00) => {
                        // addw
                        inst_count!(self, "addw");

                        self.xregs.write(
                            rd,
                            self.xregs.read(rs1).wrapping_add(self.xregs.read(rs2)) as i32 as i64
                                as u64,
                        );
                    }
                    (0x0, 0x01) => {
                        // mulw
                        inst_count!(self, "mulw");

                        let n1 = self.xregs.read(rs1) as i32;
                        let n2 = self.xregs.read(rs2) as i32;
                        let result = n1.wrapping_mul(n2);
                        self.xregs.write(rd, result as i64 as u64);
                    }
                    (0x0, 0x20) => {
                        // subw
                        inst_count!(self, "subw");

                        self.xregs.write(
                            rd,
                            ((self.xregs.read(rs1).wrapping_sub(self.xregs.read(rs2))) as i32)
                                as u64,
                        );
                    }
                    (0x1, 0x00) => {
                        // sllw
                        inst_count!(self, "sllw");

                        // The shift amount is given by rs2[4:0].
                        let shamt = self.xregs.read(rs2) & 0x1f;
                        self.xregs
                            .write(rd, ((self.xregs.read(rs1)) << shamt) as i32 as i64 as u64);
                    }
                    (0x4, 0x01) => {
                        // divw
                        inst_count!(self, "divw");

                        let dividend = self.xregs.read(rs1) as i32;
                        let divisor = self.xregs.read(rs2) as i32;
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // Set DZ (Divide by Zero) flag to 1.
                                self.state.write_bit(FCSR, 3, 1);
                                // "The quotient of division by zero has all bits set"
                                u64::MAX
                            } else if dividend == i32::MIN && divisor == -1 {
                                // Overflow
                                // "The quotient of a signed division with overflow is equal to the
                                // dividend"
                                dividend as i64 as u64
                            } else {
                                // "division of rs1 by rs2, rounding towards zero"
                                dividend.wrapping_div(divisor) as i64 as u64
                            },
                        );
                    }
                    (0x5, 0x00) => {
                        // srlw
                        inst_count!(self, "srlw");

                        // The shift amount is given by rs2[4:0].
                        let shamt = self.xregs.read(rs2) & 0x1f;
                        self.xregs.write(
                            rd,
                            ((self.xregs.read(rs1) as u32) >> shamt) as i32 as i64 as u64,
                        );
                    }
                    (0x5, 0x01) => {
                        // divuw
                        inst_count!(self, "divuw");

                        let dividend = self.xregs.read(rs1) as u32;
                        let divisor = self.xregs.read(rs2) as u32;
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // Set DZ (Divide by Zero) flag to 1.
                                self.state.write_bit(FCSR, 3, 1);
                                // "The quotient of division by zero has all bits set"
                                u64::MAX
                            } else {
                                // "division of rs1 by rs2, rounding towards zero"
                                dividend.wrapping_div(divisor) as i32 as i64 as u64
                            },
                        );
                    }
                    (0x5, 0x20) => {
                        // sraw
                        inst_count!(self, "sraw");

                        // The shift amount is given by rs2[4:0].
                        let shamt = self.xregs.read(rs2) & 0x1f;
                        self.xregs
                            .write(rd, ((self.xregs.read(rs1) as i32) >> shamt) as i64 as u64);
                    }
                    (0x6, 0x01) => {
                        // remw
                        inst_count!(self, "remw");

                        let dividend = self.xregs.read(rs1) as i32;
                        let divisor = self.xregs.read(rs2) as i32;
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // "the remainder of division by zero equals the dividend"
                                dividend as i64 as u64
                            } else if dividend == i32::MIN && divisor == -1 {
                                // Overflow
                                // "the remainder is zero"
                                0
                            } else {
                                // "provide the remainder of the corresponding division
                                // operation"
                                dividend.wrapping_rem(divisor) as i64 as u64
                            },
                        );
                    }
                    (0x7, 0x01) => {
                        // remuw
                        inst_count!(self, "remuw");

                        let dividend = self.xregs.read(rs1) as u32;
                        let divisor = self.xregs.read(rs2) as u32;
                        self.xregs.write(
                            rd,
                            if divisor == 0 {
                                // Division by zero
                                // "the remainder of division by zero equals the dividend"
                                dividend as i32 as i64 as u64
                            } else {
                                // "provide the remainder of the corresponding division
                                // operation"
                                dividend.wrapping_rem(divisor) as i32 as i64 as u64
                            },
                        );
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x43 => {
                // RV32F and RV64F
                // TODO: support the rounding mode encoding (rm).
                let rs3 = ((inst & 0xf8000000) >> 27) as u64;
                let funct2 = (inst & 0x03000000) >> 25;
                match funct2 {
                    0x0 => {
                        // fmadd.s
                        inst_count!(self, "fmadd.s");

                        self.fregs.write(
                            rd,
                            (self.fregs.read(rs1) as f32)
                                .mul_add(self.fregs.read(rs2) as f32, self.fregs.read(rs3) as f32)
                                as f64,
                        );
                    }
                    0x1 => {
                        // fmadd.d
                        inst_count!(self, "fmadd.d");

                        self.fregs.write(
                            rd,
                            self.fregs
                                .read(rs1)
                                .mul_add(self.fregs.read(rs2), self.fregs.read(rs3)),
                        );
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x47 => {
                // RV32F and RV64F
                // TODO: support the rounding mode encoding (rm).
                let rs3 = ((inst & 0xf8000000) >> 27) as u64;
                let funct2 = (inst & 0x03000000) >> 25;
                match funct2 {
                    0x0 => {
                        // fmsub.s
                        inst_count!(self, "fmsub.s");

                        self.fregs.write(
                            rd,
                            (self.fregs.read(rs1) as f32)
                                .mul_add(self.fregs.read(rs2) as f32, -self.fregs.read(rs3) as f32)
                                as f64,
                        );
                    }
                    0x1 => {
                        // fmsub.d
                        inst_count!(self, "fmsub.d");

                        self.fregs.write(
                            rd,
                            self.fregs
                                .read(rs1)
                                .mul_add(self.fregs.read(rs2), -self.fregs.read(rs3)),
                        );
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x4b => {
                // RV32F and RV64F
                // TODO: support the rounding mode encoding (rm).
                let rs3 = ((inst & 0xf8000000) >> 27) as u64;
                let funct2 = (inst & 0x03000000) >> 25;
                match funct2 {
                    0x0 => {
                        // fnmadd.s
                        inst_count!(self, "fnmadd.s");

                        self.fregs.write(
                            rd,
                            (-self.fregs.read(rs1) as f32)
                                .mul_add(self.fregs.read(rs2) as f32, self.fregs.read(rs3) as f32)
                                as f64,
                        );
                    }
                    0x1 => {
                        // fnmadd.d
                        inst_count!(self, "fnmadd.d");

                        self.fregs.write(
                            rd,
                            (-self.fregs.read(rs1))
                                .mul_add(self.fregs.read(rs2), self.fregs.read(rs3)),
                        );
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x4f => {
                // RV32F and RV64F
                // TODO: support the rounding mode encoding (rm).
                let rs3 = ((inst & 0xf8000000) >> 27) as u64;
                let funct2 = (inst & 0x03000000) >> 25;
                match funct2 {
                    0x0 => {
                        // fnmsub.s
                        inst_count!(self, "fnmsub.s");

                        self.fregs.write(
                            rd,
                            (-self.fregs.read(rs1) as f32)
                                .mul_add(self.fregs.read(rs2) as f32, -self.fregs.read(rs3) as f32)
                                as f64,
                        );
                    }
                    0x1 => {
                        // fnmsub.d
                        inst_count!(self, "fnmsub.d");

                        self.fregs.write(
                            rd,
                            (-self.fregs.read(rs1))
                                .mul_add(self.fregs.read(rs2), -self.fregs.read(rs3)),
                        );
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x53 => {
                // RV32F and RV64F
                // TODO: support the rounding mode encoding (rm).
                // TODO: NaN Boxing of Narrower Values (Spec 12.2).
                // TODO: set exception flags.

                /*
                 * Floating-point instructions align with the IEEE 754 (1985).
                 * The format consist of three fields: a sign bit, a biased exponent, and a fraction.
                 *
                 * | sign(1) | exponent(8) | fraction(23) |
                 * Ok => {}
                 * 31                                     0
                 *
                 */

                // Check the frm field is valid.
                match self.state.read_bits(FCSR, 5..8) {
                    0b000 => {}
                    0b001 => {}
                    0b010 => {}
                    0b011 => {}
                    0b100 => {}
                    0b111 => {}
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }

                match funct7 {
                    0x00 => {
                        // fadd.s
                        inst_count!(self, "fadd.s");

                        self.fregs.write(
                            rd,
                            (self.fregs.read(rs1) as f32 + self.fregs.read(rs2) as f32) as f64,
                        )
                    }
                    0x01 => {
                        // fadd.d
                        inst_count!(self, "fadd.d");

                        self.fregs
                            .write(rd, self.fregs.read(rs1) + self.fregs.read(rs2));
                    }
                    0x04 => {
                        // fsub.s
                        inst_count!(self, "fsub.s");

                        self.fregs.write(
                            rd,
                            (self.fregs.read(rs1) as f32 - self.fregs.read(rs2) as f32) as f64,
                        )
                    }
                    0x05 => {
                        // fsub.d
                        inst_count!(self, "fsub.d");

                        self.fregs
                            .write(rd, self.fregs.read(rs1) - self.fregs.read(rs2));
                    }
                    0x08 => {
                        // fmul.s
                        inst_count!(self, "fmul.s");

                        self.fregs.write(
                            rd,
                            (self.fregs.read(rs1) as f32 * self.fregs.read(rs2) as f32) as f64,
                        )
                    }
                    0x09 => {
                        // fmul.d
                        inst_count!(self, "fmul.d");

                        self.fregs
                            .write(rd, self.fregs.read(rs1) * self.fregs.read(rs2));
                    }
                    0x0c => {
                        // fdiv.s
                        inst_count!(self, "fdiv.s");

                        self.fregs.write(
                            rd,
                            (self.fregs.read(rs1) as f32 / self.fregs.read(rs2) as f32) as f64,
                        )
                    }
                    0x0d => {
                        // fdiv.d
                        inst_count!(self, "fdiv.d");

                        self.fregs
                            .write(rd, self.fregs.read(rs1) / self.fregs.read(rs2));
                    }
                    0x10 => {
                        match funct3 {
                            0x0 => {
                                // fsgnj.s
                                inst_count!(self, "fsgnj.s");

                                self.fregs
                                    .write(rd, self.fregs.read(rs1).copysign(self.fregs.read(rs2)));
                            }
                            0x1 => {
                                // fsgnjn.s
                                inst_count!(self, "fsgnjn.s");

                                self.fregs.write(
                                    rd,
                                    self.fregs.read(rs1).copysign(-self.fregs.read(rs2)),
                                );
                            }
                            0x2 => {
                                // fsgnjx.s
                                inst_count!(self, "fsgnjx.s");

                                let sign1 = (self.fregs.read(rs1) as f32).to_bits() & 0x80000000;
                                let sign2 = (self.fregs.read(rs2) as f32).to_bits() & 0x80000000;
                                let other = (self.fregs.read(rs1) as f32).to_bits() & 0x7fffffff;
                                self.fregs
                                    .write(rd, f32::from_bits((sign1 ^ sign2) | other) as f64);
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x11 => {
                        match funct3 {
                            0x0 => {
                                // fsgnj.d
                                inst_count!(self, "fsgnj.d");

                                self.fregs
                                    .write(rd, self.fregs.read(rs1).copysign(self.fregs.read(rs2)));
                            }
                            0x1 => {
                                // fsgnjn.d
                                inst_count!(self, "fsgnjn.d");

                                self.fregs.write(
                                    rd,
                                    self.fregs.read(rs1).copysign(-self.fregs.read(rs2)),
                                );
                            }
                            0x2 => {
                                // fsgnjx.d
                                inst_count!(self, "fsgnjx.d");

                                let sign1 = self.fregs.read(rs1).to_bits() & 0x80000000_00000000;
                                let sign2 = self.fregs.read(rs2).to_bits() & 0x80000000_00000000;
                                let other = self.fregs.read(rs1).to_bits() & 0x7fffffff_ffffffff;
                                self.fregs
                                    .write(rd, f64::from_bits((sign1 ^ sign2) | other));
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x14 => {
                        match funct3 {
                            0x0 => {
                                // fmin.s
                                inst_count!(self, "fmin.s");

                                self.fregs
                                    .write(rd, self.fregs.read(rs1).min(self.fregs.read(rs2)));
                            }
                            0x1 => {
                                // fmax.s
                                inst_count!(self, "fmax.s");

                                self.fregs
                                    .write(rd, self.fregs.read(rs1).max(self.fregs.read(rs2)));
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x15 => {
                        match funct3 {
                            0x0 => {
                                // fmin.d
                                inst_count!(self, "fmin.d");

                                self.fregs
                                    .write(rd, self.fregs.read(rs1).min(self.fregs.read(rs2)));
                            }
                            0x1 => {
                                // fmax.d
                                inst_count!(self, "fmax.d");

                                self.fregs
                                    .write(rd, self.fregs.read(rs1).max(self.fregs.read(rs2)));
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x20 => {
                        // fcvt.s.d
                        inst_count!(self, "fcvt.s.d");

                        self.fregs.write(rd, self.fregs.read(rs1));
                    }
                    0x21 => {
                        // fcvt.d.s
                        inst_count!(self, "fcvt.d.s");

                        self.fregs.write(rd, (self.fregs.read(rs1) as f32) as f64);
                    }
                    0x2c => {
                        // fsqrt.s
                        inst_count!(self, "fsqrt.s");

                        self.fregs
                            .write(rd, (self.fregs.read(rs1) as f32).sqrt() as f64);
                    }
                    0x2d => {
                        // fsqrt.d
                        inst_count!(self, "fsqrt.d");

                        self.fregs.write(rd, self.fregs.read(rs1).sqrt());
                    }
                    0x50 => {
                        match funct3 {
                            0x0 => {
                                // fle.s
                                inst_count!(self, "fle.s");

                                self.xregs.write(
                                    rd,
                                    if self.fregs.read(rs1) <= self.fregs.read(rs2) {
                                        1
                                    } else {
                                        0
                                    },
                                );
                            }
                            0x1 => {
                                // flt.s
                                inst_count!(self, "flt.s");

                                self.xregs.write(
                                    rd,
                                    if self.fregs.read(rs1) < self.fregs.read(rs2) {
                                        1
                                    } else {
                                        0
                                    },
                                );
                            }
                            0x2 => {
                                // feq.s
                                inst_count!(self, "feq.s");

                                self.xregs.write(
                                    rd,
                                    if self.fregs.read(rs1) == self.fregs.read(rs2) {
                                        1
                                    } else {
                                        0
                                    },
                                );
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x51 => {
                        match funct3 {
                            0x0 => {
                                // fle.d
                                inst_count!(self, "fle.d");

                                self.xregs.write(
                                    rd,
                                    if self.fregs.read(rs1) <= self.fregs.read(rs2) {
                                        1
                                    } else {
                                        0
                                    },
                                );
                            }
                            0x1 => {
                                // flt.d
                                inst_count!(self, "flt.d");

                                self.xregs.write(
                                    rd,
                                    if self.fregs.read(rs1) < self.fregs.read(rs2) {
                                        1
                                    } else {
                                        0
                                    },
                                );
                            }
                            0x2 => {
                                // feq.d
                                inst_count!(self, "feq.d");

                                self.xregs.write(
                                    rd,
                                    if self.fregs.read(rs1) == self.fregs.read(rs2) {
                                        1
                                    } else {
                                        0
                                    },
                                );
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x60 => {
                        match rs2 {
                            0x0 => {
                                // fcvt.w.s
                                inst_count!(self, "fcvt.w.s");

                                self.xregs.write(
                                    rd,
                                    ((self.fregs.read(rs1) as f32).round() as i32) as u64,
                                );
                            }
                            0x1 => {
                                // fcvt.wu.s
                                inst_count!(self, "fcvt.wu.s");

                                self.xregs.write(
                                    rd,
                                    (((self.fregs.read(rs1) as f32).round() as u32) as i32) as u64,
                                );
                            }
                            0x2 => {
                                // fcvt.l.s
                                inst_count!(self, "fcvt.l.s");

                                self.xregs
                                    .write(rd, (self.fregs.read(rs1) as f32).round() as u64);
                            }
                            0x3 => {
                                // fcvt.lu.s
                                inst_count!(self, "fcvt.lu.s");

                                self.xregs
                                    .write(rd, (self.fregs.read(rs1) as f32).round() as u64);
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x61 => {
                        match rs2 {
                            0x0 => {
                                // fcvt.w.d
                                inst_count!(self, "fcvt.w.d");

                                self.xregs
                                    .write(rd, (self.fregs.read(rs1).round() as i32) as u64);
                            }
                            0x1 => {
                                // fcvt.wu.d
                                inst_count!(self, "fcvt.wu.d");

                                self.xregs.write(
                                    rd,
                                    ((self.fregs.read(rs1).round() as u32) as i32) as u64,
                                );
                            }
                            0x2 => {
                                // fcvt.l.d
                                inst_count!(self, "fcvt.l.d");

                                self.xregs.write(rd, self.fregs.read(rs1).round() as u64);
                            }
                            0x3 => {
                                // fcvt.lu.d
                                inst_count!(self, "fcvt.lu.d");

                                self.xregs.write(rd, self.fregs.read(rs1).round() as u64);
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x68 => {
                        match rs2 {
                            0x0 => {
                                // fcvt.s.w
                                inst_count!(self, "fcvt.s.w");

                                self.fregs
                                    .write(rd, ((self.xregs.read(rs1) as i32) as f32) as f64);
                            }
                            0x1 => {
                                // fcvt.s.wu
                                inst_count!(self, "fcvt.s.wu");

                                self.fregs
                                    .write(rd, ((self.xregs.read(rs1) as u32) as f32) as f64);
                            }
                            0x2 => {
                                // fcvt.s.l
                                inst_count!(self, "fcvt.s.l");

                                self.fregs.write(rd, (self.xregs.read(rs1) as f32) as f64);
                            }
                            0x3 => {
                                // fcvt.s.lu
                                inst_count!(self, "fcvt.s.lu");

                                self.fregs
                                    .write(rd, ((self.xregs.read(rs1) as u64) as f32) as f64);
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x69 => {
                        match rs2 {
                            0x0 => {
                                // fcvt.d.w
                                inst_count!(self, "fcvt.d.w");

                                self.fregs.write(rd, (self.xregs.read(rs1) as i32) as f64);
                            }
                            0x1 => {
                                // fcvt.d.wu
                                inst_count!(self, "fcvt.d.wu");

                                self.fregs.write(rd, (self.xregs.read(rs1) as u32) as f64);
                            }
                            0x2 => {
                                // fcvt.d.l
                                inst_count!(self, "fcvt.d.l");

                                self.fregs.write(rd, self.xregs.read(rs1) as f64);
                            }
                            0x3 => {
                                // fcvt.d.lu
                                inst_count!(self, "fcvt.d.lu");

                                self.fregs.write(rd, self.xregs.read(rs1) as f64);
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x70 => {
                        match funct3 {
                            0x0 => {
                                // fmv.x.w
                                inst_count!(self, "fmv.x.w");

                                // "The bits are not modified in the transfer"
                                self.xregs.write(
                                    rd,
                                    (self.fregs.read(rs1).to_bits() as u32) as i32 as i64 as u64,
                                );
                            }
                            0x1 => {
                                // fclass.s
                                inst_count!(self, "fclass.s");

                                let f = self.fregs.read(rs1);
                                match f.classify() {
                                    FpCategory::Infinite => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 0 } else { 7 });
                                    }
                                    FpCategory::Normal => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 1 } else { 6 });
                                    }
                                    FpCategory::Subnormal => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 2 } else { 5 });
                                    }
                                    FpCategory::Zero => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 3 } else { 4 });
                                    }
                                    // don't support a signaling nan, only support a quiet nan.
                                    FpCategory::Nan => self.xregs.write(rd, 9),
                                }
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x71 => {
                        match funct3 {
                            0x0 => {
                                // fmv.x.d
                                inst_count!(self, "fmv.x.d");

                                // "FMV.X.D and FMV.D.X do not modify the bits being transferred"
                                self.xregs.write(rd, self.fregs.read(rs1).to_bits());
                            }
                            0x1 => {
                                // fclass.d
                                inst_count!(self, "fclass.d");

                                let f = self.fregs.read(rs1);
                                match f.classify() {
                                    FpCategory::Infinite => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 0 } else { 7 });
                                    }
                                    FpCategory::Normal => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 1 } else { 6 });
                                    }
                                    FpCategory::Subnormal => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 2 } else { 5 });
                                    }
                                    FpCategory::Zero => {
                                        self.xregs
                                            .write(rd, if f.is_sign_negative() { 3 } else { 4 });
                                    }
                                    // don't support a signaling nan, only support a quiet nan.
                                    FpCategory::Nan => self.xregs.write(rd, 9),
                                }
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x78 => {
                        // fmv.w.x
                        inst_count!(self, "fmv.w.x");

                        // "The bits are not modified in the transfer"
                        self.fregs
                            .write(rd, f32::from_bits(self.xregs.read(rs1) as u32) as f64);
                    }
                    0x79 => {
                        // fmv.d.x
                        inst_count!(self, "fmv.d.x");

                        // "FMV.X.D and FMV.D.X do not modify the bits being transferred"
                        self.fregs.write(rd, f64::from_bits(self.xregs.read(rs1)));
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x63 => {
                // RV32I
                // imm[12|10:5|4:1|11] = inst[31|30:25|11:8|7]
                let imm = (((inst & 0x80000000) as i32 as i64 >> 19) as u64)
                    | ((inst & 0x80) << 4) // imm[11]
                    | ((inst >> 20) & 0x7e0) // imm[10:5]
                    | ((inst >> 7) & 0x1e); // imm[4:1]

                match funct3 {
                    0x0 => {
                        // beq
                        inst_count!(self, "beq");

                        if self.xregs.read(rs1) == self.xregs.read(rs2) {
                            self.pc = self.pc.wrapping_add(imm).wrapping_sub(4);
                        }
                    }
                    0x1 => {
                        // bne
                        inst_count!(self, "bne");

                        if self.xregs.read(rs1) != self.xregs.read(rs2) {
                            self.pc = self.pc.wrapping_add(imm).wrapping_sub(4);
                        }
                    }
                    0x4 => {
                        // blt
                        inst_count!(self, "blt");

                        if (self.xregs.read(rs1) as i64) < (self.xregs.read(rs2) as i64) {
                            self.pc = self.pc.wrapping_add(imm).wrapping_sub(4);
                        }
                    }
                    0x5 => {
                        // bge
                        inst_count!(self, "bge");

                        if (self.xregs.read(rs1) as i64) >= (self.xregs.read(rs2) as i64) {
                            self.pc = self.pc.wrapping_add(imm).wrapping_sub(4);
                        }
                    }
                    0x6 => {
                        // bltu
                        inst_count!(self, "bltu");

                        if self.xregs.read(rs1) < self.xregs.read(rs2) {
                            self.pc = self.pc.wrapping_add(imm).wrapping_sub(4);
                        }
                    }
                    0x7 => {
                        // bgeu
                        inst_count!(self, "bgeu");

                        if self.xregs.read(rs1) >= self.xregs.read(rs2) {
                            self.pc = self.pc.wrapping_add(imm).wrapping_sub(4);
                        }
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            0x67 => {
                // jalr
                inst_count!(self, "jalr");

                // Don't add 4 because the pc already moved on.
                let t = self.pc;

                let offset = (inst as i32 as i64) >> 20;
                let target = ((self.xregs.read(rs1) as i64).wrapping_add(offset)) & !1;

                self.pc = target as u64;
                self.xregs.write(rd, t);
            }
            0x6F => {
                // jal
                inst_count!(self, "jal");

                self.xregs.write(rd, self.pc);

                // imm[20|10:1|11|19:12] = inst[31|30:21|20|19:12]
                let offset = (((inst & 0x80000000) as i32 as i64 >> 11) as u64) // imm[20]
                    | (inst & 0xff000) // imm[19:12]
                    | ((inst >> 9) & 0x800) // imm[11]
                    | ((inst >> 20) & 0x7fe); // imm[10:1]

                self.pc = self.pc.wrapping_add(offset).wrapping_sub(4);
            }
            0x73 => {
                // RV32I, RVZicsr, and supervisor ISA
                let csr_addr = ((inst >> 20) & 0xfff) as u16;
                match funct3 {
                    0x0 => {
                        match (rs2, funct7) {
                            (0x0, 0x0) => {
                                // ecall
                                inst_count!(self, "ecall");

                                // Makes a request of the execution environment by raising an
                                // environment call exception.
                                match self.mode {
                                    Mode::User => {
                                        return Err(Exception::EnvironmentCallFromUMode);
                                    }
                                    Mode::Supervisor => {
                                        return Err(Exception::EnvironmentCallFromSMode);
                                    }
                                    Mode::Machine => {
                                        return Err(Exception::EnvironmentCallFromMMode);
                                    }
                                    _ => {
                                        return Err(Exception::IllegalInstruction);
                                    }
                                }
                            }
                            (0x1, 0x0) => {
                                // ebreak
                                inst_count!(self, "ebreak");

                                // Makes a request of the debugger bu raising a Breakpoint
                                // exception.
                                return Err(Exception::Breakpoint);
                            }
                            (0x2, 0x0) => {
                                // uret
                                inst_count!(self, "uret");
                                panic!("uret: not implemented yet. pc {}", self.pc);
                            }
                            (0x2, 0x8) => {
                                // sret
                                inst_count!(self, "sret");

                                // "The RISC-V Reader" book says:
                                // "Returns from a supervisor-mode exception handler. Sets the pc to
                                // CSRs[sepc], the privilege mode to CSRs[sstatus].SPP,
                                // CSRs[sstatus].SIE to CSRs[sstatus].SPIE, CSRs[sstatus].SPIE to
                                // 1, and CSRs[sstatus].SPP to 0.", but the implementation in QEMU
                                // and Spike use `mstatus` instead of `sstatus`.

                                // Set the program counter to the supervisor exception program
                                // counter (SEPC).
                                self.pc = self.state.read(SEPC);

                                // TODO: Check TSR field

                                // Set the current privileged mode depending on a privious
                                // privilege mode for supervisor mode (SPP, 8).
                                self.mode = match self.state.read_bit(SSTATUS, 8) {
                                    0 => Mode::User,
                                    1 => Mode::Supervisor,
                                    _ => Mode::Debug,
                                };
                                // Read a privious interrupt-enable bit for supervisor mode (SPIE,
                                // 5), and set a global interrupt-enable bit for supervisor mode
                                // (SIE, 1) to it.
                                self.state
                                    .write_bit(SSTATUS, 1, self.state.read_bit(SSTATUS, 5));

                                // Set a privious interrupt-enable bit for supervisor mode (SPIE,
                                // 5) to 1.
                                self.state.write_bit(SSTATUS, 5, 1);
                                // Set a privious privilege mode for supervisor mode (SPP, 8) to 0.
                                self.state.write_bit(SSTATUS, 8, 0);
                            }
                            (0x2, 0x18) => {
                                // mret
                                inst_count!(self, "mret");

                                // "The RISC-V Reader" book says:
                                // "Returns from a machine-mode exception handler. Sets the pc to
                                // CSRs[mepc], the privilege mode to CSRs[mstatus].MPP,
                                // CSRs[mstatus].MIE to CSRs[mstatus].MPIE, and CSRs[mstatus].MPIE
                                // to 1; and, if user mode is supported, sets CSRs[mstatus].MPP to
                                // 0".

                                // Set the program counter to the machine exception program
                                // counter (MEPC).
                                self.pc = self.state.read(MEPC);

                                // Set the current privileged mode depending on a privious
                                // privilege mode for machine  mode (MPP, 11..13).
                                self.mode = match self.state.read_bits(MSTATUS, 11..13) {
                                    0b00 => Mode::User,
                                    0b01 => Mode::Supervisor,
                                    0b11 => Mode::Machine,
                                    _ => Mode::Debug,
                                };

                                // Read a privious interrupt-enable bit for machine mode (MPIE, 7),
                                // and set a global interrupt-enable bit for machine mode (MIE, 3)
                                // to it.
                                self.state
                                    .write_bit(MSTATUS, 3, self.state.read_bit(MSTATUS, 7));

                                // Set a privious interrupt-enable bit for machine mode (MPIE, 7)
                                // to 1.
                                self.state.write_bit(MSTATUS, 7, 1);

                                // Set a privious privilege mode for machine mode (MPP, 11..13) to
                                // 0.
                                self.state.write_bits(MSTATUS, 11..13, 0b00);
                            }
                            (0x5, 0x8) => {
                                // wfi
                                inst_count!(self, "wfi");
                                // "provides a hint to the implementation that the current
                                // hart can be stalled until an interrupt might need servicing."
                                self.idle = true;
                            }
                            (_, 0x9) => {
                                // sfence.vma
                                inst_count!(self, "sfence.vma");
                                // "SFENCE.VMA is used to synchronize updates to in-memory
                                // memory-management data structures with current execution"
                            }
                            (_, 0x11) => {
                                // hfence.bvma
                                inst_count!(self, "hfence.bvma");
                            }
                            (_, 0x51) => {
                                // hfence.gvma
                                inst_count!(self, "hfence.gvma");
                            }
                            _ => {
                                return Err(Exception::IllegalInstruction);
                            }
                        }
                    }
                    0x1 => {
                        // csrrw
                        inst_count!(self, "csrrw");

                        let t = self.state.read(csr_addr);
                        self.state.write(csr_addr, self.xregs.read(rs1));
                        self.xregs.write(rd, t);

                        if csr_addr == SATP {
                            self.update_paging();
                        }
                    }
                    0x2 => {
                        // csrrs
                        inst_count!(self, "csrrs");

                        let t = self.state.read(csr_addr);
                        self.state.write(csr_addr, t | self.xregs.read(rs1));
                        self.xregs.write(rd, t);

                        if csr_addr == SATP {
                            self.update_paging();
                        }
                    }
                    0x3 => {
                        // csrrc
                        inst_count!(self, "csrrc");

                        let t = self.state.read(csr_addr);
                        self.state.write(csr_addr, t & (!self.xregs.read(rs1)));
                        self.xregs.write(rd, t);

                        if csr_addr == SATP {
                            self.update_paging();
                        }
                    }
                    0x5 => {
                        // csrrwi
                        inst_count!(self, "csrrwi");

                        let zimm = rs1;
                        self.xregs.write(rd, self.state.read(csr_addr));
                        self.state.write(csr_addr, zimm);

                        if csr_addr == SATP {
                            self.update_paging();
                        }
                    }
                    0x6 => {
                        // csrrsi
                        inst_count!(self, "csrrsi");

                        let zimm = rs1;
                        let t = self.state.read(csr_addr);
                        self.state.write(csr_addr, t | zimm);
                        self.xregs.write(rd, t);

                        if csr_addr == SATP {
                            self.update_paging();
                        }
                    }
                    0x7 => {
                        // csrrci
                        inst_count!(self, "csrrci");

                        let zimm = rs1;
                        let t = self.state.read(csr_addr);
                        self.state.write(csr_addr, t & (!zimm));
                        self.xregs.write(rd, t);

                        if csr_addr == SATP {
                            self.update_paging();
                        }
                    }
                    _ => {
                        return Err(Exception::IllegalInstruction);
                    }
                }
            }
            _ => {
                return Err(Exception::IllegalInstruction);
            }
        }
        Ok(inst)
    }
}