1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
|
//===-- RISCVAsmParser.cpp - Parse RISC-V assembly to MCInst instructions -===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/RISCVAsmBackend.h"
#include "MCTargetDesc/RISCVBaseInfo.h"
#include "MCTargetDesc/RISCVInstPrinter.h"
#include "MCTargetDesc/RISCVMCAsmInfo.h"
#include "MCTargetDesc/RISCVMCTargetDesc.h"
#include "MCTargetDesc/RISCVMatInt.h"
#include "MCTargetDesc/RISCVTargetStreamer.h"
#include "TargetInfo/RISCVTargetInfo.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstBuilder.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCParser/AsmLexer.h"
#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/RISCVAttributes.h"
#include "llvm/TargetParser/RISCVISAInfo.h"
#include <limits>
#include <optional>
using namespace llvm;
#define DEBUG_TYPE "riscv-asm-parser"
STATISTIC(RISCVNumInstrsCompressed,
"Number of RISC-V Compressed instructions emitted");
static cl::opt<bool> AddBuildAttributes("riscv-add-build-attributes",
cl::init(false));
namespace llvm {
extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
} // namespace llvm
namespace {
struct RISCVOperand;
struct ParserOptionsSet {
bool IsPicEnabled;
};
class RISCVAsmParser : public MCTargetAsmParser {
// This tracks the parsing of the 4 optional operands that make up the vtype
// portion of vset(i)vli instructions which are separated by commas.
enum class VTypeState {
SeenNothingYet,
SeenSew,
SeenLmul,
SeenTailPolicy,
SeenMaskPolicy,
};
SmallVector<FeatureBitset, 4> FeatureBitStack;
SmallVector<ParserOptionsSet, 4> ParserOptionsStack;
ParserOptionsSet ParserOptions;
SMLoc getLoc() const { return getParser().getTok().getLoc(); }
bool isRV64() const { return getSTI().hasFeature(RISCV::Feature64Bit); }
bool isRVE() const { return getSTI().hasFeature(RISCV::FeatureStdExtE); }
bool enableExperimentalExtension() const {
return getSTI().hasFeature(RISCV::Experimental);
}
RISCVTargetStreamer &getTargetStreamer() {
assert(getParser().getStreamer().getTargetStreamer() &&
"do not have a target streamer");
MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
return static_cast<RISCVTargetStreamer &>(TS);
}
unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
unsigned Kind) override;
bool generateImmOutOfRangeError(OperandVector &Operands, uint64_t ErrorInfo,
int64_t Lower, int64_t Upper,
const Twine &Msg);
bool generateImmOutOfRangeError(SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
const Twine &Msg);
bool matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
OperandVector &Operands, MCStreamer &Out,
uint64_t &ErrorInfo,
bool MatchingInlineAsm) override;
MCRegister matchRegisterNameHelper(StringRef Name) const;
bool parseRegister(MCRegister &Reg, SMLoc &StartLoc, SMLoc &EndLoc) override;
ParseStatus tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
SMLoc &EndLoc) override;
bool parseInstruction(ParseInstructionInfo &Info, StringRef Name,
SMLoc NameLoc, OperandVector &Operands) override;
ParseStatus parseDirective(AsmToken DirectiveID) override;
bool parseVTypeToken(const AsmToken &Tok, VTypeState &State, unsigned &Sew,
unsigned &Lmul, bool &Fractional, bool &TailAgnostic,
bool &MaskAgnostic);
bool generateVTypeError(SMLoc ErrorLoc);
bool generateXSfmmVTypeError(SMLoc ErrorLoc);
// Helper to actually emit an instruction to the MCStreamer. Also, when
// possible, compression of the instruction is performed.
void emitToStreamer(MCStreamer &S, const MCInst &Inst);
// Helper to emit a combination of LUI, ADDI(W), and SLLI instructions that
// synthesize the desired immediate value into the destination register.
void emitLoadImm(MCRegister DestReg, int64_t Value, MCStreamer &Out);
// Helper to emit a combination of AUIPC and SecondOpcode. Used to implement
// helpers such as emitLoadLocalAddress and emitLoadAddress.
void emitAuipcInstPair(MCRegister DestReg, MCRegister TmpReg,
const MCExpr *Symbol, RISCV::Specifier VKHi,
unsigned SecondOpcode, SMLoc IDLoc, MCStreamer &Out);
// Helper to emit pseudo instruction "lla" used in PC-rel addressing.
void emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
// Helper to emit pseudo instruction "lga" used in GOT-rel addressing.
void emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
// Helper to emit pseudo instruction "la" used in GOT/PC-rel addressing.
void emitLoadAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
// Helper to emit pseudo instruction "la.tls.ie" used in initial-exec TLS
// addressing.
void emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
// Helper to emit pseudo instruction "la.tls.gd" used in global-dynamic TLS
// addressing.
void emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc, MCStreamer &Out);
// Helper to emit pseudo load/store instruction with a symbol.
void emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
MCStreamer &Out, bool HasTmpReg);
// Helper to emit pseudo sign/zero extend instruction.
void emitPseudoExtend(MCInst &Inst, bool SignExtend, int64_t Width,
SMLoc IDLoc, MCStreamer &Out);
// Helper to emit pseudo vmsge{u}.vx instruction.
void emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc, MCStreamer &Out);
// Checks that a PseudoAddTPRel is using x4/tp in its second input operand.
// Enforcing this using a restricted register class for the second input
// operand of PseudoAddTPRel results in a poor diagnostic due to the fact
// 'add' is an overloaded mnemonic.
bool checkPseudoAddTPRel(MCInst &Inst, OperandVector &Operands);
// Checks that a PseudoTLSDESCCall is using x5/t0 in its output operand.
// Enforcing this using a restricted register class for the output
// operand of PseudoTLSDESCCall results in a poor diagnostic due to the fact
// 'jalr' is an overloaded mnemonic.
bool checkPseudoTLSDESCCall(MCInst &Inst, OperandVector &Operands);
// Check instruction constraints.
bool validateInstruction(MCInst &Inst, OperandVector &Operands);
/// Helper for processing MC instructions that have been successfully matched
/// by matchAndEmitInstruction. Modifications to the emitted instructions,
/// like the expansion of pseudo instructions (e.g., "li"), can be performed
/// in this method.
bool processInstruction(MCInst &Inst, SMLoc IDLoc, OperandVector &Operands,
MCStreamer &Out);
// Auto-generated instruction matching functions
#define GET_ASSEMBLER_HEADER
#include "RISCVGenAsmMatcher.inc"
ParseStatus parseCSRSystemRegister(OperandVector &Operands);
ParseStatus parseFPImm(OperandVector &Operands);
ParseStatus parseImmediate(OperandVector &Operands);
ParseStatus parseRegister(OperandVector &Operands, bool AllowParens = false);
ParseStatus parseMemOpBaseReg(OperandVector &Operands);
ParseStatus parseZeroOffsetMemOp(OperandVector &Operands);
ParseStatus parseOperandWithSpecifier(OperandVector &Operands);
ParseStatus parseBareSymbol(OperandVector &Operands);
ParseStatus parseCallSymbol(OperandVector &Operands);
ParseStatus parsePseudoJumpSymbol(OperandVector &Operands);
ParseStatus parseJALOffset(OperandVector &Operands);
ParseStatus parseVTypeI(OperandVector &Operands);
ParseStatus parseMaskReg(OperandVector &Operands);
ParseStatus parseInsnDirectiveOpcode(OperandVector &Operands);
ParseStatus parseInsnCDirectiveOpcode(OperandVector &Operands);
ParseStatus parseGPRAsFPR(OperandVector &Operands);
ParseStatus parseGPRAsFPR64(OperandVector &Operands);
ParseStatus parseGPRPairAsFPR64(OperandVector &Operands);
template <bool IsRV64Inst> ParseStatus parseGPRPair(OperandVector &Operands);
ParseStatus parseGPRPair(OperandVector &Operands, bool IsRV64Inst);
ParseStatus parseFRMArg(OperandVector &Operands);
ParseStatus parseFenceArg(OperandVector &Operands);
ParseStatus parseRegList(OperandVector &Operands, bool MustIncludeS0 = false);
ParseStatus parseRegListS0(OperandVector &Operands) {
return parseRegList(Operands, /*MustIncludeS0=*/true);
}
ParseStatus parseRegReg(OperandVector &Operands);
ParseStatus parseXSfmmVType(OperandVector &Operands);
ParseStatus parseRetval(OperandVector &Operands);
ParseStatus parseZcmpStackAdj(OperandVector &Operands,
bool ExpectNegative = false);
ParseStatus parseZcmpNegStackAdj(OperandVector &Operands) {
return parseZcmpStackAdj(Operands, /*ExpectNegative*/ true);
}
bool parseOperand(OperandVector &Operands, StringRef Mnemonic);
bool parseExprWithSpecifier(const MCExpr *&Res, SMLoc &E);
bool parseDataExpr(const MCExpr *&Res) override;
bool parseDirectiveOption();
bool parseDirectiveAttribute();
bool parseDirectiveInsn(SMLoc L);
bool parseDirectiveVariantCC();
/// Helper to reset target features for a new arch string. It
/// also records the new arch string that is expanded by RISCVISAInfo
/// and reports error for invalid arch string.
bool resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
bool FromOptionDirective);
void setFeatureBits(uint64_t Feature, StringRef FeatureString) {
if (!(getSTI().hasFeature(Feature))) {
MCSubtargetInfo &STI = copySTI();
setAvailableFeatures(
ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
}
}
void clearFeatureBits(uint64_t Feature, StringRef FeatureString) {
if (getSTI().hasFeature(Feature)) {
MCSubtargetInfo &STI = copySTI();
setAvailableFeatures(
ComputeAvailableFeatures(STI.ToggleFeature(FeatureString)));
}
}
void pushFeatureBits() {
assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
"These two stacks must be kept synchronized");
FeatureBitStack.push_back(getSTI().getFeatureBits());
ParserOptionsStack.push_back(ParserOptions);
}
bool popFeatureBits() {
assert(FeatureBitStack.size() == ParserOptionsStack.size() &&
"These two stacks must be kept synchronized");
if (FeatureBitStack.empty())
return true;
FeatureBitset FeatureBits = FeatureBitStack.pop_back_val();
copySTI().setFeatureBits(FeatureBits);
setAvailableFeatures(ComputeAvailableFeatures(FeatureBits));
ParserOptions = ParserOptionsStack.pop_back_val();
return false;
}
std::unique_ptr<RISCVOperand> defaultMaskRegOp() const;
std::unique_ptr<RISCVOperand> defaultFRMArgOp() const;
std::unique_ptr<RISCVOperand> defaultFRMArgLegacyOp() const;
public:
enum RISCVMatchResultTy : unsigned {
Match_Dummy = FIRST_TARGET_MATCH_RESULT_TY,
#define GET_OPERAND_DIAGNOSTIC_TYPES
#include "RISCVGenAsmMatcher.inc"
#undef GET_OPERAND_DIAGNOSTIC_TYPES
};
static bool classifySymbolRef(const MCExpr *Expr, RISCV::Specifier &Kind);
static bool isSymbolDiff(const MCExpr *Expr);
RISCVAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
const MCInstrInfo &MII, const MCTargetOptions &Options)
: MCTargetAsmParser(Options, STI, MII) {
MCAsmParserExtension::Initialize(Parser);
Parser.addAliasForDirective(".half", ".2byte");
Parser.addAliasForDirective(".hword", ".2byte");
Parser.addAliasForDirective(".word", ".4byte");
Parser.addAliasForDirective(".dword", ".8byte");
setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
auto ABIName = StringRef(Options.ABIName);
if (ABIName.ends_with("f") && !getSTI().hasFeature(RISCV::FeatureStdExtF)) {
errs() << "Hard-float 'f' ABI can't be used for a target that "
"doesn't support the F instruction set extension (ignoring "
"target-abi)\n";
} else if (ABIName.ends_with("d") &&
!getSTI().hasFeature(RISCV::FeatureStdExtD)) {
errs() << "Hard-float 'd' ABI can't be used for a target that "
"doesn't support the D instruction set extension (ignoring "
"target-abi)\n";
}
// Use computeTargetABI to check if ABIName is valid. If invalid, output
// error message.
RISCVABI::computeTargetABI(STI.getTargetTriple(), STI.getFeatureBits(),
ABIName);
const MCObjectFileInfo *MOFI = Parser.getContext().getObjectFileInfo();
ParserOptions.IsPicEnabled = MOFI->isPositionIndependent();
if (AddBuildAttributes)
getTargetStreamer().emitTargetAttributes(STI, /*EmitStackAlign*/ false);
}
};
/// RISCVOperand - Instances of this class represent a parsed machine
/// instruction
struct RISCVOperand final : public MCParsedAsmOperand {
enum class KindTy {
Token,
Register,
Immediate,
FPImmediate,
SystemRegister,
VType,
FRM,
Fence,
RegList,
StackAdj,
RegReg,
} Kind;
struct RegOp {
MCRegister RegNum;
bool IsGPRAsFPR;
};
struct ImmOp {
const MCExpr *Val;
bool IsRV64;
};
struct FPImmOp {
uint64_t Val;
};
struct SysRegOp {
const char *Data;
unsigned Length;
unsigned Encoding;
// FIXME: Add the Encoding parsed fields as needed for checks,
// e.g.: read/write or user/supervisor/machine privileges.
};
struct VTypeOp {
unsigned Val;
};
struct FRMOp {
RISCVFPRndMode::RoundingMode FRM;
};
struct FenceOp {
unsigned Val;
};
struct RegListOp {
unsigned Encoding;
};
struct StackAdjOp {
unsigned Val;
};
struct RegRegOp {
MCRegister BaseReg;
MCRegister OffsetReg;
};
SMLoc StartLoc, EndLoc;
union {
StringRef Tok;
RegOp Reg;
ImmOp Imm;
FPImmOp FPImm;
SysRegOp SysReg;
VTypeOp VType;
FRMOp FRM;
FenceOp Fence;
RegListOp RegList;
StackAdjOp StackAdj;
RegRegOp RegReg;
};
RISCVOperand(KindTy K) : Kind(K) {}
public:
RISCVOperand(const RISCVOperand &o) : MCParsedAsmOperand() {
Kind = o.Kind;
StartLoc = o.StartLoc;
EndLoc = o.EndLoc;
switch (Kind) {
case KindTy::Register:
Reg = o.Reg;
break;
case KindTy::Immediate:
Imm = o.Imm;
break;
case KindTy::FPImmediate:
FPImm = o.FPImm;
break;
case KindTy::Token:
Tok = o.Tok;
break;
case KindTy::SystemRegister:
SysReg = o.SysReg;
break;
case KindTy::VType:
VType = o.VType;
break;
case KindTy::FRM:
FRM = o.FRM;
break;
case KindTy::Fence:
Fence = o.Fence;
break;
case KindTy::RegList:
RegList = o.RegList;
break;
case KindTy::StackAdj:
StackAdj = o.StackAdj;
break;
case KindTy::RegReg:
RegReg = o.RegReg;
break;
}
}
bool isToken() const override { return Kind == KindTy::Token; }
bool isReg() const override { return Kind == KindTy::Register; }
bool isV0Reg() const {
return Kind == KindTy::Register && Reg.RegNum == RISCV::V0;
}
bool isAnyReg() const {
return Kind == KindTy::Register &&
(RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum) ||
RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg.RegNum) ||
RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg.RegNum));
}
bool isAnyRegC() const {
return Kind == KindTy::Register &&
(RISCVMCRegisterClasses[RISCV::GPRCRegClassID].contains(
Reg.RegNum) ||
RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(
Reg.RegNum));
}
bool isImm() const override { return Kind == KindTy::Immediate; }
bool isMem() const override { return false; }
bool isSystemRegister() const { return Kind == KindTy::SystemRegister; }
bool isRegReg() const { return Kind == KindTy::RegReg; }
bool isRegList() const { return Kind == KindTy::RegList; }
bool isRegListS0() const {
return Kind == KindTy::RegList && RegList.Encoding != RISCVZC::RA;
}
bool isStackAdj() const { return Kind == KindTy::StackAdj; }
bool isGPR() const {
return Kind == KindTy::Register &&
RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg.RegNum);
}
bool isGPRPair() const {
return Kind == KindTy::Register &&
RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(
Reg.RegNum);
}
bool isGPRPairC() const {
return Kind == KindTy::Register &&
RISCVMCRegisterClasses[RISCV::GPRPairCRegClassID].contains(
Reg.RegNum);
}
bool isGPRPairNoX0() const {
return Kind == KindTy::Register &&
RISCVMCRegisterClasses[RISCV::GPRPairNoX0RegClassID].contains(
Reg.RegNum);
}
bool isGPRF16() const {
return Kind == KindTy::Register &&
RISCVMCRegisterClasses[RISCV::GPRF16RegClassID].contains(Reg.RegNum);
}
bool isGPRF32() const {
return Kind == KindTy::Register &&
RISCVMCRegisterClasses[RISCV::GPRF32RegClassID].contains(Reg.RegNum);
}
bool isGPRAsFPR() const { return isGPR() && Reg.IsGPRAsFPR; }
bool isGPRAsFPR16() const { return isGPRF16() && Reg.IsGPRAsFPR; }
bool isGPRAsFPR32() const { return isGPRF32() && Reg.IsGPRAsFPR; }
bool isGPRPairAsFPR64() const { return isGPRPair() && Reg.IsGPRAsFPR; }
static bool evaluateConstantImm(const MCExpr *Expr, int64_t &Imm) {
if (auto CE = dyn_cast<MCConstantExpr>(Expr)) {
Imm = CE->getValue();
return true;
}
return false;
}
// True if operand is a symbol with no modifiers, or a constant with no
// modifiers and isShiftedInt<N-1, 1>(Op).
template <int N> bool isBareSimmNLsb0() const {
if (!isImm())
return false;
int64_t Imm;
if (evaluateConstantImm(getImm(), Imm))
return isShiftedInt<N - 1, 1>(fixImmediateForRV32(Imm, isRV64Imm()));
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == RISCV::S_None;
}
// True if operand is a symbol with no modifiers, or a constant with no
// modifiers and isInt<N>(Op).
template <int N> bool isBareSimmN() const {
if (!isImm())
return false;
int64_t Imm;
if (evaluateConstantImm(getImm(), Imm))
return isInt<N>(fixImmediateForRV32(Imm, isRV64Imm()));
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == RISCV::S_None;
}
// Predicate methods for AsmOperands defined in RISCVInstrInfo.td
bool isBareSymbol() const {
int64_t Imm;
// Must be of 'immediate' type but not a constant.
if (!isImm() || evaluateConstantImm(getImm(), Imm))
return false;
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == RISCV::S_None;
}
bool isCallSymbol() const {
int64_t Imm;
// Must be of 'immediate' type but not a constant.
if (!isImm() || evaluateConstantImm(getImm(), Imm))
return false;
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == ELF::R_RISCV_CALL_PLT;
}
bool isPseudoJumpSymbol() const {
int64_t Imm;
// Must be of 'immediate' type but not a constant.
if (!isImm() || evaluateConstantImm(getImm(), Imm))
return false;
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == ELF::R_RISCV_CALL_PLT;
}
bool isTPRelAddSymbol() const {
int64_t Imm;
// Must be of 'immediate' type but not a constant.
if (!isImm() || evaluateConstantImm(getImm(), Imm))
return false;
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == ELF::R_RISCV_TPREL_ADD;
}
bool isTLSDESCCallSymbol() const {
int64_t Imm;
// Must be of 'immediate' type but not a constant.
if (!isImm() || evaluateConstantImm(getImm(), Imm))
return false;
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == ELF::R_RISCV_TLSDESC_CALL;
}
bool isCSRSystemRegister() const { return isSystemRegister(); }
// If the last operand of the vsetvli/vsetvli instruction is a constant
// expression, KindTy is Immediate.
bool isVTypeI10() const {
if (Kind == KindTy::VType)
return true;
return isUImm<10>();
}
bool isVTypeI11() const {
if (Kind == KindTy::VType)
return true;
return isUImm<11>();
}
bool isXSfmmVType() const {
return Kind == KindTy::VType && RISCVVType::isValidXSfmmVType(VType.Val);
}
/// Return true if the operand is a valid for the fence instruction e.g.
/// ('iorw').
bool isFenceArg() const { return Kind == KindTy::Fence; }
/// Return true if the operand is a valid floating point rounding mode.
bool isFRMArg() const { return Kind == KindTy::FRM; }
bool isFRMArgLegacy() const { return Kind == KindTy::FRM; }
bool isRTZArg() const { return isFRMArg() && FRM.FRM == RISCVFPRndMode::RTZ; }
/// Return true if the operand is a valid fli.s floating-point immediate.
bool isLoadFPImm() const {
if (isImm())
return isUImm5();
if (Kind != KindTy::FPImmediate)
return false;
int Idx = RISCVLoadFPImm::getLoadFPImm(
APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
// Don't allow decimal version of the minimum value. It is a different value
// for each supported data type.
return Idx >= 0 && Idx != 1;
}
bool isImmXLenLI() const {
int64_t Imm;
if (!isImm())
return false;
// Given only Imm, ensuring that the actually specified constant is either
// a signed or unsigned 64-bit number is unfortunately impossible.
if (evaluateConstantImm(getImm(), Imm))
return isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm));
return RISCVAsmParser::isSymbolDiff(getImm());
}
bool isImmXLenLI_Restricted() const {
int64_t Imm;
if (!isImm())
return false;
bool IsConstantImm = evaluateConstantImm(getImm(), Imm);
// 'la imm' supports constant immediates only.
return IsConstantImm &&
(isRV64Imm() || (isInt<32>(Imm) || isUInt<32>(Imm)));
}
template <unsigned N> bool isUImm() const {
int64_t Imm;
if (!isImm())
return false;
bool IsConstantImm = evaluateConstantImm(getImm(), Imm);
return IsConstantImm && isUInt<N>(Imm);
}
template <unsigned N, unsigned S> bool isUImmShifted() const {
int64_t Imm;
if (!isImm())
return false;
bool IsConstantImm = evaluateConstantImm(getImm(), Imm);
return IsConstantImm && isShiftedUInt<N, S>(Imm);
}
template <class Pred> bool isUImmPred(Pred p) const {
int64_t Imm;
if (!isImm())
return false;
bool IsConstantImm = evaluateConstantImm(getImm(), Imm);
return IsConstantImm && p(Imm);
}
bool isUImmLog2XLen() const {
if (isImm() && isRV64Imm())
return isUImm<6>();
return isUImm<5>();
}
bool isUImmLog2XLenNonZero() const {
if (isImm() && isRV64Imm())
return isUImmPred([](int64_t Imm) { return Imm != 0 && isUInt<6>(Imm); });
return isUImmPred([](int64_t Imm) { return Imm != 0 && isUInt<5>(Imm); });
}
bool isUImmLog2XLenHalf() const {
if (isImm() && isRV64Imm())
return isUImm<5>();
return isUImm<4>();
}
bool isUImm1() const { return isUImm<1>(); }
bool isUImm2() const { return isUImm<2>(); }
bool isUImm3() const { return isUImm<3>(); }
bool isUImm4() const { return isUImm<4>(); }
bool isUImm5() const { return isUImm<5>(); }
bool isUImm6() const { return isUImm<6>(); }
bool isUImm7() const { return isUImm<7>(); }
bool isUImm8() const { return isUImm<8>(); }
bool isUImm9() const { return isUImm<9>(); }
bool isUImm10() const { return isUImm<10>(); }
bool isUImm11() const { return isUImm<11>(); }
bool isUImm16() const { return isUImm<16>(); }
bool isUImm20() const { return isUImm<20>(); }
bool isUImm32() const { return isUImm<32>(); }
bool isUImm48() const { return isUImm<48>(); }
bool isUImm64() const { return isUImm<64>(); }
bool isUImm5NonZero() const {
return isUImmPred([](int64_t Imm) { return Imm != 0 && isUInt<5>(Imm); });
}
bool isUImm5GT3() const {
return isUImmPred([](int64_t Imm) { return isUInt<5>(Imm) && Imm > 3; });
}
bool isUImm5Plus1() const {
return isUImmPred(
[](int64_t Imm) { return Imm > 0 && isUInt<5>(Imm - 1); });
}
bool isUImm5GE6Plus1() const {
return isUImmPred(
[](int64_t Imm) { return Imm >= 6 && isUInt<5>(Imm - 1); });
}
bool isUImm5Slist() const {
return isUImmPred([](int64_t Imm) {
return (Imm == 0) || (Imm == 1) || (Imm == 2) || (Imm == 4) ||
(Imm == 8) || (Imm == 16) || (Imm == 15) || (Imm == 31);
});
}
bool isUImm8GE32() const {
return isUImmPred([](int64_t Imm) { return isUInt<8>(Imm) && Imm >= 32; });
}
bool isRnumArg() const {
return isUImmPred(
[](int64_t Imm) { return Imm >= INT64_C(0) && Imm <= INT64_C(10); });
}
bool isRnumArg_0_7() const {
return isUImmPred(
[](int64_t Imm) { return Imm >= INT64_C(0) && Imm <= INT64_C(7); });
}
bool isRnumArg_1_10() const {
return isUImmPred(
[](int64_t Imm) { return Imm >= INT64_C(1) && Imm <= INT64_C(10); });
}
bool isRnumArg_2_14() const {
return isUImmPred(
[](int64_t Imm) { return Imm >= INT64_C(2) && Imm <= INT64_C(14); });
}
template <unsigned N> bool isSImm() const {
int64_t Imm;
if (!isImm())
return false;
bool IsConstantImm = evaluateConstantImm(getImm(), Imm);
return IsConstantImm && isInt<N>(fixImmediateForRV32(Imm, isRV64Imm()));
}
template <class Pred> bool isSImmPred(Pred p) const {
int64_t Imm;
if (!isImm())
return false;
bool IsConstantImm = evaluateConstantImm(getImm(), Imm);
return IsConstantImm && p(fixImmediateForRV32(Imm, isRV64Imm()));
}
bool isSImm5() const { return isSImm<5>(); }
bool isSImm6() const { return isSImm<6>(); }
bool isSImm10() const { return isSImm<10>(); }
bool isSImm11() const { return isSImm<11>(); }
bool isSImm16() const { return isSImm<16>(); }
bool isSImm26() const { return isSImm<26>(); }
bool isSImm5NonZero() const {
return isSImmPred([](int64_t Imm) { return Imm != 0 && isInt<5>(Imm); });
}
bool isSImm6NonZero() const {
return isSImmPred([](int64_t Imm) { return Imm != 0 && isInt<6>(Imm); });
}
bool isCLUIImm() const {
return isUImmPred([](int64_t Imm) {
return (isUInt<5>(Imm) && Imm != 0) || (Imm >= 0xfffe0 && Imm <= 0xfffff);
});
}
bool isUImm2Lsb0() const { return isUImmShifted<1, 1>(); }
bool isUImm5Lsb0() const { return isUImmShifted<4, 1>(); }
bool isUImm6Lsb0() const { return isUImmShifted<5, 1>(); }
bool isUImm7Lsb00() const { return isUImmShifted<5, 2>(); }
bool isUImm7Lsb000() const { return isUImmShifted<4, 3>(); }
bool isUImm8Lsb00() const { return isUImmShifted<6, 2>(); }
bool isUImm8Lsb000() const { return isUImmShifted<5, 3>(); }
bool isUImm9Lsb000() const { return isUImmShifted<6, 3>(); }
bool isUImm14Lsb00() const { return isUImmShifted<12, 2>(); }
bool isUImm10Lsb00NonZero() const {
return isUImmPred(
[](int64_t Imm) { return isShiftedUInt<8, 2>(Imm) && (Imm != 0); });
}
// If this a RV32 and the immediate is a uimm32, sign extend it to 32 bits.
// This allows writing 'addi a0, a0, 0xffffffff'.
static int64_t fixImmediateForRV32(int64_t Imm, bool IsRV64Imm) {
if (IsRV64Imm || !isUInt<32>(Imm))
return Imm;
return SignExtend64<32>(Imm);
}
bool isSImm12() const {
if (!isImm())
return false;
int64_t Imm;
if (evaluateConstantImm(getImm(), Imm))
return isInt<12>(fixImmediateForRV32(Imm, isRV64Imm()));
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
(VK == RISCV::S_LO || VK == RISCV::S_PCREL_LO ||
VK == RISCV::S_TPREL_LO || VK == ELF::R_RISCV_TLSDESC_LOAD_LO12 ||
VK == ELF::R_RISCV_TLSDESC_ADD_LO12);
}
bool isSImm12Lsb00000() const {
return isSImmPred([](int64_t Imm) { return isShiftedInt<7, 5>(Imm); });
}
bool isSImm10Lsb0000NonZero() const {
return isSImmPred(
[](int64_t Imm) { return Imm != 0 && isShiftedInt<6, 4>(Imm); });
}
bool isSImm16NonZero() const {
return isSImmPred([](int64_t Imm) { return Imm != 0 && isInt<16>(Imm); });
}
bool isUImm16NonZero() const {
return isUImmPred([](int64_t Imm) { return isUInt<16>(Imm) && Imm != 0; });
}
bool isSImm20LI() const {
if (!isImm())
return false;
int64_t Imm;
if (evaluateConstantImm(getImm(), Imm))
return isInt<20>(fixImmediateForRV32(Imm, isRV64Imm()));
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
VK == RISCV::S_QC_ABS20;
}
bool isSImm10Unsigned() const { return isSImm<10>() || isUImm<10>(); }
bool isUImm20LUI() const {
if (!isImm())
return false;
int64_t Imm;
if (evaluateConstantImm(getImm(), Imm))
return isUInt<20>(Imm);
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
(VK == ELF::R_RISCV_HI20 || VK == ELF::R_RISCV_TPREL_HI20);
}
bool isUImm20AUIPC() const {
if (!isImm())
return false;
int64_t Imm;
if (evaluateConstantImm(getImm(), Imm))
return isUInt<20>(Imm);
RISCV::Specifier VK = RISCV::S_None;
return RISCVAsmParser::classifySymbolRef(getImm(), VK) &&
(VK == ELF::R_RISCV_PCREL_HI20 || VK == ELF::R_RISCV_GOT_HI20 ||
VK == ELF::R_RISCV_TLS_GOT_HI20 || VK == ELF::R_RISCV_TLS_GD_HI20 ||
VK == ELF::R_RISCV_TLSDESC_HI20);
}
bool isImmZero() const {
return isUImmPred([](int64_t Imm) { return 0 == Imm; });
}
bool isImmThree() const {
return isUImmPred([](int64_t Imm) { return 3 == Imm; });
}
bool isImmFour() const {
return isUImmPred([](int64_t Imm) { return 4 == Imm; });
}
bool isSImm5Plus1() const {
return isSImmPred(
[](int64_t Imm) { return Imm != INT64_MIN && isInt<5>(Imm - 1); });
}
bool isSImm18() const {
return isSImmPred([](int64_t Imm) { return isInt<18>(Imm); });
}
bool isSImm18Lsb0() const {
return isSImmPred([](int64_t Imm) { return isShiftedInt<17, 1>(Imm); });
}
bool isSImm19Lsb00() const {
return isSImmPred([](int64_t Imm) { return isShiftedInt<17, 2>(Imm); });
}
bool isSImm20Lsb000() const {
return isSImmPred([](int64_t Imm) { return isShiftedInt<17, 3>(Imm); });
}
bool isSImm32Lsb0() const {
return isSImmPred([](int64_t Imm) { return isShiftedInt<31, 1>(Imm); });
}
/// getStartLoc - Gets location of the first token of this operand
SMLoc getStartLoc() const override { return StartLoc; }
/// getEndLoc - Gets location of the last token of this operand
SMLoc getEndLoc() const override { return EndLoc; }
/// True if this operand is for an RV64 instruction
bool isRV64Imm() const {
assert(Kind == KindTy::Immediate && "Invalid type access!");
return Imm.IsRV64;
}
MCRegister getReg() const override {
assert(Kind == KindTy::Register && "Invalid type access!");
return Reg.RegNum;
}
StringRef getSysReg() const {
assert(Kind == KindTy::SystemRegister && "Invalid type access!");
return StringRef(SysReg.Data, SysReg.Length);
}
const MCExpr *getImm() const {
assert(Kind == KindTy::Immediate && "Invalid type access!");
return Imm.Val;
}
uint64_t getFPConst() const {
assert(Kind == KindTy::FPImmediate && "Invalid type access!");
return FPImm.Val;
}
StringRef getToken() const {
assert(Kind == KindTy::Token && "Invalid type access!");
return Tok;
}
unsigned getVType() const {
assert(Kind == KindTy::VType && "Invalid type access!");
return VType.Val;
}
RISCVFPRndMode::RoundingMode getFRM() const {
assert(Kind == KindTy::FRM && "Invalid type access!");
return FRM.FRM;
}
unsigned getFence() const {
assert(Kind == KindTy::Fence && "Invalid type access!");
return Fence.Val;
}
void print(raw_ostream &OS, const MCAsmInfo &MAI) const override {
auto RegName = [](MCRegister Reg) {
if (Reg)
return RISCVInstPrinter::getRegisterName(Reg);
else
return "noreg";
};
switch (Kind) {
case KindTy::Immediate:
OS << "<imm: ";
MAI.printExpr(OS, *Imm.Val);
OS << ' ' << (Imm.IsRV64 ? "rv64" : "rv32") << '>';
break;
case KindTy::FPImmediate:
OS << "<fpimm: " << FPImm.Val << ">";
break;
case KindTy::Register:
OS << "<reg: " << RegName(Reg.RegNum) << " (" << Reg.RegNum
<< (Reg.IsGPRAsFPR ? ") GPRasFPR>" : ")>");
break;
case KindTy::Token:
OS << "'" << getToken() << "'";
break;
case KindTy::SystemRegister:
OS << "<sysreg: " << getSysReg() << " (" << SysReg.Encoding << ")>";
break;
case KindTy::VType:
OS << "<vtype: ";
RISCVVType::printVType(getVType(), OS);
OS << '>';
break;
case KindTy::FRM:
OS << "<frm: ";
roundingModeToString(getFRM());
OS << '>';
break;
case KindTy::Fence:
OS << "<fence: ";
OS << getFence();
OS << '>';
break;
case KindTy::RegList:
OS << "<reglist: ";
RISCVZC::printRegList(RegList.Encoding, OS);
OS << '>';
break;
case KindTy::StackAdj:
OS << "<stackadj: ";
OS << StackAdj.Val;
OS << '>';
break;
case KindTy::RegReg:
OS << "<RegReg: BaseReg " << RegName(RegReg.BaseReg) << " OffsetReg "
<< RegName(RegReg.OffsetReg);
break;
}
}
static std::unique_ptr<RISCVOperand> createToken(StringRef Str, SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::Token);
Op->Tok = Str;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand>
createReg(MCRegister Reg, SMLoc S, SMLoc E, bool IsGPRAsFPR = false) {
auto Op = std::make_unique<RISCVOperand>(KindTy::Register);
Op->Reg.RegNum = Reg;
Op->Reg.IsGPRAsFPR = IsGPRAsFPR;
Op->StartLoc = S;
Op->EndLoc = E;
return Op;
}
static std::unique_ptr<RISCVOperand> createImm(const MCExpr *Val, SMLoc S,
SMLoc E, bool IsRV64) {
auto Op = std::make_unique<RISCVOperand>(KindTy::Immediate);
Op->Imm.Val = Val;
Op->Imm.IsRV64 = IsRV64;
Op->StartLoc = S;
Op->EndLoc = E;
return Op;
}
static std::unique_ptr<RISCVOperand> createFPImm(uint64_t Val, SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::FPImmediate);
Op->FPImm.Val = Val;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand> createSysReg(StringRef Str, SMLoc S,
unsigned Encoding) {
auto Op = std::make_unique<RISCVOperand>(KindTy::SystemRegister);
Op->SysReg.Data = Str.data();
Op->SysReg.Length = Str.size();
Op->SysReg.Encoding = Encoding;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand>
createFRMArg(RISCVFPRndMode::RoundingMode FRM, SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::FRM);
Op->FRM.FRM = FRM;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand> createFenceArg(unsigned Val, SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::Fence);
Op->Fence.Val = Val;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand> createVType(unsigned VTypeI, SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::VType);
Op->VType.Val = VTypeI;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand> createRegList(unsigned RlistEncode,
SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::RegList);
Op->RegList.Encoding = RlistEncode;
Op->StartLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand>
createRegReg(MCRegister BaseReg, MCRegister OffsetReg, SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::RegReg);
Op->RegReg.BaseReg = BaseReg;
Op->RegReg.OffsetReg = OffsetReg;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
static std::unique_ptr<RISCVOperand> createStackAdj(unsigned StackAdj, SMLoc S) {
auto Op = std::make_unique<RISCVOperand>(KindTy::StackAdj);
Op->StackAdj.Val = StackAdj;
Op->StartLoc = S;
return Op;
}
static void addExpr(MCInst &Inst, const MCExpr *Expr, bool IsRV64Imm) {
assert(Expr && "Expr shouldn't be null!");
int64_t Imm = 0;
bool IsConstant = evaluateConstantImm(Expr, Imm);
if (IsConstant)
Inst.addOperand(
MCOperand::createImm(fixImmediateForRV32(Imm, IsRV64Imm)));
else
Inst.addOperand(MCOperand::createExpr(Expr));
}
// Used by the TableGen Code
void addRegOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
Inst.addOperand(MCOperand::createReg(getReg()));
}
void addImmOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
addExpr(Inst, getImm(), isRV64Imm());
}
void addSImm10UnsignedOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
int64_t Imm;
[[maybe_unused]] bool IsConstant = evaluateConstantImm(getImm(), Imm);
assert(IsConstant);
Inst.addOperand(MCOperand::createImm(SignExtend64<10>(Imm)));
}
void addFPImmOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
if (isImm()) {
addExpr(Inst, getImm(), isRV64Imm());
return;
}
int Imm = RISCVLoadFPImm::getLoadFPImm(
APFloat(APFloat::IEEEdouble(), APInt(64, getFPConst())));
Inst.addOperand(MCOperand::createImm(Imm));
}
void addFenceArgOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
Inst.addOperand(MCOperand::createImm(Fence.Val));
}
void addCSRSystemRegisterOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
Inst.addOperand(MCOperand::createImm(SysReg.Encoding));
}
// Support non-canonical syntax:
// "vsetivli rd, uimm, 0xabc" or "vsetvli rd, rs1, 0xabc"
// "vsetivli rd, uimm, (0xc << N)" or "vsetvli rd, rs1, (0xc << N)"
void addVTypeIOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
int64_t Imm = 0;
if (Kind == KindTy::Immediate) {
[[maybe_unused]] bool IsConstantImm = evaluateConstantImm(getImm(), Imm);
assert(IsConstantImm && "Invalid VTypeI Operand!");
} else {
Imm = getVType();
}
Inst.addOperand(MCOperand::createImm(Imm));
}
void addRegListOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
Inst.addOperand(MCOperand::createImm(RegList.Encoding));
}
void addRegRegOperands(MCInst &Inst, unsigned N) const {
assert(N == 2 && "Invalid number of operands!");
Inst.addOperand(MCOperand::createReg(RegReg.BaseReg));
Inst.addOperand(MCOperand::createReg(RegReg.OffsetReg));
}
void addStackAdjOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
Inst.addOperand(MCOperand::createImm(StackAdj.Val));
}
void addFRMArgOperands(MCInst &Inst, unsigned N) const {
assert(N == 1 && "Invalid number of operands!");
Inst.addOperand(MCOperand::createImm(getFRM()));
}
};
} // end anonymous namespace.
#define GET_REGISTER_MATCHER
#define GET_SUBTARGET_FEATURE_NAME
#define GET_MATCHER_IMPLEMENTATION
#define GET_MNEMONIC_SPELL_CHECKER
#include "RISCVGenAsmMatcher.inc"
static MCRegister convertFPR64ToFPR16(MCRegister Reg) {
assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
return Reg - RISCV::F0_D + RISCV::F0_H;
}
static MCRegister convertFPR64ToFPR32(MCRegister Reg) {
assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
return Reg - RISCV::F0_D + RISCV::F0_F;
}
static MCRegister convertFPR64ToFPR128(MCRegister Reg) {
assert(Reg >= RISCV::F0_D && Reg <= RISCV::F31_D && "Invalid register");
return Reg - RISCV::F0_D + RISCV::F0_Q;
}
static MCRegister convertVRToVRMx(const MCRegisterInfo &RI, MCRegister Reg,
unsigned Kind) {
unsigned RegClassID;
if (Kind == MCK_VRM2)
RegClassID = RISCV::VRM2RegClassID;
else if (Kind == MCK_VRM4)
RegClassID = RISCV::VRM4RegClassID;
else if (Kind == MCK_VRM8)
RegClassID = RISCV::VRM8RegClassID;
else
return MCRegister();
return RI.getMatchingSuperReg(Reg, RISCV::sub_vrm1_0,
&RISCVMCRegisterClasses[RegClassID]);
}
unsigned RISCVAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
unsigned Kind) {
RISCVOperand &Op = static_cast<RISCVOperand &>(AsmOp);
if (!Op.isReg())
return Match_InvalidOperand;
MCRegister Reg = Op.getReg();
bool IsRegFPR64 =
RISCVMCRegisterClasses[RISCV::FPR64RegClassID].contains(Reg);
bool IsRegFPR64C =
RISCVMCRegisterClasses[RISCV::FPR64CRegClassID].contains(Reg);
bool IsRegVR = RISCVMCRegisterClasses[RISCV::VRRegClassID].contains(Reg);
if (IsRegFPR64 && Kind == MCK_FPR128) {
Op.Reg.RegNum = convertFPR64ToFPR128(Reg);
return Match_Success;
}
// As the parser couldn't differentiate an FPR32 from an FPR64, coerce the
// register from FPR64 to FPR32 or FPR64C to FPR32C if necessary.
if ((IsRegFPR64 && Kind == MCK_FPR32) ||
(IsRegFPR64C && Kind == MCK_FPR32C)) {
Op.Reg.RegNum = convertFPR64ToFPR32(Reg);
return Match_Success;
}
// As the parser couldn't differentiate an FPR16 from an FPR64, coerce the
// register from FPR64 to FPR16 if necessary.
if (IsRegFPR64 && Kind == MCK_FPR16) {
Op.Reg.RegNum = convertFPR64ToFPR16(Reg);
return Match_Success;
}
if (Kind == MCK_GPRAsFPR16 && Op.isGPRAsFPR()) {
Op.Reg.RegNum = Reg - RISCV::X0 + RISCV::X0_H;
return Match_Success;
}
if (Kind == MCK_GPRAsFPR32 && Op.isGPRAsFPR()) {
Op.Reg.RegNum = Reg - RISCV::X0 + RISCV::X0_W;
return Match_Success;
}
// There are some GPRF64AsFPR instructions that have no RV32 equivalent. We
// reject them at parsing thinking we should match as GPRPairAsFPR for RV32.
// So we explicitly accept them here for RV32 to allow the generic code to
// report that the instruction requires RV64.
if (RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg) &&
Kind == MCK_GPRF64AsFPR && STI->hasFeature(RISCV::FeatureStdExtZdinx) &&
!isRV64())
return Match_Success;
// As the parser couldn't differentiate an VRM2/VRM4/VRM8 from an VR, coerce
// the register from VR to VRM2/VRM4/VRM8 if necessary.
if (IsRegVR && (Kind == MCK_VRM2 || Kind == MCK_VRM4 || Kind == MCK_VRM8)) {
Op.Reg.RegNum = convertVRToVRMx(*getContext().getRegisterInfo(), Reg, Kind);
if (!Op.Reg.RegNum)
return Match_InvalidOperand;
return Match_Success;
}
return Match_InvalidOperand;
}
bool RISCVAsmParser::generateImmOutOfRangeError(
SMLoc ErrorLoc, int64_t Lower, int64_t Upper,
const Twine &Msg = "immediate must be an integer in the range") {
return Error(ErrorLoc, Msg + " [" + Twine(Lower) + ", " + Twine(Upper) + "]");
}
bool RISCVAsmParser::generateImmOutOfRangeError(
OperandVector &Operands, uint64_t ErrorInfo, int64_t Lower, int64_t Upper,
const Twine &Msg = "immediate must be an integer in the range") {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
return generateImmOutOfRangeError(ErrorLoc, Lower, Upper, Msg);
}
bool RISCVAsmParser::matchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
OperandVector &Operands,
MCStreamer &Out,
uint64_t &ErrorInfo,
bool MatchingInlineAsm) {
MCInst Inst;
FeatureBitset MissingFeatures;
auto Result = MatchInstructionImpl(Operands, Inst, ErrorInfo, MissingFeatures,
MatchingInlineAsm);
switch (Result) {
default:
break;
case Match_Success:
if (validateInstruction(Inst, Operands))
return true;
return processInstruction(Inst, IDLoc, Operands, Out);
case Match_MissingFeature: {
assert(MissingFeatures.any() && "Unknown missing features!");
bool FirstFeature = true;
std::string Msg = "instruction requires the following:";
for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i) {
if (MissingFeatures[i]) {
Msg += FirstFeature ? " " : ", ";
Msg += getSubtargetFeatureName(i);
FirstFeature = false;
}
}
return Error(IDLoc, Msg);
}
case Match_MnemonicFail: {
FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
std::string Suggestion = RISCVMnemonicSpellCheck(
((RISCVOperand &)*Operands[0]).getToken(), FBS, 0);
return Error(IDLoc, "unrecognized instruction mnemonic" + Suggestion);
}
case Match_InvalidOperand: {
SMLoc ErrorLoc = IDLoc;
if (ErrorInfo != ~0ULL) {
if (ErrorInfo >= Operands.size())
return Error(ErrorLoc, "too few operands for instruction");
ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
if (ErrorLoc == SMLoc())
ErrorLoc = IDLoc;
}
return Error(ErrorLoc, "invalid operand for instruction");
}
}
// Handle the case when the error message is of specific type
// other than the generic Match_InvalidOperand, and the
// corresponding operand is missing.
if (Result > FIRST_TARGET_MATCH_RESULT_TY) {
SMLoc ErrorLoc = IDLoc;
if (ErrorInfo != ~0ULL && ErrorInfo >= Operands.size())
return Error(ErrorLoc, "too few operands for instruction");
}
switch (Result) {
default:
break;
case Match_InvalidImmXLenLI:
if (isRV64()) {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
return Error(ErrorLoc, "operand must be a constant 64-bit integer");
}
return generateImmOutOfRangeError(Operands, ErrorInfo,
std::numeric_limits<int32_t>::min(),
std::numeric_limits<uint32_t>::max());
case Match_InvalidImmXLenLI_Restricted:
if (isRV64()) {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
return Error(ErrorLoc, "operand either must be a constant 64-bit integer "
"or a bare symbol name");
}
return generateImmOutOfRangeError(
Operands, ErrorInfo, std::numeric_limits<int32_t>::min(),
std::numeric_limits<uint32_t>::max(),
"operand either must be a bare symbol name or an immediate integer in "
"the range");
case Match_InvalidUImmLog2XLen:
if (isRV64())
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
case Match_InvalidUImmLog2XLenNonZero:
if (isRV64())
return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 6) - 1);
return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
case Match_InvalidUImm1:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 1) - 1);
case Match_InvalidUImm2:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 2) - 1);
case Match_InvalidUImm2Lsb0:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 2,
"immediate must be one of");
case Match_InvalidUImm3:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 3) - 1);
case Match_InvalidUImm4:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 4) - 1);
case Match_InvalidUImm5:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 5) - 1);
case Match_InvalidUImm5NonZero:
return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5) - 1);
case Match_InvalidUImm5GT3:
return generateImmOutOfRangeError(Operands, ErrorInfo, 4, (1 << 5) - 1);
case Match_InvalidUImm5Plus1:
return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 5));
case Match_InvalidUImm5GE6Plus1:
return generateImmOutOfRangeError(Operands, ErrorInfo, 6, (1 << 5));
case Match_InvalidUImm5Slist: {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
return Error(ErrorLoc,
"immediate must be one of: 0, 1, 2, 4, 8, 15, 16, 31");
}
case Match_InvalidUImm6:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 6) - 1);
case Match_InvalidUImm7:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 7) - 1);
case Match_InvalidUImm8:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 8) - 1);
case Match_InvalidUImm8GE32:
return generateImmOutOfRangeError(Operands, ErrorInfo, 32, (1 << 8) - 1);
case Match_InvalidSImm5:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4),
(1 << 4) - 1);
case Match_InvalidSImm5NonZero:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 4), (1 << 4) - 1,
"immediate must be non-zero in the range");
case Match_InvalidSImm6:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 5),
(1 << 5) - 1);
case Match_InvalidSImm6NonZero:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 5), (1 << 5) - 1,
"immediate must be non-zero in the range");
case Match_InvalidCLUIImm:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 1, (1 << 5) - 1,
"immediate must be in [0xfffe0, 0xfffff] or");
case Match_InvalidUImm5Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 5) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidUImm6Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 6) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidUImm7Lsb00:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 7) - 4,
"immediate must be a multiple of 4 bytes in the range");
case Match_InvalidUImm8Lsb00:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 8) - 4,
"immediate must be a multiple of 4 bytes in the range");
case Match_InvalidUImm8Lsb000:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 8) - 8,
"immediate must be a multiple of 8 bytes in the range");
case Match_InvalidUImm9:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 9) - 1,
"immediate offset must be in the range");
case Match_InvalidBareSImm9Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 8), (1 << 8) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidUImm9Lsb000:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 9) - 8,
"immediate must be a multiple of 8 bytes in the range");
case Match_InvalidSImm10:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 9),
(1 << 9) - 1);
case Match_InvalidSImm10Unsigned:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 9),
(1 << 10) - 1);
case Match_InvalidUImm10Lsb00NonZero:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 4, (1 << 10) - 4,
"immediate must be a multiple of 4 bytes in the range");
case Match_InvalidSImm10Lsb0000NonZero:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
"immediate must be a multiple of 16 bytes and non-zero in the range");
case Match_InvalidSImm11:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 10),
(1 << 10) - 1);
case Match_InvalidBareSImm11Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 10), (1 << 10) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidUImm10:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 10) - 1);
case Match_InvalidUImm11:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 11) - 1);
case Match_InvalidUImm14Lsb00:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 14) - 4,
"immediate must be a multiple of 4 bytes in the range");
case Match_InvalidUImm16NonZero:
return generateImmOutOfRangeError(Operands, ErrorInfo, 1, (1 << 16) - 1);
case Match_InvalidSImm12:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 11), (1 << 11) - 1,
"operand must be a symbol with %lo/%pcrel_lo/%tprel_lo specifier or an "
"integer in the range");
case Match_InvalidBareSImm12Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 11), (1 << 11) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidSImm12Lsb00000:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 11), (1 << 11) - 32,
"immediate must be a multiple of 32 bytes in the range");
case Match_InvalidBareSImm13Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 12), (1 << 12) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidSImm16:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 15),
(1 << 15) - 1);
case Match_InvalidSImm16NonZero:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 15), (1 << 15) - 1,
"immediate must be non-zero in the range");
case Match_InvalidSImm20LI:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 19), (1 << 19) - 1,
"operand must be a symbol with a %qc.abs20 specifier or an integer "
" in the range");
case Match_InvalidUImm20LUI:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 20) - 1,
"operand must be a symbol with "
"%hi/%tprel_hi specifier or an integer in "
"the range");
case Match_InvalidUImm20:
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 20) - 1);
case Match_InvalidUImm20AUIPC:
return generateImmOutOfRangeError(
Operands, ErrorInfo, 0, (1 << 20) - 1,
"operand must be a symbol with a "
"%pcrel_hi/%got_pcrel_hi/%tls_ie_pcrel_hi/%tls_gd_pcrel_hi specifier "
"or "
"an integer in the range");
case Match_InvalidBareSImm21Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 20), (1 << 20) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidCSRSystemRegister: {
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 12) - 1,
"operand must be a valid system register "
"name or an integer in the range");
}
case Match_InvalidVTypeI: {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
return generateVTypeError(ErrorLoc);
}
case Match_InvalidSImm5Plus1: {
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 4) + 1,
(1 << 4),
"immediate must be in the range");
}
case Match_InvalidSImm18:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 17),
(1 << 17) - 1);
case Match_InvalidSImm18Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 17), (1 << 17) - 2,
"immediate must be a multiple of 2 bytes in the range");
case Match_InvalidSImm19Lsb00:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 18), (1 << 18) - 4,
"immediate must be a multiple of 4 bytes in the range");
case Match_InvalidSImm20Lsb000:
return generateImmOutOfRangeError(
Operands, ErrorInfo, -(1 << 19), (1 << 19) - 8,
"immediate must be a multiple of 8 bytes in the range");
case Match_InvalidSImm26:
return generateImmOutOfRangeError(Operands, ErrorInfo, -(1 << 25),
(1 << 25) - 1);
// HACK: See comment before `BareSymbolQC_E_LI` in RISCVInstrInfoXqci.td.
case Match_InvalidBareSymbolQC_E_LI:
LLVM_FALLTHROUGH;
// END HACK
case Match_InvalidBareSImm32:
return generateImmOutOfRangeError(Operands, ErrorInfo,
std::numeric_limits<int32_t>::min(),
std::numeric_limits<uint32_t>::max());
case Match_InvalidBareSImm32Lsb0:
return generateImmOutOfRangeError(
Operands, ErrorInfo, std::numeric_limits<int32_t>::min(),
std::numeric_limits<int32_t>::max() - 1,
"operand must be a multiple of 2 bytes in the range");
case Match_InvalidRnumArg: {
return generateImmOutOfRangeError(Operands, ErrorInfo, 0, 10);
}
case Match_InvalidStackAdj: {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
return Error(
ErrorLoc,
"stack adjustment is invalid for this instruction and register list");
}
}
if (const char *MatchDiag = getMatchKindDiag((RISCVMatchResultTy)Result)) {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[ErrorInfo]).getStartLoc();
return Error(ErrorLoc, MatchDiag);
}
llvm_unreachable("Unknown match type detected!");
}
// Attempts to match Name as a register (either using the default name or
// alternative ABI names), returning the matching register. Upon failure,
// returns a non-valid MCRegister. If IsRVE, then registers x16-x31 will be
// rejected.
MCRegister RISCVAsmParser::matchRegisterNameHelper(StringRef Name) const {
MCRegister Reg = MatchRegisterName(Name);
// The 16-/32-/128- and 64-bit FPRs have the same asm name. Check
// that the initial match always matches the 64-bit variant, and
// not the 16/32/128-bit one.
assert(!(Reg >= RISCV::F0_H && Reg <= RISCV::F31_H));
assert(!(Reg >= RISCV::F0_F && Reg <= RISCV::F31_F));
assert(!(Reg >= RISCV::F0_Q && Reg <= RISCV::F31_Q));
// The default FPR register class is based on the tablegen enum ordering.
static_assert(RISCV::F0_D < RISCV::F0_H, "FPR matching must be updated");
static_assert(RISCV::F0_D < RISCV::F0_F, "FPR matching must be updated");
static_assert(RISCV::F0_D < RISCV::F0_Q, "FPR matching must be updated");
if (!Reg)
Reg = MatchRegisterAltName(Name);
if (isRVE() && Reg >= RISCV::X16 && Reg <= RISCV::X31)
Reg = MCRegister();
return Reg;
}
bool RISCVAsmParser::parseRegister(MCRegister &Reg, SMLoc &StartLoc,
SMLoc &EndLoc) {
if (!tryParseRegister(Reg, StartLoc, EndLoc).isSuccess())
return Error(StartLoc, "invalid register name");
return false;
}
ParseStatus RISCVAsmParser::tryParseRegister(MCRegister &Reg, SMLoc &StartLoc,
SMLoc &EndLoc) {
const AsmToken &Tok = getParser().getTok();
StartLoc = Tok.getLoc();
EndLoc = Tok.getEndLoc();
StringRef Name = getLexer().getTok().getIdentifier();
Reg = matchRegisterNameHelper(Name);
if (!Reg)
return ParseStatus::NoMatch;
getParser().Lex(); // Eat identifier token.
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseRegister(OperandVector &Operands,
bool AllowParens) {
SMLoc FirstS = getLoc();
bool HadParens = false;
AsmToken LParen;
// If this is an LParen and a parenthesised register name is allowed, parse it
// atomically.
if (AllowParens && getLexer().is(AsmToken::LParen)) {
AsmToken Buf[2];
size_t ReadCount = getLexer().peekTokens(Buf);
if (ReadCount == 2 && Buf[1].getKind() == AsmToken::RParen) {
HadParens = true;
LParen = getParser().getTok();
getParser().Lex(); // Eat '('
}
}
switch (getLexer().getKind()) {
default:
if (HadParens)
getLexer().UnLex(LParen);
return ParseStatus::NoMatch;
case AsmToken::Identifier:
StringRef Name = getLexer().getTok().getIdentifier();
MCRegister Reg = matchRegisterNameHelper(Name);
if (!Reg) {
if (HadParens)
getLexer().UnLex(LParen);
return ParseStatus::NoMatch;
}
if (HadParens)
Operands.push_back(RISCVOperand::createToken("(", FirstS));
SMLoc S = getLoc();
SMLoc E = getTok().getEndLoc();
getLexer().Lex();
Operands.push_back(RISCVOperand::createReg(Reg, S, E));
}
if (HadParens) {
getParser().Lex(); // Eat ')'
Operands.push_back(RISCVOperand::createToken(")", getLoc()));
}
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseInsnDirectiveOpcode(OperandVector &Operands) {
SMLoc S = getLoc();
SMLoc E;
const MCExpr *Res;
switch (getLexer().getKind()) {
default:
return ParseStatus::NoMatch;
case AsmToken::LParen:
case AsmToken::Minus:
case AsmToken::Plus:
case AsmToken::Exclaim:
case AsmToken::Tilde:
case AsmToken::Integer:
case AsmToken::String: {
if (getParser().parseExpression(Res, E))
return ParseStatus::Failure;
auto *CE = dyn_cast<MCConstantExpr>(Res);
if (CE) {
int64_t Imm = CE->getValue();
if (isUInt<7>(Imm)) {
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
}
break;
}
case AsmToken::Identifier: {
StringRef Identifier;
if (getParser().parseIdentifier(Identifier))
return ParseStatus::Failure;
auto Opcode = RISCVInsnOpcode::lookupRISCVOpcodeByName(Identifier);
if (Opcode) {
assert(isUInt<7>(Opcode->Value) && (Opcode->Value & 0x3) == 3 &&
"Unexpected opcode");
Res = MCConstantExpr::create(Opcode->Value, getContext());
E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
break;
}
case AsmToken::Percent:
break;
}
return generateImmOutOfRangeError(
S, 0, 127,
"opcode must be a valid opcode name or an immediate in the range");
}
ParseStatus RISCVAsmParser::parseInsnCDirectiveOpcode(OperandVector &Operands) {
SMLoc S = getLoc();
SMLoc E;
const MCExpr *Res;
switch (getLexer().getKind()) {
default:
return ParseStatus::NoMatch;
case AsmToken::LParen:
case AsmToken::Minus:
case AsmToken::Plus:
case AsmToken::Exclaim:
case AsmToken::Tilde:
case AsmToken::Integer:
case AsmToken::String: {
if (getParser().parseExpression(Res, E))
return ParseStatus::Failure;
auto *CE = dyn_cast<MCConstantExpr>(Res);
if (CE) {
int64_t Imm = CE->getValue();
if (Imm >= 0 && Imm <= 2) {
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
}
break;
}
case AsmToken::Identifier: {
StringRef Identifier;
if (getParser().parseIdentifier(Identifier))
return ParseStatus::Failure;
unsigned Opcode;
if (Identifier == "C0")
Opcode = 0;
else if (Identifier == "C1")
Opcode = 1;
else if (Identifier == "C2")
Opcode = 2;
else
break;
Res = MCConstantExpr::create(Opcode, getContext());
E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
case AsmToken::Percent: {
// Discard operand with modifier.
break;
}
}
return generateImmOutOfRangeError(
S, 0, 2,
"opcode must be a valid opcode name or an immediate in the range");
}
ParseStatus RISCVAsmParser::parseCSRSystemRegister(OperandVector &Operands) {
SMLoc S = getLoc();
const MCExpr *Res;
auto SysRegFromConstantInt = [this](const MCExpr *E, SMLoc S) {
if (auto *CE = dyn_cast<MCConstantExpr>(E)) {
int64_t Imm = CE->getValue();
if (isUInt<12>(Imm)) {
auto Range = RISCVSysReg::lookupSysRegByEncoding(Imm);
// Accept an immediate representing a named Sys Reg if it satisfies the
// the required features.
for (auto &Reg : Range) {
if (Reg.IsAltName || Reg.IsDeprecatedName)
continue;
if (Reg.haveRequiredFeatures(STI->getFeatureBits()))
return RISCVOperand::createSysReg(Reg.Name, S, Imm);
}
// Accept an immediate representing an un-named Sys Reg if the range is
// valid, regardless of the required features.
return RISCVOperand::createSysReg("", S, Imm);
}
}
return std::unique_ptr<RISCVOperand>();
};
switch (getLexer().getKind()) {
default:
return ParseStatus::NoMatch;
case AsmToken::LParen:
case AsmToken::Minus:
case AsmToken::Plus:
case AsmToken::Exclaim:
case AsmToken::Tilde:
case AsmToken::Integer:
case AsmToken::String: {
if (getParser().parseExpression(Res))
return ParseStatus::Failure;
if (auto SysOpnd = SysRegFromConstantInt(Res, S)) {
Operands.push_back(std::move(SysOpnd));
return ParseStatus::Success;
}
return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
}
case AsmToken::Identifier: {
StringRef Identifier;
if (getParser().parseIdentifier(Identifier))
return ParseStatus::Failure;
const auto *SysReg = RISCVSysReg::lookupSysRegByName(Identifier);
if (SysReg) {
if (SysReg->IsDeprecatedName) {
// Lookup the undeprecated name.
auto Range = RISCVSysReg::lookupSysRegByEncoding(SysReg->Encoding);
for (auto &Reg : Range) {
if (Reg.IsAltName || Reg.IsDeprecatedName)
continue;
Warning(S, "'" + Identifier + "' is a deprecated alias for '" +
Reg.Name + "'");
}
}
// Accept a named Sys Reg if the required features are present.
const auto &FeatureBits = getSTI().getFeatureBits();
if (!SysReg->haveRequiredFeatures(FeatureBits)) {
const auto *Feature = llvm::find_if(RISCVFeatureKV, [&](auto Feature) {
return SysReg->FeaturesRequired[Feature.Value];
});
auto ErrorMsg = std::string("system register '") + SysReg->Name + "' ";
if (SysReg->IsRV32Only && FeatureBits[RISCV::Feature64Bit]) {
ErrorMsg += "is RV32 only";
if (Feature != std::end(RISCVFeatureKV))
ErrorMsg += " and ";
}
if (Feature != std::end(RISCVFeatureKV)) {
ErrorMsg +=
"requires '" + std::string(Feature->Key) + "' to be enabled";
}
return Error(S, ErrorMsg);
}
Operands.push_back(
RISCVOperand::createSysReg(Identifier, S, SysReg->Encoding));
return ParseStatus::Success;
}
// Accept a symbol name that evaluates to an absolute value.
MCSymbol *Sym = getContext().lookupSymbol(Identifier);
if (Sym && Sym->isVariable()) {
// Pass false for SetUsed, since redefining the value later does not
// affect this instruction.
if (auto SysOpnd = SysRegFromConstantInt(Sym->getVariableValue(), S)) {
Operands.push_back(std::move(SysOpnd));
return ParseStatus::Success;
}
}
return generateImmOutOfRangeError(S, 0, (1 << 12) - 1,
"operand must be a valid system register "
"name or an integer in the range");
}
case AsmToken::Percent: {
// Discard operand with modifier.
return generateImmOutOfRangeError(S, 0, (1 << 12) - 1);
}
}
return ParseStatus::NoMatch;
}
ParseStatus RISCVAsmParser::parseFPImm(OperandVector &Operands) {
SMLoc S = getLoc();
// Parse special floats (inf/nan/min) representation.
if (getTok().is(AsmToken::Identifier)) {
StringRef Identifier = getTok().getIdentifier();
if (Identifier.compare_insensitive("inf") == 0) {
Operands.push_back(
RISCVOperand::createImm(MCConstantExpr::create(30, getContext()), S,
getTok().getEndLoc(), isRV64()));
} else if (Identifier.compare_insensitive("nan") == 0) {
Operands.push_back(
RISCVOperand::createImm(MCConstantExpr::create(31, getContext()), S,
getTok().getEndLoc(), isRV64()));
} else if (Identifier.compare_insensitive("min") == 0) {
Operands.push_back(
RISCVOperand::createImm(MCConstantExpr::create(1, getContext()), S,
getTok().getEndLoc(), isRV64()));
} else {
return TokError("invalid floating point literal");
}
Lex(); // Eat the token.
return ParseStatus::Success;
}
// Handle negation, as that still comes through as a separate token.
bool IsNegative = parseOptionalToken(AsmToken::Minus);
const AsmToken &Tok = getTok();
if (!Tok.is(AsmToken::Real))
return TokError("invalid floating point immediate");
// Parse FP representation.
APFloat RealVal(APFloat::IEEEdouble());
auto StatusOrErr =
RealVal.convertFromString(Tok.getString(), APFloat::rmTowardZero);
if (errorToBool(StatusOrErr.takeError()))
return TokError("invalid floating point representation");
if (IsNegative)
RealVal.changeSign();
Operands.push_back(RISCVOperand::createFPImm(
RealVal.bitcastToAPInt().getZExtValue(), S));
Lex(); // Eat the token.
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseImmediate(OperandVector &Operands) {
SMLoc S = getLoc();
SMLoc E;
const MCExpr *Res;
switch (getLexer().getKind()) {
default:
return ParseStatus::NoMatch;
case AsmToken::LParen:
case AsmToken::Dot:
case AsmToken::Minus:
case AsmToken::Plus:
case AsmToken::Exclaim:
case AsmToken::Tilde:
case AsmToken::Integer:
case AsmToken::String:
case AsmToken::Identifier:
if (getParser().parseExpression(Res, E))
return ParseStatus::Failure;
break;
case AsmToken::Percent:
return parseOperandWithSpecifier(Operands);
}
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseOperandWithSpecifier(OperandVector &Operands) {
SMLoc S = getLoc();
SMLoc E;
if (parseToken(AsmToken::Percent, "expected '%' relocation specifier"))
return ParseStatus::Failure;
const MCExpr *Expr = nullptr;
bool Failed = parseExprWithSpecifier(Expr, E);
if (!Failed)
Operands.push_back(RISCVOperand::createImm(Expr, S, E, isRV64()));
return Failed;
}
bool RISCVAsmParser::parseExprWithSpecifier(const MCExpr *&Res, SMLoc &E) {
SMLoc Loc = getLoc();
if (getLexer().getKind() != AsmToken::Identifier)
return TokError("expected '%' relocation specifier");
StringRef Identifier = getParser().getTok().getIdentifier();
auto Spec = RISCV::parseSpecifierName(Identifier);
if (!Spec)
return TokError("invalid relocation specifier");
getParser().Lex(); // Eat the identifier
if (parseToken(AsmToken::LParen, "expected '('"))
return true;
const MCExpr *SubExpr;
if (getParser().parseParenExpression(SubExpr, E))
return true;
Res = MCSpecifierExpr::create(SubExpr, Spec, getContext(), Loc);
return false;
}
bool RISCVAsmParser::parseDataExpr(const MCExpr *&Res) {
SMLoc E;
if (parseOptionalToken(AsmToken::Percent))
return parseExprWithSpecifier(Res, E);
return getParser().parseExpression(Res);
}
ParseStatus RISCVAsmParser::parseBareSymbol(OperandVector &Operands) {
SMLoc S = getLoc();
const MCExpr *Res;
if (getLexer().getKind() != AsmToken::Identifier)
return ParseStatus::NoMatch;
StringRef Identifier;
AsmToken Tok = getLexer().getTok();
if (getParser().parseIdentifier(Identifier))
return ParseStatus::Failure;
SMLoc E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
if (Sym->isVariable()) {
const MCExpr *V = Sym->getVariableValue();
if (!isa<MCSymbolRefExpr>(V)) {
getLexer().UnLex(Tok); // Put back if it's not a bare symbol.
return ParseStatus::NoMatch;
}
Res = V;
} else
Res = MCSymbolRefExpr::create(Sym, getContext());
MCBinaryExpr::Opcode Opcode;
switch (getLexer().getKind()) {
default:
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
case AsmToken::Plus:
Opcode = MCBinaryExpr::Add;
getLexer().Lex();
break;
case AsmToken::Minus:
Opcode = MCBinaryExpr::Sub;
getLexer().Lex();
break;
}
const MCExpr *Expr;
if (getParser().parseExpression(Expr, E))
return ParseStatus::Failure;
Res = MCBinaryExpr::create(Opcode, Res, Expr, getContext());
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseCallSymbol(OperandVector &Operands) {
SMLoc S = getLoc();
const MCExpr *Res;
if (getLexer().getKind() != AsmToken::Identifier)
return ParseStatus::NoMatch;
std::string Identifier(getTok().getIdentifier());
if (getLexer().peekTok().is(AsmToken::At)) {
Lex();
Lex();
StringRef PLT;
SMLoc Loc = getLoc();
if (getParser().parseIdentifier(PLT) || PLT != "plt")
return Error(Loc, "@ (except the deprecated/ignored @plt) is disallowed");
} else if (!getLexer().peekTok().is(AsmToken::EndOfStatement)) {
// Avoid parsing the register in `call rd, foo` as a call symbol.
return ParseStatus::NoMatch;
} else {
Lex();
}
SMLoc E = SMLoc::getFromPointer(S.getPointer() + Identifier.size());
RISCV::Specifier Kind = ELF::R_RISCV_CALL_PLT;
MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
Res = MCSymbolRefExpr::create(Sym, getContext());
Res = MCSpecifierExpr::create(Res, Kind, getContext());
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parsePseudoJumpSymbol(OperandVector &Operands) {
SMLoc S = getLoc();
SMLoc E;
const MCExpr *Res;
if (getParser().parseExpression(Res, E))
return ParseStatus::Failure;
if (Res->getKind() != MCExpr::ExprKind::SymbolRef)
return Error(S, "operand must be a valid jump target");
Res = MCSpecifierExpr::create(Res, ELF::R_RISCV_CALL_PLT, getContext());
Operands.push_back(RISCVOperand::createImm(Res, S, E, isRV64()));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseJALOffset(OperandVector &Operands) {
// Parsing jal operands is fiddly due to the `jal foo` and `jal ra, foo`
// both being acceptable forms. When parsing `jal ra, foo` this function
// will be called for the `ra` register operand in an attempt to match the
// single-operand alias. parseJALOffset must fail for this case. It would
// seem logical to try parse the operand using parseImmediate and return
// NoMatch if the next token is a comma (meaning we must be parsing a jal in
// the second form rather than the first). We can't do this as there's no
// way of rewinding the lexer state. Instead, return NoMatch if this operand
// is an identifier and is followed by a comma.
if (getLexer().is(AsmToken::Identifier) &&
getLexer().peekTok().is(AsmToken::Comma))
return ParseStatus::NoMatch;
return parseImmediate(Operands);
}
bool RISCVAsmParser::parseVTypeToken(const AsmToken &Tok, VTypeState &State,
unsigned &Sew, unsigned &Lmul,
bool &Fractional, bool &TailAgnostic,
bool &MaskAgnostic) {
if (Tok.isNot(AsmToken::Identifier))
return true;
StringRef Identifier = Tok.getIdentifier();
if (State < VTypeState::SeenSew && Identifier.consume_front("e")) {
if (Identifier.getAsInteger(10, Sew))
return true;
if (!RISCVVType::isValidSEW(Sew))
return true;
State = VTypeState::SeenSew;
return false;
}
if (State < VTypeState::SeenLmul && Identifier.consume_front("m")) {
// Might arrive here if lmul and tail policy unspecified, if so we're
// parsing a MaskPolicy not an LMUL.
if (Identifier == "a" || Identifier == "u") {
MaskAgnostic = (Identifier == "a");
State = VTypeState::SeenMaskPolicy;
return false;
}
Fractional = Identifier.consume_front("f");
if (Identifier.getAsInteger(10, Lmul))
return true;
if (!RISCVVType::isValidLMUL(Lmul, Fractional))
return true;
if (Fractional) {
unsigned ELEN = STI->hasFeature(RISCV::FeatureStdExtZve64x) ? 64 : 32;
unsigned MinLMUL = ELEN / 8;
if (Lmul > MinLMUL)
Warning(Tok.getLoc(),
"use of vtype encodings with LMUL < SEWMIN/ELEN == mf" +
Twine(MinLMUL) + " is reserved");
}
State = VTypeState::SeenLmul;
return false;
}
if (State < VTypeState::SeenTailPolicy && Identifier.starts_with("t")) {
if (Identifier == "ta")
TailAgnostic = true;
else if (Identifier == "tu")
TailAgnostic = false;
else
return true;
State = VTypeState::SeenTailPolicy;
return false;
}
if (State < VTypeState::SeenMaskPolicy && Identifier.starts_with("m")) {
if (Identifier == "ma")
MaskAgnostic = true;
else if (Identifier == "mu")
MaskAgnostic = false;
else
return true;
State = VTypeState::SeenMaskPolicy;
return false;
}
return true;
}
ParseStatus RISCVAsmParser::parseVTypeI(OperandVector &Operands) {
SMLoc S = getLoc();
// Default values
unsigned Sew = 8;
unsigned Lmul = 1;
bool Fractional = false;
bool TailAgnostic = false;
bool MaskAgnostic = false;
VTypeState State = VTypeState::SeenNothingYet;
do {
if (parseVTypeToken(getTok(), State, Sew, Lmul, Fractional, TailAgnostic,
MaskAgnostic)) {
// The first time, errors return NoMatch rather than Failure
if (State == VTypeState::SeenNothingYet)
return ParseStatus::NoMatch;
break;
}
getLexer().Lex();
} while (parseOptionalToken(AsmToken::Comma));
if (!getLexer().is(AsmToken::EndOfStatement) ||
State == VTypeState::SeenNothingYet)
return generateVTypeError(S);
RISCVVType::VLMUL VLMUL = RISCVVType::encodeLMUL(Lmul, Fractional);
if (Fractional) {
unsigned ELEN = STI->hasFeature(RISCV::FeatureStdExtZve64x) ? 64 : 32;
unsigned MaxSEW = ELEN / Lmul;
// If MaxSEW < 8, we should have printed warning about reserved LMUL.
if (MaxSEW >= 8 && Sew > MaxSEW)
Warning(S, "use of vtype encodings with SEW > " + Twine(MaxSEW) +
" and LMUL == mf" + Twine(Lmul) +
" may not be compatible with all RVV implementations");
}
unsigned VTypeI =
RISCVVType::encodeVTYPE(VLMUL, Sew, TailAgnostic, MaskAgnostic);
Operands.push_back(RISCVOperand::createVType(VTypeI, S));
return ParseStatus::Success;
}
bool RISCVAsmParser::generateVTypeError(SMLoc ErrorLoc) {
return Error(
ErrorLoc,
"operand must be "
"e[8|16|32|64],m[1|2|4|8|f2|f4|f8],[ta|tu],[ma|mu]");
}
ParseStatus RISCVAsmParser::parseXSfmmVType(OperandVector &Operands) {
SMLoc S = getLoc();
unsigned Widen = 0;
unsigned SEW = 0;
bool AltFmt = false;
StringRef Identifier;
if (getTok().isNot(AsmToken::Identifier))
goto Fail;
Identifier = getTok().getIdentifier();
if (!Identifier.consume_front("e"))
goto Fail;
if (Identifier.getAsInteger(10, SEW)) {
if (Identifier != "16alt")
goto Fail;
AltFmt = true;
SEW = 16;
}
if (!RISCVVType::isValidSEW(SEW))
goto Fail;
Lex();
if (!parseOptionalToken(AsmToken::Comma))
goto Fail;
if (getTok().isNot(AsmToken::Identifier))
goto Fail;
Identifier = getTok().getIdentifier();
if (!Identifier.consume_front("w"))
goto Fail;
if (Identifier.getAsInteger(10, Widen))
goto Fail;
if (Widen != 1 && Widen != 2 && Widen != 4)
goto Fail;
Lex();
if (getLexer().is(AsmToken::EndOfStatement)) {
Operands.push_back(RISCVOperand::createVType(
RISCVVType::encodeXSfmmVType(SEW, Widen, AltFmt), S));
return ParseStatus::Success;
}
Fail:
return generateXSfmmVTypeError(S);
}
bool RISCVAsmParser::generateXSfmmVTypeError(SMLoc ErrorLoc) {
return Error(ErrorLoc, "operand must be e[8|16|16alt|32|64],w[1|2|4]");
}
ParseStatus RISCVAsmParser::parseMaskReg(OperandVector &Operands) {
if (getLexer().isNot(AsmToken::Identifier))
return ParseStatus::NoMatch;
StringRef Name = getLexer().getTok().getIdentifier();
if (!Name.consume_back(".t"))
return Error(getLoc(), "expected '.t' suffix");
MCRegister Reg = matchRegisterNameHelper(Name);
if (!Reg)
return ParseStatus::NoMatch;
if (Reg != RISCV::V0)
return ParseStatus::NoMatch;
SMLoc S = getLoc();
SMLoc E = getTok().getEndLoc();
getLexer().Lex();
Operands.push_back(RISCVOperand::createReg(Reg, S, E));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseGPRAsFPR64(OperandVector &Operands) {
if (!isRV64() || getSTI().hasFeature(RISCV::FeatureStdExtF))
return ParseStatus::NoMatch;
return parseGPRAsFPR(Operands);
}
ParseStatus RISCVAsmParser::parseGPRAsFPR(OperandVector &Operands) {
if (getLexer().isNot(AsmToken::Identifier))
return ParseStatus::NoMatch;
StringRef Name = getLexer().getTok().getIdentifier();
MCRegister Reg = matchRegisterNameHelper(Name);
if (!Reg)
return ParseStatus::NoMatch;
SMLoc S = getLoc();
SMLoc E = getTok().getEndLoc();
getLexer().Lex();
Operands.push_back(RISCVOperand::createReg(
Reg, S, E, !getSTI().hasFeature(RISCV::FeatureStdExtF)));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseGPRPairAsFPR64(OperandVector &Operands) {
if (isRV64() || getSTI().hasFeature(RISCV::FeatureStdExtF))
return ParseStatus::NoMatch;
if (getLexer().isNot(AsmToken::Identifier))
return ParseStatus::NoMatch;
StringRef Name = getLexer().getTok().getIdentifier();
MCRegister Reg = matchRegisterNameHelper(Name);
if (!Reg)
return ParseStatus::NoMatch;
if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg))
return ParseStatus::NoMatch;
if ((Reg - RISCV::X0) & 1) {
// Only report the even register error if we have at least Zfinx so we know
// some FP is enabled. We already checked F earlier.
if (getSTI().hasFeature(RISCV::FeatureStdExtZfinx))
return TokError("double precision floating point operands must use even "
"numbered X register");
return ParseStatus::NoMatch;
}
SMLoc S = getLoc();
SMLoc E = getTok().getEndLoc();
getLexer().Lex();
const MCRegisterInfo *RI = getContext().getRegisterInfo();
MCRegister Pair = RI->getMatchingSuperReg(
Reg, RISCV::sub_gpr_even,
&RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
Operands.push_back(RISCVOperand::createReg(Pair, S, E, /*isGPRAsFPR=*/true));
return ParseStatus::Success;
}
template <bool IsRV64>
ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands) {
return parseGPRPair(Operands, IsRV64);
}
ParseStatus RISCVAsmParser::parseGPRPair(OperandVector &Operands,
bool IsRV64Inst) {
// If this is not an RV64 GPRPair instruction, don't parse as a GPRPair on
// RV64 as it will prevent matching the RV64 version of the same instruction
// that doesn't use a GPRPair.
// If this is an RV64 GPRPair instruction, there is no RV32 version so we can
// still parse as a pair.
if (!IsRV64Inst && isRV64())
return ParseStatus::NoMatch;
if (getLexer().isNot(AsmToken::Identifier))
return ParseStatus::NoMatch;
StringRef Name = getLexer().getTok().getIdentifier();
MCRegister Reg = matchRegisterNameHelper(Name);
if (!Reg)
return ParseStatus::NoMatch;
if (!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(Reg))
return ParseStatus::NoMatch;
if ((Reg - RISCV::X0) & 1)
return TokError("register must be even");
SMLoc S = getLoc();
SMLoc E = getTok().getEndLoc();
getLexer().Lex();
const MCRegisterInfo *RI = getContext().getRegisterInfo();
MCRegister Pair = RI->getMatchingSuperReg(
Reg, RISCV::sub_gpr_even,
&RISCVMCRegisterClasses[RISCV::GPRPairRegClassID]);
Operands.push_back(RISCVOperand::createReg(Pair, S, E));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseFRMArg(OperandVector &Operands) {
if (getLexer().isNot(AsmToken::Identifier))
return TokError(
"operand must be a valid floating point rounding mode mnemonic");
StringRef Str = getLexer().getTok().getIdentifier();
RISCVFPRndMode::RoundingMode FRM = RISCVFPRndMode::stringToRoundingMode(Str);
if (FRM == RISCVFPRndMode::Invalid)
return TokError(
"operand must be a valid floating point rounding mode mnemonic");
Operands.push_back(RISCVOperand::createFRMArg(FRM, getLoc()));
Lex(); // Eat identifier token.
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseFenceArg(OperandVector &Operands) {
const AsmToken &Tok = getLexer().getTok();
if (Tok.is(AsmToken::Integer)) {
if (Tok.getIntVal() != 0)
goto ParseFail;
Operands.push_back(RISCVOperand::createFenceArg(0, getLoc()));
Lex();
return ParseStatus::Success;
}
if (Tok.is(AsmToken::Identifier)) {
StringRef Str = Tok.getIdentifier();
// Letters must be unique, taken from 'iorw', and in ascending order. This
// holds as long as each individual character is one of 'iorw' and is
// greater than the previous character.
unsigned Imm = 0;
bool Valid = true;
char Prev = '\0';
for (char c : Str) {
switch (c) {
default:
Valid = false;
break;
case 'i':
Imm |= RISCVFenceField::I;
break;
case 'o':
Imm |= RISCVFenceField::O;
break;
case 'r':
Imm |= RISCVFenceField::R;
break;
case 'w':
Imm |= RISCVFenceField::W;
break;
}
if (c <= Prev) {
Valid = false;
break;
}
Prev = c;
}
if (!Valid)
goto ParseFail;
Operands.push_back(RISCVOperand::createFenceArg(Imm, getLoc()));
Lex();
return ParseStatus::Success;
}
ParseFail:
return TokError("operand must be formed of letters selected in-order from "
"'iorw' or be 0");
}
ParseStatus RISCVAsmParser::parseMemOpBaseReg(OperandVector &Operands) {
if (parseToken(AsmToken::LParen, "expected '('"))
return ParseStatus::Failure;
Operands.push_back(RISCVOperand::createToken("(", getLoc()));
if (!parseRegister(Operands).isSuccess())
return Error(getLoc(), "expected register");
if (parseToken(AsmToken::RParen, "expected ')'"))
return ParseStatus::Failure;
Operands.push_back(RISCVOperand::createToken(")", getLoc()));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseZeroOffsetMemOp(OperandVector &Operands) {
// Atomic operations such as lr.w, sc.w, and amo*.w accept a "memory operand"
// as one of their register operands, such as `(a0)`. This just denotes that
// the register (in this case `a0`) contains a memory address.
//
// Normally, we would be able to parse these by putting the parens into the
// instruction string. However, GNU as also accepts a zero-offset memory
// operand (such as `0(a0)`), and ignores the 0. Normally this would be parsed
// with parseImmediate followed by parseMemOpBaseReg, but these instructions
// do not accept an immediate operand, and we do not want to add a "dummy"
// operand that is silently dropped.
//
// Instead, we use this custom parser. This will: allow (and discard) an
// offset if it is zero; require (and discard) parentheses; and add only the
// parsed register operand to `Operands`.
//
// These operands are printed with RISCVInstPrinter::printZeroOffsetMemOp,
// which will only print the register surrounded by parentheses (which GNU as
// also uses as its canonical representation for these operands).
std::unique_ptr<RISCVOperand> OptionalImmOp;
if (getLexer().isNot(AsmToken::LParen)) {
// Parse an Integer token. We do not accept arbitrary constant expressions
// in the offset field (because they may include parens, which complicates
// parsing a lot).
int64_t ImmVal;
SMLoc ImmStart = getLoc();
if (getParser().parseIntToken(ImmVal,
"expected '(' or optional integer offset"))
return ParseStatus::Failure;
// Create a RISCVOperand for checking later (so the error messages are
// nicer), but we don't add it to Operands.
SMLoc ImmEnd = getLoc();
OptionalImmOp =
RISCVOperand::createImm(MCConstantExpr::create(ImmVal, getContext()),
ImmStart, ImmEnd, isRV64());
}
if (parseToken(AsmToken::LParen,
OptionalImmOp ? "expected '(' after optional integer offset"
: "expected '(' or optional integer offset"))
return ParseStatus::Failure;
if (!parseRegister(Operands).isSuccess())
return Error(getLoc(), "expected register");
if (parseToken(AsmToken::RParen, "expected ')'"))
return ParseStatus::Failure;
// Deferred Handling of non-zero offsets. This makes the error messages nicer.
if (OptionalImmOp && !OptionalImmOp->isImmZero())
return Error(
OptionalImmOp->getStartLoc(), "optional integer offset must be 0",
SMRange(OptionalImmOp->getStartLoc(), OptionalImmOp->getEndLoc()));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseRegReg(OperandVector &Operands) {
// RR : a2(a1)
if (getLexer().getKind() != AsmToken::Identifier)
return ParseStatus::NoMatch;
SMLoc S = getLoc();
StringRef OffsetRegName = getLexer().getTok().getIdentifier();
MCRegister OffsetReg = matchRegisterNameHelper(OffsetRegName);
if (!OffsetReg ||
!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(OffsetReg))
return Error(getLoc(), "expected GPR register");
getLexer().Lex();
if (parseToken(AsmToken::LParen, "expected '(' or invalid operand"))
return ParseStatus::Failure;
if (getLexer().getKind() != AsmToken::Identifier)
return Error(getLoc(), "expected GPR register");
StringRef BaseRegName = getLexer().getTok().getIdentifier();
MCRegister BaseReg = matchRegisterNameHelper(BaseRegName);
if (!BaseReg ||
!RISCVMCRegisterClasses[RISCV::GPRRegClassID].contains(BaseReg))
return Error(getLoc(), "expected GPR register");
getLexer().Lex();
if (parseToken(AsmToken::RParen, "expected ')'"))
return ParseStatus::Failure;
Operands.push_back(RISCVOperand::createRegReg(BaseReg, OffsetReg, S));
return ParseStatus::Success;
}
// RegList: {ra [, s0[-sN]]}
// XRegList: {x1 [, x8[-x9][, x18[-xN]]]}
// When MustIncludeS0 = true (not the default) (used for `qc.cm.pushfp`) which
// must include `fp`/`s0` in the list:
// RegList: {ra, s0[-sN]}
// XRegList: {x1, x8[-x9][, x18[-xN]]}
ParseStatus RISCVAsmParser::parseRegList(OperandVector &Operands,
bool MustIncludeS0) {
if (getTok().isNot(AsmToken::LCurly))
return ParseStatus::NoMatch;
SMLoc S = getLoc();
Lex();
bool UsesXRegs;
MCRegister RegEnd;
do {
if (getTok().isNot(AsmToken::Identifier))
return Error(getLoc(), "invalid register");
StringRef RegName = getTok().getIdentifier();
MCRegister Reg = matchRegisterNameHelper(RegName);
if (!Reg)
return Error(getLoc(), "invalid register");
if (!RegEnd) {
UsesXRegs = RegName[0] == 'x';
if (Reg != RISCV::X1)
return Error(getLoc(), "register list must start from 'ra' or 'x1'");
} else if (RegEnd == RISCV::X1) {
if (Reg != RISCV::X8 || (UsesXRegs != (RegName[0] == 'x')))
return Error(getLoc(), Twine("register must be '") +
(UsesXRegs ? "x8" : "s0") + "'");
} else if (RegEnd == RISCV::X9 && UsesXRegs) {
if (Reg != RISCV::X18 || (RegName[0] != 'x'))
return Error(getLoc(), "register must be 'x18'");
} else {
return Error(getLoc(), "too many register ranges");
}
RegEnd = Reg;
Lex();
SMLoc MinusLoc = getLoc();
if (parseOptionalToken(AsmToken::Minus)) {
if (RegEnd == RISCV::X1)
return Error(MinusLoc, Twine("register '") + (UsesXRegs ? "x1" : "ra") +
"' cannot start a multiple register range");
if (getTok().isNot(AsmToken::Identifier))
return Error(getLoc(), "invalid register");
StringRef RegName = getTok().getIdentifier();
MCRegister Reg = matchRegisterNameHelper(RegName);
if (!Reg)
return Error(getLoc(), "invalid register");
if (RegEnd == RISCV::X8) {
if ((Reg != RISCV::X9 &&
(UsesXRegs || Reg < RISCV::X18 || Reg > RISCV::X27)) ||
(UsesXRegs != (RegName[0] == 'x'))) {
if (UsesXRegs)
return Error(getLoc(), "register must be 'x9'");
return Error(getLoc(), "register must be in the range 's1' to 's11'");
}
} else if (RegEnd == RISCV::X18) {
if (Reg < RISCV::X19 || Reg > RISCV::X27 || (RegName[0] != 'x'))
return Error(getLoc(),
"register must be in the range 'x19' to 'x27'");
} else
llvm_unreachable("unexpected register");
RegEnd = Reg;
Lex();
}
} while (parseOptionalToken(AsmToken::Comma));
if (parseToken(AsmToken::RCurly, "expected ',' or '}'"))
return ParseStatus::Failure;
if (RegEnd == RISCV::X26)
return Error(S, "invalid register list, '{ra, s0-s10}' or '{x1, x8-x9, "
"x18-x26}' is not supported");
auto Encode = RISCVZC::encodeRegList(RegEnd, isRVE());
assert(Encode != RISCVZC::INVALID_RLIST);
if (MustIncludeS0 && Encode == RISCVZC::RA)
return Error(S, "register list must include 's0' or 'x8'");
Operands.push_back(RISCVOperand::createRegList(Encode, S));
return ParseStatus::Success;
}
ParseStatus RISCVAsmParser::parseZcmpStackAdj(OperandVector &Operands,
bool ExpectNegative) {
SMLoc S = getLoc();
bool Negative = parseOptionalToken(AsmToken::Minus);
if (getTok().isNot(AsmToken::Integer))
return ParseStatus::NoMatch;
int64_t StackAdjustment = getTok().getIntVal();
auto *RegListOp = static_cast<RISCVOperand *>(Operands.back().get());
if (!RegListOp->isRegList())
return ParseStatus::NoMatch;
unsigned RlistEncode = RegListOp->RegList.Encoding;
assert(RlistEncode != RISCVZC::INVALID_RLIST);
unsigned StackAdjBase = RISCVZC::getStackAdjBase(RlistEncode, isRV64());
if (Negative != ExpectNegative || StackAdjustment % 16 != 0 ||
StackAdjustment < StackAdjBase || (StackAdjustment - StackAdjBase) > 48) {
int64_t Lower = StackAdjBase;
int64_t Upper = StackAdjBase + 48;
if (ExpectNegative) {
Lower = -Lower;
Upper = -Upper;
std::swap(Lower, Upper);
}
return generateImmOutOfRangeError(S, Lower, Upper,
"stack adjustment for register list must "
"be a multiple of 16 bytes in the range");
}
unsigned StackAdj = (StackAdjustment - StackAdjBase);
Operands.push_back(RISCVOperand::createStackAdj(StackAdj, S));
Lex();
return ParseStatus::Success;
}
/// Looks at a token type and creates the relevant operand from this
/// information, adding to Operands. If operand was parsed, returns false, else
/// true.
bool RISCVAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
// Check if the current operand has a custom associated parser, if so, try to
// custom parse the operand, or fallback to the general approach.
ParseStatus Result =
MatchOperandParserImpl(Operands, Mnemonic, /*ParseForAllFeatures=*/true);
if (Result.isSuccess())
return false;
if (Result.isFailure())
return true;
// Attempt to parse token as a register.
if (parseRegister(Operands, true).isSuccess())
return false;
// Attempt to parse token as an immediate
if (parseImmediate(Operands).isSuccess()) {
// Parse memory base register if present
if (getLexer().is(AsmToken::LParen))
return !parseMemOpBaseReg(Operands).isSuccess();
return false;
}
// Finally we have exhausted all options and must declare defeat.
Error(getLoc(), "unknown operand");
return true;
}
bool RISCVAsmParser::parseInstruction(ParseInstructionInfo &Info,
StringRef Name, SMLoc NameLoc,
OperandVector &Operands) {
// Apply mnemonic aliases because the destination mnemonic may have require
// custom operand parsing. The generic tblgen'erated code does this later, at
// the start of MatchInstructionImpl(), but that's too late for custom
// operand parsing.
const FeatureBitset &AvailableFeatures = getAvailableFeatures();
applyMnemonicAliases(Name, AvailableFeatures, 0);
// First operand is token for instruction
Operands.push_back(RISCVOperand::createToken(Name, NameLoc));
// If there are no more operands, then finish
if (getLexer().is(AsmToken::EndOfStatement)) {
getParser().Lex(); // Consume the EndOfStatement.
return false;
}
// Parse first operand
if (parseOperand(Operands, Name))
return true;
// Parse until end of statement, consuming commas between operands
while (parseOptionalToken(AsmToken::Comma)) {
// Parse next operand
if (parseOperand(Operands, Name))
return true;
}
if (getParser().parseEOL("unexpected token")) {
getParser().eatToEndOfStatement();
return true;
}
return false;
}
bool RISCVAsmParser::classifySymbolRef(const MCExpr *Expr,
RISCV::Specifier &Kind) {
Kind = RISCV::S_None;
if (const auto *RE = dyn_cast<MCSpecifierExpr>(Expr)) {
Kind = RE->getSpecifier();
Expr = RE->getSubExpr();
}
MCValue Res;
if (Expr->evaluateAsRelocatable(Res, nullptr))
return Res.getSpecifier() == RISCV::S_None;
return false;
}
bool RISCVAsmParser::isSymbolDiff(const MCExpr *Expr) {
MCValue Res;
if (Expr->evaluateAsRelocatable(Res, nullptr)) {
return Res.getSpecifier() == RISCV::S_None && Res.getAddSym() &&
Res.getSubSym();
}
return false;
}
ParseStatus RISCVAsmParser::parseDirective(AsmToken DirectiveID) {
StringRef IDVal = DirectiveID.getString();
if (IDVal == ".option")
return parseDirectiveOption();
if (IDVal == ".attribute")
return parseDirectiveAttribute();
if (IDVal == ".insn")
return parseDirectiveInsn(DirectiveID.getLoc());
if (IDVal == ".variant_cc")
return parseDirectiveVariantCC();
return ParseStatus::NoMatch;
}
bool RISCVAsmParser::resetToArch(StringRef Arch, SMLoc Loc, std::string &Result,
bool FromOptionDirective) {
for (auto &Feature : RISCVFeatureKV)
if (llvm::RISCVISAInfo::isSupportedExtensionFeature(Feature.Key))
clearFeatureBits(Feature.Value, Feature.Key);
auto ParseResult = llvm::RISCVISAInfo::parseArchString(
Arch, /*EnableExperimentalExtension=*/true,
/*ExperimentalExtensionVersionCheck=*/true);
if (!ParseResult) {
std::string Buffer;
raw_string_ostream OutputErrMsg(Buffer);
handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
OutputErrMsg << "invalid arch name '" << Arch << "', "
<< ErrMsg.getMessage();
});
return Error(Loc, OutputErrMsg.str());
}
auto &ISAInfo = *ParseResult;
for (auto &Feature : RISCVFeatureKV)
if (ISAInfo->hasExtension(Feature.Key))
setFeatureBits(Feature.Value, Feature.Key);
if (FromOptionDirective) {
if (ISAInfo->getXLen() == 32 && isRV64())
return Error(Loc, "bad arch string switching from rv64 to rv32");
else if (ISAInfo->getXLen() == 64 && !isRV64())
return Error(Loc, "bad arch string switching from rv32 to rv64");
}
if (ISAInfo->getXLen() == 32)
clearFeatureBits(RISCV::Feature64Bit, "64bit");
else if (ISAInfo->getXLen() == 64)
setFeatureBits(RISCV::Feature64Bit, "64bit");
else
return Error(Loc, "bad arch string " + Arch);
Result = ISAInfo->toString();
return false;
}
bool RISCVAsmParser::parseDirectiveOption() {
MCAsmParser &Parser = getParser();
// Get the option token.
AsmToken Tok = Parser.getTok();
// At the moment only identifiers are supported.
if (parseToken(AsmToken::Identifier, "expected identifier"))
return true;
StringRef Option = Tok.getIdentifier();
if (Option == "push") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionPush();
pushFeatureBits();
return false;
}
if (Option == "pop") {
SMLoc StartLoc = Parser.getTok().getLoc();
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionPop();
if (popFeatureBits())
return Error(StartLoc, ".option pop with no .option push");
return false;
}
if (Option == "arch") {
SmallVector<RISCVOptionArchArg> Args;
do {
if (Parser.parseComma())
return true;
RISCVOptionArchArgType Type;
if (parseOptionalToken(AsmToken::Plus))
Type = RISCVOptionArchArgType::Plus;
else if (parseOptionalToken(AsmToken::Minus))
Type = RISCVOptionArchArgType::Minus;
else if (!Args.empty())
return Error(Parser.getTok().getLoc(),
"unexpected token, expected + or -");
else
Type = RISCVOptionArchArgType::Full;
if (Parser.getTok().isNot(AsmToken::Identifier))
return Error(Parser.getTok().getLoc(),
"unexpected token, expected identifier");
StringRef Arch = Parser.getTok().getString();
SMLoc Loc = Parser.getTok().getLoc();
Parser.Lex();
if (Type == RISCVOptionArchArgType::Full) {
std::string Result;
if (resetToArch(Arch, Loc, Result, true))
return true;
Args.emplace_back(Type, Result);
break;
}
if (isDigit(Arch.back()))
return Error(
Loc, "extension version number parsing not currently implemented");
std::string Feature = RISCVISAInfo::getTargetFeatureForExtension(Arch);
if (!enableExperimentalExtension() &&
StringRef(Feature).starts_with("experimental-"))
return Error(Loc, "unexpected experimental extensions");
auto Ext = llvm::lower_bound(RISCVFeatureKV, Feature);
if (Ext == std::end(RISCVFeatureKV) || StringRef(Ext->Key) != Feature)
return Error(Loc, "unknown extension feature");
Args.emplace_back(Type, Arch.str());
if (Type == RISCVOptionArchArgType::Plus) {
FeatureBitset OldFeatureBits = STI->getFeatureBits();
setFeatureBits(Ext->Value, Ext->Key);
auto ParseResult = RISCVFeatures::parseFeatureBits(isRV64(), STI->getFeatureBits());
if (!ParseResult) {
copySTI().setFeatureBits(OldFeatureBits);
setAvailableFeatures(ComputeAvailableFeatures(OldFeatureBits));
std::string Buffer;
raw_string_ostream OutputErrMsg(Buffer);
handleAllErrors(ParseResult.takeError(), [&](llvm::StringError &ErrMsg) {
OutputErrMsg << ErrMsg.getMessage();
});
return Error(Loc, OutputErrMsg.str());
}
} else {
assert(Type == RISCVOptionArchArgType::Minus);
// It is invalid to disable an extension that there are other enabled
// extensions depend on it.
// TODO: Make use of RISCVISAInfo to handle this
for (auto &Feature : RISCVFeatureKV) {
if (getSTI().hasFeature(Feature.Value) &&
Feature.Implies.test(Ext->Value))
return Error(Loc, Twine("can't disable ") + Ext->Key +
" extension; " + Feature.Key +
" extension requires " + Ext->Key +
" extension");
}
clearFeatureBits(Ext->Value, Ext->Key);
}
} while (Parser.getTok().isNot(AsmToken::EndOfStatement));
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionArch(Args);
return false;
}
if (Option == "exact") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionExact();
setFeatureBits(RISCV::FeatureExactAssembly, "exact-asm");
clearFeatureBits(RISCV::FeatureRelax, "relax");
return false;
}
if (Option == "noexact") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionNoExact();
clearFeatureBits(RISCV::FeatureExactAssembly, "exact-asm");
setFeatureBits(RISCV::FeatureRelax, "relax");
return false;
}
if (Option == "rvc") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionRVC();
setFeatureBits(RISCV::FeatureStdExtC, "c");
return false;
}
if (Option == "norvc") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionNoRVC();
clearFeatureBits(RISCV::FeatureStdExtC, "c");
clearFeatureBits(RISCV::FeatureStdExtZca, "zca");
return false;
}
if (Option == "pic") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionPIC();
ParserOptions.IsPicEnabled = true;
return false;
}
if (Option == "nopic") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionNoPIC();
ParserOptions.IsPicEnabled = false;
return false;
}
if (Option == "relax") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionRelax();
setFeatureBits(RISCV::FeatureRelax, "relax");
return false;
}
if (Option == "norelax") {
if (Parser.parseEOL())
return true;
getTargetStreamer().emitDirectiveOptionNoRelax();
clearFeatureBits(RISCV::FeatureRelax, "relax");
return false;
}
// Unknown option.
Warning(Parser.getTok().getLoc(),
"unknown option, expected 'push', 'pop', "
"'rvc', 'norvc', 'arch', 'relax', 'norelax', "
"'exact', or 'noexact'");
Parser.eatToEndOfStatement();
return false;
}
/// parseDirectiveAttribute
/// ::= .attribute expression ',' ( expression | "string" )
/// ::= .attribute identifier ',' ( expression | "string" )
bool RISCVAsmParser::parseDirectiveAttribute() {
MCAsmParser &Parser = getParser();
int64_t Tag;
SMLoc TagLoc;
TagLoc = Parser.getTok().getLoc();
if (Parser.getTok().is(AsmToken::Identifier)) {
StringRef Name = Parser.getTok().getIdentifier();
std::optional<unsigned> Ret =
ELFAttrs::attrTypeFromString(Name, RISCVAttrs::getRISCVAttributeTags());
if (!Ret)
return Error(TagLoc, "attribute name not recognised: " + Name);
Tag = *Ret;
Parser.Lex();
} else {
const MCExpr *AttrExpr;
TagLoc = Parser.getTok().getLoc();
if (Parser.parseExpression(AttrExpr))
return true;
const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
if (check(!CE, TagLoc, "expected numeric constant"))
return true;
Tag = CE->getValue();
}
if (Parser.parseComma())
return true;
StringRef StringValue;
int64_t IntegerValue = 0;
bool IsIntegerValue = true;
// RISC-V attributes have a string value if the tag number is odd
// and an integer value if the tag number is even.
if (Tag % 2)
IsIntegerValue = false;
SMLoc ValueExprLoc = Parser.getTok().getLoc();
if (IsIntegerValue) {
const MCExpr *ValueExpr;
if (Parser.parseExpression(ValueExpr))
return true;
const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
if (!CE)
return Error(ValueExprLoc, "expected numeric constant");
IntegerValue = CE->getValue();
} else {
if (Parser.getTok().isNot(AsmToken::String))
return Error(Parser.getTok().getLoc(), "expected string constant");
StringValue = Parser.getTok().getStringContents();
Parser.Lex();
}
if (Parser.parseEOL())
return true;
if (IsIntegerValue)
getTargetStreamer().emitAttribute(Tag, IntegerValue);
else if (Tag != RISCVAttrs::ARCH)
getTargetStreamer().emitTextAttribute(Tag, StringValue);
else {
std::string Result;
if (resetToArch(StringValue, ValueExprLoc, Result, false))
return true;
// Then emit the arch string.
getTargetStreamer().emitTextAttribute(Tag, Result);
}
return false;
}
bool isValidInsnFormat(StringRef Format, const MCSubtargetInfo &STI) {
return StringSwitch<bool>(Format)
.Cases("r", "r4", "i", "b", "sb", "u", "j", "uj", "s", true)
.Cases("cr", "ci", "ciw", "css", "cl", "cs", "ca", "cb", "cj",
STI.hasFeature(RISCV::FeatureStdExtZca))
.Cases("qc.eai", "qc.ei", "qc.eb", "qc.ej", "qc.es",
!STI.hasFeature(RISCV::Feature64Bit))
.Default(false);
}
/// parseDirectiveInsn
/// ::= .insn [ format encoding, (operands (, operands)*) ]
/// ::= .insn [ length, value ]
/// ::= .insn [ value ]
bool RISCVAsmParser::parseDirectiveInsn(SMLoc L) {
MCAsmParser &Parser = getParser();
// Expect instruction format as identifier.
StringRef Format;
SMLoc ErrorLoc = Parser.getTok().getLoc();
if (Parser.parseIdentifier(Format)) {
// Try parsing .insn [ length , ] value
std::optional<int64_t> Length;
int64_t Value = 0;
if (Parser.parseAbsoluteExpression(Value))
return true;
if (Parser.parseOptionalToken(AsmToken::Comma)) {
Length = Value;
if (Parser.parseAbsoluteExpression(Value))
return true;
if (*Length == 0 || (*Length % 2) != 0)
return Error(ErrorLoc,
"instruction lengths must be a non-zero multiple of two");
// TODO: Support Instructions > 64 bits.
if (*Length > 8)
return Error(ErrorLoc,
"instruction lengths over 64 bits are not supported");
}
// We only derive a length from the encoding for 16- and 32-bit
// instructions, as the encodings for longer instructions are not frozen in
// the spec.
int64_t EncodingDerivedLength = ((Value & 0b11) == 0b11) ? 4 : 2;
if (Length) {
// Only check the length against the encoding if the length is present and
// could match
if ((*Length <= 4) && (*Length != EncodingDerivedLength))
return Error(ErrorLoc,
"instruction length does not match the encoding");
if (!isUIntN(*Length * 8, Value))
return Error(ErrorLoc, "encoding value does not fit into instruction");
} else {
if (!isUIntN(EncodingDerivedLength * 8, Value))
return Error(ErrorLoc, "encoding value does not fit into instruction");
}
if (!getSTI().hasFeature(RISCV::FeatureStdExtZca) &&
(EncodingDerivedLength == 2))
return Error(ErrorLoc, "compressed instructions are not allowed");
if (getParser().parseEOL("invalid operand for instruction")) {
getParser().eatToEndOfStatement();
return true;
}
unsigned Opcode;
if (Length) {
switch (*Length) {
case 2:
Opcode = RISCV::Insn16;
break;
case 4:
Opcode = RISCV::Insn32;
break;
case 6:
Opcode = RISCV::Insn48;
break;
case 8:
Opcode = RISCV::Insn64;
break;
default:
llvm_unreachable("Error should have already been emitted");
}
} else
Opcode = (EncodingDerivedLength == 2) ? RISCV::Insn16 : RISCV::Insn32;
emitToStreamer(getStreamer(), MCInstBuilder(Opcode).addImm(Value));
return false;
}
if (!isValidInsnFormat(Format, getSTI()))
return Error(ErrorLoc, "invalid instruction format");
std::string FormatName = (".insn_" + Format).str();
ParseInstructionInfo Info;
SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> Operands;
if (parseInstruction(Info, FormatName, L, Operands))
return true;
unsigned Opcode;
uint64_t ErrorInfo;
return matchAndEmitInstruction(L, Opcode, Operands, Parser.getStreamer(),
ErrorInfo,
/*MatchingInlineAsm=*/false);
}
/// parseDirectiveVariantCC
/// ::= .variant_cc symbol
bool RISCVAsmParser::parseDirectiveVariantCC() {
StringRef Name;
if (getParser().parseIdentifier(Name))
return TokError("expected symbol name");
if (parseEOL())
return true;
getTargetStreamer().emitDirectiveVariantCC(
*getContext().getOrCreateSymbol(Name));
return false;
}
void RISCVAsmParser::emitToStreamer(MCStreamer &S, const MCInst &Inst) {
MCInst CInst;
bool Res = false;
const MCSubtargetInfo &STI = getSTI();
if (!STI.hasFeature(RISCV::FeatureExactAssembly))
Res = RISCVRVC::compress(CInst, Inst, STI);
if (Res)
++RISCVNumInstrsCompressed;
S.emitInstruction((Res ? CInst : Inst), STI);
}
void RISCVAsmParser::emitLoadImm(MCRegister DestReg, int64_t Value,
MCStreamer &Out) {
SmallVector<MCInst, 8> Seq;
RISCVMatInt::generateMCInstSeq(Value, getSTI(), DestReg, Seq);
for (MCInst &Inst : Seq) {
emitToStreamer(Out, Inst);
}
}
void RISCVAsmParser::emitAuipcInstPair(MCRegister DestReg, MCRegister TmpReg,
const MCExpr *Symbol,
RISCV::Specifier VKHi,
unsigned SecondOpcode, SMLoc IDLoc,
MCStreamer &Out) {
// A pair of instructions for PC-relative addressing; expands to
// TmpLabel: AUIPC TmpReg, VKHi(symbol)
// OP DestReg, TmpReg, %pcrel_lo(TmpLabel)
MCContext &Ctx = getContext();
MCSymbol *TmpLabel = Ctx.createNamedTempSymbol("pcrel_hi");
Out.emitLabel(TmpLabel);
const auto *SymbolHi = MCSpecifierExpr::create(Symbol, VKHi, Ctx);
emitToStreamer(Out,
MCInstBuilder(RISCV::AUIPC).addReg(TmpReg).addExpr(SymbolHi));
const MCExpr *RefToLinkTmpLabel = MCSpecifierExpr::create(
MCSymbolRefExpr::create(TmpLabel, Ctx), RISCV::S_PCREL_LO, Ctx);
emitToStreamer(Out, MCInstBuilder(SecondOpcode)
.addReg(DestReg)
.addReg(TmpReg)
.addExpr(RefToLinkTmpLabel));
}
void RISCVAsmParser::emitLoadLocalAddress(MCInst &Inst, SMLoc IDLoc,
MCStreamer &Out) {
// The load local address pseudo-instruction "lla" is used in PC-relative
// addressing of local symbols:
// lla rdest, symbol
// expands to
// TmpLabel: AUIPC rdest, %pcrel_hi(symbol)
// ADDI rdest, rdest, %pcrel_lo(TmpLabel)
MCRegister DestReg = Inst.getOperand(0).getReg();
const MCExpr *Symbol = Inst.getOperand(1).getExpr();
emitAuipcInstPair(DestReg, DestReg, Symbol, ELF::R_RISCV_PCREL_HI20,
RISCV::ADDI, IDLoc, Out);
}
void RISCVAsmParser::emitLoadGlobalAddress(MCInst &Inst, SMLoc IDLoc,
MCStreamer &Out) {
// The load global address pseudo-instruction "lga" is used in GOT-indirect
// addressing of global symbols:
// lga rdest, symbol
// expands to
// TmpLabel: AUIPC rdest, %got_pcrel_hi(symbol)
// Lx rdest, %pcrel_lo(TmpLabel)(rdest)
MCRegister DestReg = Inst.getOperand(0).getReg();
const MCExpr *Symbol = Inst.getOperand(1).getExpr();
unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
emitAuipcInstPair(DestReg, DestReg, Symbol, ELF::R_RISCV_GOT_HI20,
SecondOpcode, IDLoc, Out);
}
void RISCVAsmParser::emitLoadAddress(MCInst &Inst, SMLoc IDLoc,
MCStreamer &Out) {
// The load address pseudo-instruction "la" is used in PC-relative and
// GOT-indirect addressing of global symbols:
// la rdest, symbol
// is an alias for either (for non-PIC)
// lla rdest, symbol
// or (for PIC)
// lga rdest, symbol
if (ParserOptions.IsPicEnabled)
emitLoadGlobalAddress(Inst, IDLoc, Out);
else
emitLoadLocalAddress(Inst, IDLoc, Out);
}
void RISCVAsmParser::emitLoadTLSIEAddress(MCInst &Inst, SMLoc IDLoc,
MCStreamer &Out) {
// The load TLS IE address pseudo-instruction "la.tls.ie" is used in
// initial-exec TLS model addressing of global symbols:
// la.tls.ie rdest, symbol
// expands to
// TmpLabel: AUIPC rdest, %tls_ie_pcrel_hi(symbol)
// Lx rdest, %pcrel_lo(TmpLabel)(rdest)
MCRegister DestReg = Inst.getOperand(0).getReg();
const MCExpr *Symbol = Inst.getOperand(1).getExpr();
unsigned SecondOpcode = isRV64() ? RISCV::LD : RISCV::LW;
emitAuipcInstPair(DestReg, DestReg, Symbol, ELF::R_RISCV_TLS_GOT_HI20,
SecondOpcode, IDLoc, Out);
}
void RISCVAsmParser::emitLoadTLSGDAddress(MCInst &Inst, SMLoc IDLoc,
MCStreamer &Out) {
// The load TLS GD address pseudo-instruction "la.tls.gd" is used in
// global-dynamic TLS model addressing of global symbols:
// la.tls.gd rdest, symbol
// expands to
// TmpLabel: AUIPC rdest, %tls_gd_pcrel_hi(symbol)
// ADDI rdest, rdest, %pcrel_lo(TmpLabel)
MCRegister DestReg = Inst.getOperand(0).getReg();
const MCExpr *Symbol = Inst.getOperand(1).getExpr();
emitAuipcInstPair(DestReg, DestReg, Symbol, ELF::R_RISCV_TLS_GD_HI20,
RISCV::ADDI, IDLoc, Out);
}
void RISCVAsmParser::emitLoadStoreSymbol(MCInst &Inst, unsigned Opcode,
SMLoc IDLoc, MCStreamer &Out,
bool HasTmpReg) {
// The load/store pseudo-instruction does a pc-relative load with
// a symbol.
//
// The expansion looks like this
//
// TmpLabel: AUIPC tmp, %pcrel_hi(symbol)
// [S|L]X rd, %pcrel_lo(TmpLabel)(tmp)
unsigned DestRegOpIdx = HasTmpReg ? 1 : 0;
MCRegister DestReg = Inst.getOperand(DestRegOpIdx).getReg();
unsigned SymbolOpIdx = HasTmpReg ? 2 : 1;
MCRegister TmpReg = Inst.getOperand(0).getReg();
// If TmpReg is a GPR pair, get the even register.
if (RISCVMCRegisterClasses[RISCV::GPRPairRegClassID].contains(TmpReg)) {
const MCRegisterInfo *RI = getContext().getRegisterInfo();
TmpReg = RI->getSubReg(TmpReg, RISCV::sub_gpr_even);
}
const MCExpr *Symbol = Inst.getOperand(SymbolOpIdx).getExpr();
emitAuipcInstPair(DestReg, TmpReg, Symbol, ELF::R_RISCV_PCREL_HI20, Opcode,
IDLoc, Out);
}
void RISCVAsmParser::emitPseudoExtend(MCInst &Inst, bool SignExtend,
int64_t Width, SMLoc IDLoc,
MCStreamer &Out) {
// The sign/zero extend pseudo-instruction does two shifts, with the shift
// amounts dependent on the XLEN.
//
// The expansion looks like this
//
// SLLI rd, rs, XLEN - Width
// SR[A|R]I rd, rd, XLEN - Width
const MCOperand &DestReg = Inst.getOperand(0);
const MCOperand &SourceReg = Inst.getOperand(1);
unsigned SecondOpcode = SignExtend ? RISCV::SRAI : RISCV::SRLI;
int64_t ShAmt = (isRV64() ? 64 : 32) - Width;
assert(ShAmt > 0 && "Shift amount must be non-zero.");
emitToStreamer(Out, MCInstBuilder(RISCV::SLLI)
.addOperand(DestReg)
.addOperand(SourceReg)
.addImm(ShAmt));
emitToStreamer(Out, MCInstBuilder(SecondOpcode)
.addOperand(DestReg)
.addOperand(DestReg)
.addImm(ShAmt));
}
void RISCVAsmParser::emitVMSGE(MCInst &Inst, unsigned Opcode, SMLoc IDLoc,
MCStreamer &Out) {
if (Inst.getNumOperands() == 3) {
// unmasked va >= x
//
// pseudoinstruction: vmsge{u}.vx vd, va, x
// expansion: vmslt{u}.vx vd, va, x; vmnand.mm vd, vd, vd
emitToStreamer(Out, MCInstBuilder(Opcode)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(1))
.addOperand(Inst.getOperand(2))
.addReg(MCRegister())
.setLoc(IDLoc));
emitToStreamer(Out, MCInstBuilder(RISCV::VMNAND_MM)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(0))
.setLoc(IDLoc));
} else if (Inst.getNumOperands() == 4) {
// masked va >= x, vd != v0
//
// pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t
// expansion: vmslt{u}.vx vd, va, x, v0.t; vmxor.mm vd, vd, v0
assert(Inst.getOperand(0).getReg() != RISCV::V0 &&
"The destination register should not be V0.");
emitToStreamer(Out, MCInstBuilder(Opcode)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(1))
.addOperand(Inst.getOperand(2))
.addOperand(Inst.getOperand(3))
.setLoc(IDLoc));
emitToStreamer(Out, MCInstBuilder(RISCV::VMXOR_MM)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(0))
.addReg(RISCV::V0)
.setLoc(IDLoc));
} else if (Inst.getNumOperands() == 5 &&
Inst.getOperand(0).getReg() == RISCV::V0) {
// masked va >= x, vd == v0
//
// pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
// expansion: vmslt{u}.vx vt, va, x; vmandn.mm vd, vd, vt
assert(Inst.getOperand(0).getReg() == RISCV::V0 &&
"The destination register should be V0.");
assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
"The temporary vector register should not be V0.");
emitToStreamer(Out, MCInstBuilder(Opcode)
.addOperand(Inst.getOperand(1))
.addOperand(Inst.getOperand(2))
.addOperand(Inst.getOperand(3))
.addReg(MCRegister())
.setLoc(IDLoc));
emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(1))
.setLoc(IDLoc));
} else if (Inst.getNumOperands() == 5) {
// masked va >= x, any vd
//
// pseudoinstruction: vmsge{u}.vx vd, va, x, v0.t, vt
// expansion: vmslt{u}.vx vt, va, x; vmandn.mm vt, v0, vt;
// vmandn.mm vd, vd, v0; vmor.mm vd, vt, vd
assert(Inst.getOperand(1).getReg() != RISCV::V0 &&
"The temporary vector register should not be V0.");
emitToStreamer(Out, MCInstBuilder(Opcode)
.addOperand(Inst.getOperand(1))
.addOperand(Inst.getOperand(2))
.addOperand(Inst.getOperand(3))
.addReg(MCRegister())
.setLoc(IDLoc));
emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
.addOperand(Inst.getOperand(1))
.addReg(RISCV::V0)
.addOperand(Inst.getOperand(1))
.setLoc(IDLoc));
emitToStreamer(Out, MCInstBuilder(RISCV::VMANDN_MM)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(0))
.addReg(RISCV::V0)
.setLoc(IDLoc));
emitToStreamer(Out, MCInstBuilder(RISCV::VMOR_MM)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(1))
.addOperand(Inst.getOperand(0))
.setLoc(IDLoc));
}
}
bool RISCVAsmParser::checkPseudoAddTPRel(MCInst &Inst,
OperandVector &Operands) {
assert(Inst.getOpcode() == RISCV::PseudoAddTPRel && "Invalid instruction");
assert(Inst.getOperand(2).isReg() && "Unexpected second operand kind");
if (Inst.getOperand(2).getReg() != RISCV::X4) {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
return Error(ErrorLoc, "the second input operand must be tp/x4 when using "
"%tprel_add specifier");
}
return false;
}
bool RISCVAsmParser::checkPseudoTLSDESCCall(MCInst &Inst,
OperandVector &Operands) {
assert(Inst.getOpcode() == RISCV::PseudoTLSDESCCall && "Invalid instruction");
assert(Inst.getOperand(0).isReg() && "Unexpected operand kind");
if (Inst.getOperand(0).getReg() != RISCV::X5) {
SMLoc ErrorLoc = ((RISCVOperand &)*Operands[3]).getStartLoc();
return Error(ErrorLoc, "the output operand must be t0/x5 when using "
"%tlsdesc_call specifier");
}
return false;
}
std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultMaskRegOp() const {
return RISCVOperand::createReg(MCRegister(), llvm::SMLoc(), llvm::SMLoc());
}
std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgOp() const {
return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::DYN,
llvm::SMLoc());
}
std::unique_ptr<RISCVOperand> RISCVAsmParser::defaultFRMArgLegacyOp() const {
return RISCVOperand::createFRMArg(RISCVFPRndMode::RoundingMode::RNE,
llvm::SMLoc());
}
bool RISCVAsmParser::validateInstruction(MCInst &Inst,
OperandVector &Operands) {
unsigned Opcode = Inst.getOpcode();
if (Opcode == RISCV::PseudoVMSGEU_VX_M_T ||
Opcode == RISCV::PseudoVMSGE_VX_M_T) {
MCRegister DestReg = Inst.getOperand(0).getReg();
MCRegister TempReg = Inst.getOperand(1).getReg();
if (DestReg == TempReg) {
SMLoc Loc = Operands.back()->getStartLoc();
return Error(Loc, "the temporary vector register cannot be the same as "
"the destination register");
}
}
if (Opcode == RISCV::TH_LDD || Opcode == RISCV::TH_LWUD ||
Opcode == RISCV::TH_LWD) {
MCRegister Rd1 = Inst.getOperand(0).getReg();
MCRegister Rd2 = Inst.getOperand(1).getReg();
MCRegister Rs1 = Inst.getOperand(2).getReg();
// The encoding with rd1 == rd2 == rs1 is reserved for XTHead load pair.
if (Rs1 == Rd1 || Rs1 == Rd2 || Rd1 == Rd2) {
SMLoc Loc = Operands[1]->getStartLoc();
return Error(Loc, "rs1, rd1, and rd2 cannot overlap");
}
}
if (Opcode == RISCV::CM_MVSA01 || Opcode == RISCV::QC_CM_MVSA01) {
MCRegister Rd1 = Inst.getOperand(0).getReg();
MCRegister Rd2 = Inst.getOperand(1).getReg();
if (Rd1 == Rd2) {
SMLoc Loc = Operands[1]->getStartLoc();
return Error(Loc, "rs1 and rs2 must be different");
}
}
const MCInstrDesc &MCID = MII.get(Opcode);
if (!(MCID.TSFlags & RISCVII::ConstraintMask))
return false;
if (Opcode == RISCV::SF_VC_V_XVW || Opcode == RISCV::SF_VC_V_IVW ||
Opcode == RISCV::SF_VC_V_FVW || Opcode == RISCV::SF_VC_V_VVW) {
// Operands Opcode, Dst, uimm, Dst, Rs2, Rs1 for SF_VC_V_XVW.
MCRegister VCIXDst = Inst.getOperand(0).getReg();
SMLoc VCIXDstLoc = Operands[2]->getStartLoc();
if (MCID.TSFlags & RISCVII::VS1Constraint) {
MCRegister VCIXRs1 = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
if (VCIXDst == VCIXRs1)
return Error(VCIXDstLoc, "the destination vector register group cannot"
" overlap the source vector register group");
}
if (MCID.TSFlags & RISCVII::VS2Constraint) {
MCRegister VCIXRs2 = Inst.getOperand(Inst.getNumOperands() - 2).getReg();
if (VCIXDst == VCIXRs2)
return Error(VCIXDstLoc, "the destination vector register group cannot"
" overlap the source vector register group");
}
return false;
}
MCRegister DestReg = Inst.getOperand(0).getReg();
unsigned Offset = 0;
int TiedOp = MCID.getOperandConstraint(1, MCOI::TIED_TO);
if (TiedOp == 0)
Offset = 1;
// Operands[1] will be the first operand, DestReg.
SMLoc Loc = Operands[1]->getStartLoc();
if (MCID.TSFlags & RISCVII::VS2Constraint) {
MCRegister CheckReg = Inst.getOperand(Offset + 1).getReg();
if (DestReg == CheckReg)
return Error(Loc, "the destination vector register group cannot overlap"
" the source vector register group");
}
if ((MCID.TSFlags & RISCVII::VS1Constraint) && Inst.getOperand(Offset + 2).isReg()) {
MCRegister CheckReg = Inst.getOperand(Offset + 2).getReg();
if (DestReg == CheckReg)
return Error(Loc, "the destination vector register group cannot overlap"
" the source vector register group");
}
if ((MCID.TSFlags & RISCVII::VMConstraint) && (DestReg == RISCV::V0)) {
// vadc, vsbc are special cases. These instructions have no mask register.
// The destination register could not be V0.
if (Opcode == RISCV::VADC_VVM || Opcode == RISCV::VADC_VXM ||
Opcode == RISCV::VADC_VIM || Opcode == RISCV::VSBC_VVM ||
Opcode == RISCV::VSBC_VXM || Opcode == RISCV::VFMERGE_VFM ||
Opcode == RISCV::VMERGE_VIM || Opcode == RISCV::VMERGE_VVM ||
Opcode == RISCV::VMERGE_VXM)
return Error(Loc, "the destination vector register group cannot be V0");
// Regardless masked or unmasked version, the number of operands is the
// same. For example, "viota.m v0, v2" is "viota.m v0, v2, NoRegister"
// actually. We need to check the last operand to ensure whether it is
// masked or not.
MCRegister CheckReg = Inst.getOperand(Inst.getNumOperands() - 1).getReg();
assert((CheckReg == RISCV::V0 || !CheckReg) &&
"Unexpected register for mask operand");
if (DestReg == CheckReg)
return Error(Loc, "the destination vector register group cannot overlap"
" the mask register");
}
return false;
}
bool RISCVAsmParser::processInstruction(MCInst &Inst, SMLoc IDLoc,
OperandVector &Operands,
MCStreamer &Out) {
Inst.setLoc(IDLoc);
switch (Inst.getOpcode()) {
default:
break;
case RISCV::PseudoC_ADDI_NOP:
emitToStreamer(Out, MCInstBuilder(RISCV::C_NOP));
return false;
case RISCV::PseudoLLAImm:
case RISCV::PseudoLAImm:
case RISCV::PseudoLI: {
MCRegister Reg = Inst.getOperand(0).getReg();
const MCOperand &Op1 = Inst.getOperand(1);
if (Op1.isExpr()) {
// We must have li reg, %lo(sym) or li reg, %pcrel_lo(sym) or similar.
// Just convert to an addi. This allows compatibility with gas.
emitToStreamer(Out, MCInstBuilder(RISCV::ADDI)
.addReg(Reg)
.addReg(RISCV::X0)
.addExpr(Op1.getExpr()));
return false;
}
int64_t Imm = Inst.getOperand(1).getImm();
// On RV32 the immediate here can either be a signed or an unsigned
// 32-bit number. Sign extension has to be performed to ensure that Imm
// represents the expected signed 64-bit number.
if (!isRV64())
Imm = SignExtend64<32>(Imm);
emitLoadImm(Reg, Imm, Out);
return false;
}
case RISCV::PseudoLLA:
emitLoadLocalAddress(Inst, IDLoc, Out);
return false;
case RISCV::PseudoLGA:
emitLoadGlobalAddress(Inst, IDLoc, Out);
return false;
case RISCV::PseudoLA:
emitLoadAddress(Inst, IDLoc, Out);
return false;
case RISCV::PseudoLA_TLS_IE:
emitLoadTLSIEAddress(Inst, IDLoc, Out);
return false;
case RISCV::PseudoLA_TLS_GD:
emitLoadTLSGDAddress(Inst, IDLoc, Out);
return false;
case RISCV::PseudoLB:
case RISCV::PseudoQC_E_LB:
emitLoadStoreSymbol(Inst, RISCV::LB, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoLBU:
case RISCV::PseudoQC_E_LBU:
emitLoadStoreSymbol(Inst, RISCV::LBU, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoLH:
case RISCV::PseudoQC_E_LH:
emitLoadStoreSymbol(Inst, RISCV::LH, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoLHU:
case RISCV::PseudoQC_E_LHU:
emitLoadStoreSymbol(Inst, RISCV::LHU, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoLW:
case RISCV::PseudoQC_E_LW:
emitLoadStoreSymbol(Inst, RISCV::LW, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoLWU:
emitLoadStoreSymbol(Inst, RISCV::LWU, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoLD:
emitLoadStoreSymbol(Inst, RISCV::LD, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoLD_RV32:
emitLoadStoreSymbol(Inst, RISCV::LD_RV32, IDLoc, Out, /*HasTmpReg=*/false);
return false;
case RISCV::PseudoFLH:
emitLoadStoreSymbol(Inst, RISCV::FLH, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoFLW:
emitLoadStoreSymbol(Inst, RISCV::FLW, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoFLD:
emitLoadStoreSymbol(Inst, RISCV::FLD, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoFLQ:
emitLoadStoreSymbol(Inst, RISCV::FLQ, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoSB:
case RISCV::PseudoQC_E_SB:
emitLoadStoreSymbol(Inst, RISCV::SB, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoSH:
case RISCV::PseudoQC_E_SH:
emitLoadStoreSymbol(Inst, RISCV::SH, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoSW:
case RISCV::PseudoQC_E_SW:
emitLoadStoreSymbol(Inst, RISCV::SW, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoSD:
emitLoadStoreSymbol(Inst, RISCV::SD, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoSD_RV32:
emitLoadStoreSymbol(Inst, RISCV::SD_RV32, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoFSH:
emitLoadStoreSymbol(Inst, RISCV::FSH, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoFSW:
emitLoadStoreSymbol(Inst, RISCV::FSW, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoFSD:
emitLoadStoreSymbol(Inst, RISCV::FSD, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoFSQ:
emitLoadStoreSymbol(Inst, RISCV::FSQ, IDLoc, Out, /*HasTmpReg=*/true);
return false;
case RISCV::PseudoAddTPRel:
if (checkPseudoAddTPRel(Inst, Operands))
return true;
break;
case RISCV::PseudoTLSDESCCall:
if (checkPseudoTLSDESCCall(Inst, Operands))
return true;
break;
case RISCV::PseudoSEXT_B:
emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/8, IDLoc, Out);
return false;
case RISCV::PseudoSEXT_H:
emitPseudoExtend(Inst, /*SignExtend=*/true, /*Width=*/16, IDLoc, Out);
return false;
case RISCV::PseudoZEXT_H:
emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/16, IDLoc, Out);
return false;
case RISCV::PseudoZEXT_W:
emitPseudoExtend(Inst, /*SignExtend=*/false, /*Width=*/32, IDLoc, Out);
return false;
case RISCV::PseudoVMSGEU_VX:
case RISCV::PseudoVMSGEU_VX_M:
case RISCV::PseudoVMSGEU_VX_M_T:
emitVMSGE(Inst, RISCV::VMSLTU_VX, IDLoc, Out);
return false;
case RISCV::PseudoVMSGE_VX:
case RISCV::PseudoVMSGE_VX_M:
case RISCV::PseudoVMSGE_VX_M_T:
emitVMSGE(Inst, RISCV::VMSLT_VX, IDLoc, Out);
return false;
case RISCV::PseudoVMSGE_VI:
case RISCV::PseudoVMSLT_VI: {
// These instructions are signed and so is immediate so we can subtract one
// and change the opcode.
int64_t Imm = Inst.getOperand(2).getImm();
unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGE_VI ? RISCV::VMSGT_VI
: RISCV::VMSLE_VI;
emitToStreamer(Out, MCInstBuilder(Opc)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(1))
.addImm(Imm - 1)
.addOperand(Inst.getOperand(3))
.setLoc(IDLoc));
return false;
}
case RISCV::PseudoVMSGEU_VI:
case RISCV::PseudoVMSLTU_VI: {
int64_t Imm = Inst.getOperand(2).getImm();
// Unsigned comparisons are tricky because the immediate is signed. If the
// immediate is 0 we can't just subtract one. vmsltu.vi v0, v1, 0 is always
// false, but vmsle.vi v0, v1, -1 is always true. Instead we use
// vmsne v0, v1, v1 which is always false.
if (Imm == 0) {
unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
? RISCV::VMSEQ_VV
: RISCV::VMSNE_VV;
emitToStreamer(Out, MCInstBuilder(Opc)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(1))
.addOperand(Inst.getOperand(1))
.addOperand(Inst.getOperand(3))
.setLoc(IDLoc));
} else {
// Other immediate values can subtract one like signed.
unsigned Opc = Inst.getOpcode() == RISCV::PseudoVMSGEU_VI
? RISCV::VMSGTU_VI
: RISCV::VMSLEU_VI;
emitToStreamer(Out, MCInstBuilder(Opc)
.addOperand(Inst.getOperand(0))
.addOperand(Inst.getOperand(1))
.addImm(Imm - 1)
.addOperand(Inst.getOperand(3))
.setLoc(IDLoc));
}
return false;
}
}
emitToStreamer(Out, Inst);
return false;
}
extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
LLVMInitializeRISCVAsmParser() {
RegisterMCAsmParser<RISCVAsmParser> X(getTheRISCV32Target());
RegisterMCAsmParser<RISCVAsmParser> Y(getTheRISCV64Target());
}
|