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
| //===--- ParsePragma.cpp - Language specific pragma parsing ---------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the language specific #pragma handlers.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/Basic/PragmaKinds.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/LoopHint.h"
#include "clang/Parse/ParseDiagnostic.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/Scope.h"
#include "llvm/ADT/StringSwitch.h"
using namespace clang;
namespace {
struct PragmaAlignHandler : public PragmaHandler {
explicit PragmaAlignHandler() : PragmaHandler("align") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaGCCVisibilityHandler : public PragmaHandler {
explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaOptionsHandler : public PragmaHandler {
explicit PragmaOptionsHandler() : PragmaHandler("options") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaPackHandler : public PragmaHandler {
explicit PragmaPackHandler() : PragmaHandler("pack") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaClangSectionHandler : public PragmaHandler {
explicit PragmaClangSectionHandler(Sema &S)
: PragmaHandler("section"), Actions(S) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
private:
Sema &Actions;
};
struct PragmaMSStructHandler : public PragmaHandler {
explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaUnusedHandler : public PragmaHandler {
PragmaUnusedHandler() : PragmaHandler("unused") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaWeakHandler : public PragmaHandler {
explicit PragmaWeakHandler() : PragmaHandler("weak") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaRedefineExtnameHandler : public PragmaHandler {
explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaOpenCLExtensionHandler : public PragmaHandler {
PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaFPContractHandler : public PragmaHandler {
PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
// Pragma STDC implementations.
/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
tok::OnOffSwitch OOS;
if (PP.LexOnOffSwitch(OOS))
return;
if (OOS == tok::OOS_ON) {
PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
}
MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_fenv_access);
Toks[0].setLocation(Tok.getLocation());
Toks[0].setAnnotationEndLoc(Tok.getLocation());
Toks[0].setAnnotationValue(reinterpret_cast<void*>(
static_cast<uintptr_t>(OOS)));
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
};
/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
PragmaSTDC_CX_LIMITED_RANGEHandler() : PragmaHandler("CX_LIMITED_RANGE") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &Tok) override {
tok::OnOffSwitch OOS;
PP.LexOnOffSwitch(OOS);
}
};
/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
struct PragmaSTDC_UnknownHandler : public PragmaHandler {
PragmaSTDC_UnknownHandler() = default;
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &UnknownTok) override {
// C99 6.10.6p2, unknown forms are not allowed.
PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
}
};
struct PragmaFPHandler : public PragmaHandler {
PragmaFPHandler() : PragmaHandler("fp") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaNoOpenMPHandler : public PragmaHandler {
PragmaNoOpenMPHandler() : PragmaHandler("omp") { }
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaOpenMPHandler : public PragmaHandler {
PragmaOpenMPHandler() : PragmaHandler("omp") { }
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
/// PragmaCommentHandler - "\#pragma comment ...".
struct PragmaCommentHandler : public PragmaHandler {
PragmaCommentHandler(Sema &Actions)
: PragmaHandler("comment"), Actions(Actions) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
private:
Sema &Actions;
};
struct PragmaDetectMismatchHandler : public PragmaHandler {
PragmaDetectMismatchHandler(Sema &Actions)
: PragmaHandler("detect_mismatch"), Actions(Actions) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
private:
Sema &Actions;
};
struct PragmaMSPointersToMembers : public PragmaHandler {
explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaMSVtorDisp : public PragmaHandler {
explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaMSPragma : public PragmaHandler {
explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
/// PragmaOptimizeHandler - "\#pragma clang optimize on/off".
struct PragmaOptimizeHandler : public PragmaHandler {
PragmaOptimizeHandler(Sema &S)
: PragmaHandler("optimize"), Actions(S) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
private:
Sema &Actions;
};
struct PragmaLoopHintHandler : public PragmaHandler {
PragmaLoopHintHandler() : PragmaHandler("loop") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaUnrollHintHandler : public PragmaHandler {
PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaMSRuntimeChecksHandler : public EmptyPragmaHandler {
PragmaMSRuntimeChecksHandler() : EmptyPragmaHandler("runtime_checks") {}
};
struct PragmaMSIntrinsicHandler : public PragmaHandler {
PragmaMSIntrinsicHandler() : PragmaHandler("intrinsic") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaMSOptimizeHandler : public PragmaHandler {
PragmaMSOptimizeHandler() : PragmaHandler("optimize") {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
};
struct PragmaForceCUDAHostDeviceHandler : public PragmaHandler {
PragmaForceCUDAHostDeviceHandler(Sema &Actions)
: PragmaHandler("force_cuda_host_device"), Actions(Actions) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
private:
Sema &Actions;
};
/// PragmaAttributeHandler - "\#pragma clang attribute ...".
struct PragmaAttributeHandler : public PragmaHandler {
PragmaAttributeHandler(AttributeFactory &AttrFactory)
: PragmaHandler("attribute"), AttributesForPragmaAttribute(AttrFactory) {}
void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
Token &FirstToken) override;
/// A pool of attributes that were parsed in \#pragma clang attribute.
ParsedAttributes AttributesForPragmaAttribute;
};
} // end namespace
void Parser::initializePragmaHandlers() {
AlignHandler = std::make_unique<PragmaAlignHandler>();
PP.AddPragmaHandler(AlignHandler.get());
GCCVisibilityHandler = std::make_unique<PragmaGCCVisibilityHandler>();
PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
OptionsHandler = std::make_unique<PragmaOptionsHandler>();
PP.AddPragmaHandler(OptionsHandler.get());
PackHandler = std::make_unique<PragmaPackHandler>();
PP.AddPragmaHandler(PackHandler.get());
MSStructHandler = std::make_unique<PragmaMSStructHandler>();
PP.AddPragmaHandler(MSStructHandler.get());
UnusedHandler = std::make_unique<PragmaUnusedHandler>();
PP.AddPragmaHandler(UnusedHandler.get());
WeakHandler = std::make_unique<PragmaWeakHandler>();
PP.AddPragmaHandler(WeakHandler.get());
RedefineExtnameHandler = std::make_unique<PragmaRedefineExtnameHandler>();
PP.AddPragmaHandler(RedefineExtnameHandler.get());
FPContractHandler = std::make_unique<PragmaFPContractHandler>();
PP.AddPragmaHandler("STDC", FPContractHandler.get());
STDCFENVHandler = std::make_unique<PragmaSTDC_FENV_ACCESSHandler>();
PP.AddPragmaHandler("STDC", STDCFENVHandler.get());
STDCCXLIMITHandler = std::make_unique<PragmaSTDC_CX_LIMITED_RANGEHandler>();
PP.AddPragmaHandler("STDC", STDCCXLIMITHandler.get());
STDCUnknownHandler = std::make_unique<PragmaSTDC_UnknownHandler>();
PP.AddPragmaHandler("STDC", STDCUnknownHandler.get());
PCSectionHandler = std::make_unique<PragmaClangSectionHandler>(Actions);
PP.AddPragmaHandler("clang", PCSectionHandler.get());
if (getLangOpts().OpenCL) {
OpenCLExtensionHandler = std::make_unique<PragmaOpenCLExtensionHandler>();
PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
}
if (getLangOpts().OpenMP)
OpenMPHandler = std::make_unique<PragmaOpenMPHandler>();
else
OpenMPHandler = std::make_unique<PragmaNoOpenMPHandler>();
PP.AddPragmaHandler(OpenMPHandler.get());
if (getLangOpts().MicrosoftExt ||
getTargetInfo().getTriple().isOSBinFormatELF()) {
MSCommentHandler = std::make_unique<PragmaCommentHandler>(Actions);
PP.AddPragmaHandler(MSCommentHandler.get());
}
if (getLangOpts().MicrosoftExt) {
MSDetectMismatchHandler =
std::make_unique<PragmaDetectMismatchHandler>(Actions);
PP.AddPragmaHandler(MSDetectMismatchHandler.get());
MSPointersToMembers = std::make_unique<PragmaMSPointersToMembers>();
PP.AddPragmaHandler(MSPointersToMembers.get());
MSVtorDisp = std::make_unique<PragmaMSVtorDisp>();
PP.AddPragmaHandler(MSVtorDisp.get());
MSInitSeg = std::make_unique<PragmaMSPragma>("init_seg");
PP.AddPragmaHandler(MSInitSeg.get());
MSDataSeg = std::make_unique<PragmaMSPragma>("data_seg");
PP.AddPragmaHandler(MSDataSeg.get());
MSBSSSeg = std::make_unique<PragmaMSPragma>("bss_seg");
PP.AddPragmaHandler(MSBSSSeg.get());
MSConstSeg = std::make_unique<PragmaMSPragma>("const_seg");
PP.AddPragmaHandler(MSConstSeg.get());
MSCodeSeg = std::make_unique<PragmaMSPragma>("code_seg");
PP.AddPragmaHandler(MSCodeSeg.get());
MSSection = std::make_unique<PragmaMSPragma>("section");
PP.AddPragmaHandler(MSSection.get());
MSRuntimeChecks = std::make_unique<PragmaMSRuntimeChecksHandler>();
PP.AddPragmaHandler(MSRuntimeChecks.get());
MSIntrinsic = std::make_unique<PragmaMSIntrinsicHandler>();
PP.AddPragmaHandler(MSIntrinsic.get());
MSOptimize = std::make_unique<PragmaMSOptimizeHandler>();
PP.AddPragmaHandler(MSOptimize.get());
}
if (getLangOpts().CUDA) {
CUDAForceHostDeviceHandler =
std::make_unique<PragmaForceCUDAHostDeviceHandler>(Actions);
PP.AddPragmaHandler("clang", CUDAForceHostDeviceHandler.get());
}
OptimizeHandler = std::make_unique<PragmaOptimizeHandler>(Actions);
PP.AddPragmaHandler("clang", OptimizeHandler.get());
LoopHintHandler = std::make_unique<PragmaLoopHintHandler>();
PP.AddPragmaHandler("clang", LoopHintHandler.get());
UnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("unroll");
PP.AddPragmaHandler(UnrollHintHandler.get());
NoUnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("nounroll");
PP.AddPragmaHandler(NoUnrollHintHandler.get());
UnrollAndJamHintHandler =
std::make_unique<PragmaUnrollHintHandler>("unroll_and_jam");
PP.AddPragmaHandler(UnrollAndJamHintHandler.get());
NoUnrollAndJamHintHandler =
std::make_unique<PragmaUnrollHintHandler>("nounroll_and_jam");
PP.AddPragmaHandler(NoUnrollAndJamHintHandler.get());
FPHandler = std::make_unique<PragmaFPHandler>();
PP.AddPragmaHandler("clang", FPHandler.get());
AttributePragmaHandler =
std::make_unique<PragmaAttributeHandler>(AttrFactory);
PP.AddPragmaHandler("clang", AttributePragmaHandler.get());
}
void Parser::resetPragmaHandlers() {
// Remove the pragma handlers we installed.
PP.RemovePragmaHandler(AlignHandler.get());
AlignHandler.reset();
PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
GCCVisibilityHandler.reset();
PP.RemovePragmaHandler(OptionsHandler.get());
OptionsHandler.reset();
PP.RemovePragmaHandler(PackHandler.get());
PackHandler.reset();
PP.RemovePragmaHandler(MSStructHandler.get());
MSStructHandler.reset();
PP.RemovePragmaHandler(UnusedHandler.get());
UnusedHandler.reset();
PP.RemovePragmaHandler(WeakHandler.get());
WeakHandler.reset();
PP.RemovePragmaHandler(RedefineExtnameHandler.get());
RedefineExtnameHandler.reset();
if (getLangOpts().OpenCL) {
PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
OpenCLExtensionHandler.reset();
PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
}
PP.RemovePragmaHandler(OpenMPHandler.get());
OpenMPHandler.reset();
if (getLangOpts().MicrosoftExt ||
getTargetInfo().getTriple().isOSBinFormatELF()) {
PP.RemovePragmaHandler(MSCommentHandler.get());
MSCommentHandler.reset();
}
PP.RemovePragmaHandler("clang", PCSectionHandler.get());
PCSectionHandler.reset();
if (getLangOpts().MicrosoftExt) {
PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
MSDetectMismatchHandler.reset();
PP.RemovePragmaHandler(MSPointersToMembers.get());
MSPointersToMembers.reset();
PP.RemovePragmaHandler(MSVtorDisp.get());
MSVtorDisp.reset();
PP.RemovePragmaHandler(MSInitSeg.get());
MSInitSeg.reset();
PP.RemovePragmaHandler(MSDataSeg.get());
MSDataSeg.reset();
PP.RemovePragmaHandler(MSBSSSeg.get());
MSBSSSeg.reset();
PP.RemovePragmaHandler(MSConstSeg.get());
MSConstSeg.reset();
PP.RemovePragmaHandler(MSCodeSeg.get());
MSCodeSeg.reset();
PP.RemovePragmaHandler(MSSection.get());
MSSection.reset();
PP.RemovePragmaHandler(MSRuntimeChecks.get());
MSRuntimeChecks.reset();
PP.RemovePragmaHandler(MSIntrinsic.get());
MSIntrinsic.reset();
PP.RemovePragmaHandler(MSOptimize.get());
MSOptimize.reset();
}
if (getLangOpts().CUDA) {
PP.RemovePragmaHandler("clang", CUDAForceHostDeviceHandler.get());
CUDAForceHostDeviceHandler.reset();
}
PP.RemovePragmaHandler("STDC", FPContractHandler.get());
FPContractHandler.reset();
PP.RemovePragmaHandler("STDC", STDCFENVHandler.get());
STDCFENVHandler.reset();
PP.RemovePragmaHandler("STDC", STDCCXLIMITHandler.get());
STDCCXLIMITHandler.reset();
PP.RemovePragmaHandler("STDC", STDCUnknownHandler.get());
STDCUnknownHandler.reset();
PP.RemovePragmaHandler("clang", OptimizeHandler.get());
OptimizeHandler.reset();
PP.RemovePragmaHandler("clang", LoopHintHandler.get());
LoopHintHandler.reset();
PP.RemovePragmaHandler(UnrollHintHandler.get());
UnrollHintHandler.reset();
PP.RemovePragmaHandler(NoUnrollHintHandler.get());
NoUnrollHintHandler.reset();
PP.RemovePragmaHandler(UnrollAndJamHintHandler.get());
UnrollAndJamHintHandler.reset();
PP.RemovePragmaHandler(NoUnrollAndJamHintHandler.get());
NoUnrollAndJamHintHandler.reset();
PP.RemovePragmaHandler("clang", FPHandler.get());
FPHandler.reset();
PP.RemovePragmaHandler("clang", AttributePragmaHandler.get());
AttributePragmaHandler.reset();
}
/// Handle the annotation token produced for #pragma unused(...)
///
/// Each annot_pragma_unused is followed by the argument token so e.g.
/// "#pragma unused(x,y)" becomes:
/// annot_pragma_unused 'x' annot_pragma_unused 'y'
void Parser::HandlePragmaUnused() {
assert(Tok.is(tok::annot_pragma_unused));
SourceLocation UnusedLoc = ConsumeAnnotationToken();
Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc);
ConsumeToken(); // The argument token.
}
void Parser::HandlePragmaVisibility() {
assert(Tok.is(tok::annot_pragma_vis));
const IdentifierInfo *VisType =
static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
SourceLocation VisLoc = ConsumeAnnotationToken();
Actions.ActOnPragmaVisibility(VisType, VisLoc);
}
namespace {
struct PragmaPackInfo {
Sema::PragmaMsStackAction Action;
StringRef SlotLabel;
Token Alignment;
};
} // end anonymous namespace
void Parser::HandlePragmaPack() {
assert(Tok.is(tok::annot_pragma_pack));
PragmaPackInfo *Info =
static_cast<PragmaPackInfo *>(Tok.getAnnotationValue());
SourceLocation PragmaLoc = Tok.getLocation();
ExprResult Alignment;
if (Info->Alignment.is(tok::numeric_constant)) {
Alignment = Actions.ActOnNumericConstant(Info->Alignment);
if (Alignment.isInvalid()) {
ConsumeAnnotationToken();
return;
}
}
Actions.ActOnPragmaPack(PragmaLoc, Info->Action, Info->SlotLabel,
Alignment.get());
// Consume the token after processing the pragma to enable pragma-specific
// #include warnings.
ConsumeAnnotationToken();
}
void Parser::HandlePragmaMSStruct() {
assert(Tok.is(tok::annot_pragma_msstruct));
PragmaMSStructKind Kind = static_cast<PragmaMSStructKind>(
reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
Actions.ActOnPragmaMSStruct(Kind);
ConsumeAnnotationToken();
}
void Parser::HandlePragmaAlign() {
assert(Tok.is(tok::annot_pragma_align));
Sema::PragmaOptionsAlignKind Kind =
static_cast<Sema::PragmaOptionsAlignKind>(
reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
Actions.ActOnPragmaOptionsAlign(Kind, Tok.getLocation());
// Consume the token after processing the pragma to enable pragma-specific
// #include warnings.
ConsumeAnnotationToken();
}
void Parser::HandlePragmaDump() {
assert(Tok.is(tok::annot_pragma_dump));
IdentifierInfo *II =
reinterpret_cast<IdentifierInfo *>(Tok.getAnnotationValue());
Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
ConsumeAnnotationToken();
}
void Parser::HandlePragmaWeak() {
assert(Tok.is(tok::annot_pragma_weak));
SourceLocation PragmaLoc = ConsumeAnnotationToken();
Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc,
Tok.getLocation());
ConsumeToken(); // The weak name.
}
void Parser::HandlePragmaWeakAlias() {
assert(Tok.is(tok::annot_pragma_weakalias));
SourceLocation PragmaLoc = ConsumeAnnotationToken();
IdentifierInfo *WeakName = Tok.getIdentifierInfo();
SourceLocation WeakNameLoc = Tok.getLocation();
ConsumeToken();
IdentifierInfo *AliasName = Tok.getIdentifierInfo();
SourceLocation AliasNameLoc = Tok.getLocation();
ConsumeToken();
Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc,
WeakNameLoc, AliasNameLoc);
}
void Parser::HandlePragmaRedefineExtname() {
assert(Tok.is(tok::annot_pragma_redefine_extname));
SourceLocation RedefLoc = ConsumeAnnotationToken();
IdentifierInfo *RedefName = Tok.getIdentifierInfo();
SourceLocation RedefNameLoc = Tok.getLocation();
ConsumeToken();
IdentifierInfo *AliasName = Tok.getIdentifierInfo();
SourceLocation AliasNameLoc = Tok.getLocation();
ConsumeToken();
Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
RedefNameLoc, AliasNameLoc);
}
void Parser::HandlePragmaFPContract() {
assert(Tok.is(tok::annot_pragma_fp_contract));
tok::OnOffSwitch OOS =
static_cast<tok::OnOffSwitch>(
reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
LangOptions::FPContractModeKind FPC;
switch (OOS) {
case tok::OOS_ON:
FPC = LangOptions::FPC_On;
break;
case tok::OOS_OFF:
FPC = LangOptions::FPC_Off;
break;
case tok::OOS_DEFAULT:
FPC = getLangOpts().getDefaultFPContractMode();
break;
}
Actions.ActOnPragmaFPContract(FPC);
ConsumeAnnotationToken();
}
void Parser::HandlePragmaFEnvAccess() {
assert(Tok.is(tok::annot_pragma_fenv_access));
tok::OnOffSwitch OOS =
static_cast<tok::OnOffSwitch>(
reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
LangOptions::FEnvAccessModeKind FPC;
switch (OOS) {
case tok::OOS_ON:
FPC = LangOptions::FEA_On;
break;
case tok::OOS_OFF:
FPC = LangOptions::FEA_Off;
break;
case tok::OOS_DEFAULT: // FIXME: Add this cli option when it makes sense.
FPC = LangOptions::FEA_Off;
break;
}
Actions.ActOnPragmaFEnvAccess(FPC);
ConsumeAnnotationToken();
}
StmtResult Parser::HandlePragmaCaptured()
{
assert(Tok.is(tok::annot_pragma_captured));
ConsumeAnnotationToken();
if (Tok.isNot(tok::l_brace)) {
PP.Diag(Tok, diag::err_expected) << tok::l_brace;
return StmtError();
}
SourceLocation Loc = Tok.getLocation();
ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope |
Scope::CompoundStmtScope);
Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default,
/*NumParams=*/1);
StmtResult R = ParseCompoundStatement();
CapturedRegionScope.Exit();
if (R.isInvalid()) {
Actions.ActOnCapturedRegionError();
return StmtError();
}
return Actions.ActOnCapturedRegionEnd(R.get());
}
namespace {
enum OpenCLExtState : char {
Disable, Enable, Begin, End
};
typedef std::pair<const IdentifierInfo *, OpenCLExtState> OpenCLExtData;
}
void Parser::HandlePragmaOpenCLExtension() {
assert(Tok.is(tok::annot_pragma_opencl_extension));
OpenCLExtData *Data = static_cast<OpenCLExtData*>(Tok.getAnnotationValue());
auto State = Data->second;
auto Ident = Data->first;
SourceLocation NameLoc = Tok.getLocation();
ConsumeAnnotationToken();
auto &Opt = Actions.getOpenCLOptions();
auto Name = Ident->getName();
// OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
// overriding all previously issued extension directives, but only if the
// behavior is set to disable."
if (Name == "all") {
if (State == Disable) {
Opt.disableAll();
Opt.enableSupportedCore(getLangOpts());
} else {
PP.Diag(NameLoc, diag::warn_pragma_expected_predicate) << 1;
}
} else if (State == Begin) {
if (!Opt.isKnown(Name) || !Opt.isSupported(Name, getLangOpts())) {
Opt.support(Name);
}
Actions.setCurrentOpenCLExtension(Name);
} else if (State == End) {
if (Name != Actions.getCurrentOpenCLExtension())
PP.Diag(NameLoc, diag::warn_pragma_begin_end_mismatch);
Actions.setCurrentOpenCLExtension("");
} else if (!Opt.isKnown(Name))
PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << Ident;
else if (Opt.isSupportedExtension(Name, getLangOpts()))
Opt.enable(Name, State == Enable);
else if (Opt.isSupportedCore(Name, getLangOpts()))
PP.Diag(NameLoc, diag::warn_pragma_extension_is_core) << Ident;
else
PP.Diag(NameLoc, diag::warn_pragma_unsupported_extension) << Ident;
}
void Parser::HandlePragmaMSPointersToMembers() {
assert(Tok.is(tok::annot_pragma_ms_pointers_to_members));
LangOptions::PragmaMSPointersToMembersKind RepresentationMethod =
static_cast<LangOptions::PragmaMSPointersToMembersKind>(
reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
SourceLocation PragmaLoc = ConsumeAnnotationToken();
Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc);
}
void Parser::HandlePragmaMSVtorDisp() {
assert(Tok.is(tok::annot_pragma_ms_vtordisp));
uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
Sema::PragmaMsStackAction Action =
static_cast<Sema::PragmaMsStackAction>((Value >> 16) & 0xFFFF);
MSVtorDispAttr::Mode Mode = MSVtorDispAttr::Mode(Value & 0xFFFF);
SourceLocation PragmaLoc = ConsumeAnnotationToken();
Actions.ActOnPragmaMSVtorDisp(Action, PragmaLoc, Mode);
}
void Parser::HandlePragmaMSPragma() {
assert(Tok.is(tok::annot_pragma_ms_pragma));
// Grab the tokens out of the annotation and enter them into the stream.
auto TheTokens =
(std::pair<std::unique_ptr<Token[]>, size_t> *)Tok.getAnnotationValue();
PP.EnterTokenStream(std::move(TheTokens->first), TheTokens->second, true,
/*IsReinject=*/true);
SourceLocation PragmaLocation = ConsumeAnnotationToken();
assert(Tok.isAnyIdentifier());
StringRef PragmaName = Tok.getIdentifierInfo()->getName();
PP.Lex(Tok); // pragma kind
// Figure out which #pragma we're dealing with. The switch has no default
// because lex shouldn't emit the annotation token for unrecognized pragmas.
typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation);
PragmaHandler Handler = llvm::StringSwitch<PragmaHandler>(PragmaName)
.Case("data_seg", &Parser::HandlePragmaMSSegment)
.Case("bss_seg", &Parser::HandlePragmaMSSegment)
.Case("const_seg", &Parser::HandlePragmaMSSegment)
.Case("code_seg", &Parser::HandlePragmaMSSegment)
.Case("section", &Parser::HandlePragmaMSSection)
.Case("init_seg", &Parser::HandlePragmaMSInitSeg);
if (!(this->*Handler)(PragmaName, PragmaLocation)) {
// Pragma handling failed, and has been diagnosed. Slurp up the tokens
// until eof (really end of line) to prevent follow-on errors.
while (Tok.isNot(tok::eof))
PP.Lex(Tok);
PP.Lex(Tok);
}
}
bool Parser::HandlePragmaMSSection(StringRef PragmaName,
SourceLocation PragmaLocation) {
if (Tok.isNot(tok::l_paren)) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
return false;
}
PP.Lex(Tok); // (
// Parsing code for pragma section
if (Tok.isNot(tok::string_literal)) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
<< PragmaName;
return false;
}
ExprResult StringResult = ParseStringLiteralExpression();
if (StringResult.isInvalid())
return false; // Already diagnosed.
StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
if (SegmentName->getCharByteWidth() != 1) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
<< PragmaName;
return false;
}
int SectionFlags = ASTContext::PSF_Read;
bool SectionFlagsAreDefault = true;
while (Tok.is(tok::comma)) {
PP.Lex(Tok); // ,
// Ignore "long" and "short".
// They are undocumented, but widely used, section attributes which appear
// to do nothing.
if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) {
PP.Lex(Tok); // long/short
continue;
}
if (!Tok.isAnyIdentifier()) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren)
<< PragmaName;
return false;
}
ASTContext::PragmaSectionFlag Flag =
llvm::StringSwitch<ASTContext::PragmaSectionFlag>(
Tok.getIdentifierInfo()->getName())
.Case("read", ASTContext::PSF_Read)
.Case("write", ASTContext::PSF_Write)
.Case("execute", ASTContext::PSF_Execute)
.Case("shared", ASTContext::PSF_Invalid)
.Case("nopage", ASTContext::PSF_Invalid)
.Case("nocache", ASTContext::PSF_Invalid)
.Case("discard", ASTContext::PSF_Invalid)
.Case("remove", ASTContext::PSF_Invalid)
.Default(ASTContext::PSF_None);
if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) {
PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None
? diag::warn_pragma_invalid_specific_action
: diag::warn_pragma_unsupported_action)
<< PragmaName << Tok.getIdentifierInfo()->getName();
return false;
}
SectionFlags |= Flag;
SectionFlagsAreDefault = false;
PP.Lex(Tok); // Identifier
}
// If no section attributes are specified, the section will be marked as
// read/write.
if (SectionFlagsAreDefault)
SectionFlags |= ASTContext::PSF_Write;
if (Tok.isNot(tok::r_paren)) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
return false;
}
PP.Lex(Tok); // )
if (Tok.isNot(tok::eof)) {
PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
<< PragmaName;
return false;
}
PP.Lex(Tok); // eof
Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName);
return true;
}
bool Parser::HandlePragmaMSSegment(StringRef PragmaName,
SourceLocation PragmaLocation) {
if (Tok.isNot(tok::l_paren)) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
return false;
}
PP.Lex(Tok); // (
Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
StringRef SlotLabel;
if (Tok.isAnyIdentifier()) {
StringRef PushPop = Tok.getIdentifierInfo()->getName();
if (PushPop == "push")
Action = Sema::PSK_Push;
else if (PushPop == "pop")
Action = Sema::PSK_Pop;
else {
PP.Diag(PragmaLocation,
diag::warn_pragma_expected_section_push_pop_or_name)
<< PragmaName;
return false;
}
if (Action != Sema::PSK_Reset) {
PP.Lex(Tok); // push | pop
if (Tok.is(tok::comma)) {
PP.Lex(Tok); // ,
// If we've got a comma, we either need a label or a string.
if (Tok.isAnyIdentifier()) {
SlotLabel = Tok.getIdentifierInfo()->getName();
PP.Lex(Tok); // identifier
if (Tok.is(tok::comma))
PP.Lex(Tok);
else if (Tok.isNot(tok::r_paren)) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc)
<< PragmaName;
return false;
}
}
} else if (Tok.isNot(tok::r_paren)) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName;
return false;
}
}
}
// Grab the string literal for our section name.
StringLiteral *SegmentName = nullptr;
if (Tok.isNot(tok::r_paren)) {
if (Tok.isNot(tok::string_literal)) {
unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ?
diag::warn_pragma_expected_section_name :
diag::warn_pragma_expected_section_label_or_name :
diag::warn_pragma_expected_section_push_pop_or_name;
PP.Diag(PragmaLocation, DiagID) << PragmaName;
return false;
}
ExprResult StringResult = ParseStringLiteralExpression();
if (StringResult.isInvalid())
return false; // Already diagnosed.
SegmentName = cast<StringLiteral>(StringResult.get());
if (SegmentName->getCharByteWidth() != 1) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
<< PragmaName;
return false;
}
// Setting section "" has no effect
if (SegmentName->getLength())
Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
return false;
}
PP.Lex(Tok); // )
if (Tok.isNot(tok::eof)) {
PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
<< PragmaName;
return false;
}
PP.Lex(Tok); // eof
Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel,
SegmentName, PragmaName);
return true;
}
// #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName,
SourceLocation PragmaLocation) {
if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) {
PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target);
return false;
}
if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
PragmaName))
return false;
// Parse either the known section names or the string section name.
StringLiteral *SegmentName = nullptr;
if (Tok.isAnyIdentifier()) {
auto *II = Tok.getIdentifierInfo();
StringRef Section = llvm::StringSwitch<StringRef>(II->getName())
.Case("compiler", "\".CRT$XCC\"")
.Case("lib", "\".CRT$XCL\"")
.Case("user", "\".CRT$XCU\"")
.Default("");
if (!Section.empty()) {
// Pretend the user wrote the appropriate string literal here.
Token Toks[1];
Toks[0].startToken();
Toks[0].setKind(tok::string_literal);
Toks[0].setLocation(Tok.getLocation());
Toks[0].setLiteralData(Section.data());
Toks[0].setLength(Section.size());
SegmentName =
cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
PP.Lex(Tok);
}
} else if (Tok.is(tok::string_literal)) {
ExprResult StringResult = ParseStringLiteralExpression();
if (StringResult.isInvalid())
return false;
SegmentName = cast<StringLiteral>(StringResult.get());
if (SegmentName->getCharByteWidth() != 1) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
<< PragmaName;
return false;
}
// FIXME: Add support for the '[, func-name]' part of the pragma.
}
if (!SegmentName) {
PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName;
return false;
}
if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
PragmaName) ||
ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
PragmaName))
return false;
Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName);
return true;
}
namespace {
struct PragmaLoopHintInfo {
Token PragmaName;
Token Option;
ArrayRef<Token> Toks;
};
} // end anonymous namespace
static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
StringRef Str = PragmaName.getIdentifierInfo()->getName();
std::string ClangLoopStr = (llvm::Twine("clang loop ") + Str).str();
return llvm::StringSwitch<StringRef>(Str)
.Case("loop", ClangLoopStr)
.Case("unroll_and_jam", Str)
.Case("unroll", Str)
.Default("");
}
bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
assert(Tok.is(tok::annot_pragma_loop_hint));
PragmaLoopHintInfo *Info =
static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo();
Hint.PragmaNameLoc = IdentifierLoc::create(
Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo);
// It is possible that the loop hint has no option identifier, such as
// #pragma unroll(4).
IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier)
? Info->Option.getIdentifierInfo()
: nullptr;
Hint.OptionLoc = IdentifierLoc::create(
Actions.Context, Info->Option.getLocation(), OptionInfo);
llvm::ArrayRef<Token> Toks = Info->Toks;
// Return a valid hint if pragma unroll or nounroll were specified
// without an argument.
auto IsLoopHint = llvm::StringSwitch<bool>(PragmaNameInfo->getName())
.Cases("unroll", "nounroll", "unroll_and_jam",
"nounroll_and_jam", true)
.Default(false);
if (Toks.empty() && IsLoopHint) {
ConsumeAnnotationToken();
Hint.Range = Info->PragmaName.getLocation();
return true;
}
// The constant expression is always followed by an eof token, which increases
// the TokSize by 1.
assert(!Toks.empty() &&
"PragmaLoopHintInfo::Toks must contain at least one token.");
// If no option is specified the argument is assumed to be a constant expr.
bool OptionUnroll = false;
bool OptionUnrollAndJam = false;
bool OptionDistribute = false;
bool OptionPipelineDisabled = false;
bool StateOption = false;
if (OptionInfo) { // Pragma Unroll does not specify an option.
OptionUnroll = OptionInfo->isStr("unroll");
OptionUnrollAndJam = OptionInfo->isStr("unroll_and_jam");
OptionDistribute = OptionInfo->isStr("distribute");
OptionPipelineDisabled = OptionInfo->isStr("pipeline");
StateOption = llvm::StringSwitch<bool>(OptionInfo->getName())
.Case("vectorize", true)
.Case("interleave", true)
.Case("vectorize_predicate", true)
.Default(false) ||
OptionUnroll || OptionUnrollAndJam || OptionDistribute ||
OptionPipelineDisabled;
}
bool AssumeSafetyArg = !OptionUnroll && !OptionUnrollAndJam &&
!OptionDistribute && !OptionPipelineDisabled;
// Verify loop hint has an argument.
if (Toks[0].is(tok::eof)) {
ConsumeAnnotationToken();
Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument)
<< /*StateArgument=*/StateOption
<< /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
<< /*AssumeSafetyKeyword=*/AssumeSafetyArg;
return false;
}
// Validate the argument.
if (StateOption) {
ConsumeAnnotationToken();
SourceLocation StateLoc = Toks[0].getLocation();
IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
bool Valid = StateInfo &&
llvm::StringSwitch<bool>(StateInfo->getName())
.Case("disable", true)
.Case("enable", !OptionPipelineDisabled)
.Case("full", OptionUnroll || OptionUnrollAndJam)
.Case("assume_safety", AssumeSafetyArg)
.Default(false);
if (!Valid) {
if (OptionPipelineDisabled) {
Diag(Toks[0].getLocation(), diag::err_pragma_pipeline_invalid_keyword);
} else {
Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword)
<< /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
<< /*AssumeSafetyKeyword=*/AssumeSafetyArg;
}
return false;
}
if (Toks.size() > 2)
Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< PragmaLoopHintString(Info->PragmaName, Info->Option);
Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
} else {
// Enter constant expression including eof terminator into token stream.
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
/*IsReinject=*/false);
ConsumeAnnotationToken();
ExprResult R = ParseConstantExpression();
// Tokens following an error in an ill-formed constant expression will
// remain in the token stream and must be removed.
if (Tok.isNot(tok::eof)) {
Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< PragmaLoopHintString(Info->PragmaName, Info->Option);
while (Tok.isNot(tok::eof))
ConsumeAnyToken();
}
ConsumeToken(); // Consume the constant expression eof terminator.
if (R.isInvalid() ||
Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
return false;
// Argument is a constant expression with an integer type.
Hint.ValueExpr = R.get();
}
Hint.Range = SourceRange(Info->PragmaName.getLocation(),
Info->Toks.back().getLocation());
return true;
}
namespace {
struct PragmaAttributeInfo {
enum ActionType { Push, Pop, Attribute };
ParsedAttributes &Attributes;
ActionType Action;
const IdentifierInfo *Namespace = nullptr;
ArrayRef<Token> Tokens;
PragmaAttributeInfo(ParsedAttributes &Attributes) : Attributes(Attributes) {}
};
#include "clang/Parse/AttrSubMatchRulesParserStringSwitches.inc"
} // end anonymous namespace
static StringRef getIdentifier(const Token &Tok) {
if (Tok.is(tok::identifier))
return Tok.getIdentifierInfo()->getName();
const char *S = tok::getKeywordSpelling(Tok.getKind());
if (!S)
return "";
return S;
}
static bool isAbstractAttrMatcherRule(attr::SubjectMatchRule Rule) {
using namespace attr;
switch (Rule) {
#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract) \
case Value: \
return IsAbstract;
#include "clang/Basic/AttrSubMatchRulesList.inc"
}
llvm_unreachable("Invalid attribute subject match rule");
return false;
}
static void diagnoseExpectedAttributeSubjectSubRule(
Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
SourceLocation SubRuleLoc) {
auto Diagnostic =
PRef.Diag(SubRuleLoc,
diag::err_pragma_attribute_expected_subject_sub_identifier)
<< PrimaryRuleName;
if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
Diagnostic << /*SubRulesSupported=*/1 << SubRules;
else
Diagnostic << /*SubRulesSupported=*/0;
}
static void diagnoseUnknownAttributeSubjectSubRule(
Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
StringRef SubRuleName, SourceLocation SubRuleLoc) {
auto Diagnostic =
PRef.Diag(SubRuleLoc, diag::err_pragma_attribute_unknown_subject_sub_rule)
<< SubRuleName << PrimaryRuleName;
if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
Diagnostic << /*SubRulesSupported=*/1 << SubRules;
else
Diagnostic << /*SubRulesSupported=*/0;
}
bool Parser::ParsePragmaAttributeSubjectMatchRuleSet(
attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc,
SourceLocation &LastMatchRuleEndLoc) {
bool IsAny = false;
BalancedDelimiterTracker AnyParens(*this, tok::l_paren);
if (getIdentifier(Tok) == "any") {
AnyLoc = ConsumeToken();
IsAny = true;
if (AnyParens.expectAndConsume())
return true;
}
do {
// Parse the subject matcher rule.
StringRef Name = getIdentifier(Tok);
if (Name.empty()) {
Diag(Tok, diag::err_pragma_attribute_expected_subject_identifier);
return true;
}
std::pair<Optional<attr::SubjectMatchRule>,
Optional<attr::SubjectMatchRule> (*)(StringRef, bool)>
Rule = isAttributeSubjectMatchRule(Name);
if (!Rule.first) {
Diag(Tok, diag::err_pragma_attribute_unknown_subject_rule) << Name;
return true;
}
attr::SubjectMatchRule PrimaryRule = *Rule.first;
SourceLocation RuleLoc = ConsumeToken();
BalancedDelimiterTracker Parens(*this, tok::l_paren);
if (isAbstractAttrMatcherRule(PrimaryRule)) {
if (Parens.expectAndConsume())
return true;
} else if (Parens.consumeOpen()) {
if (!SubjectMatchRules
.insert(
std::make_pair(PrimaryRule, SourceRange(RuleLoc, RuleLoc)))
.second)
Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
<< Name
<< FixItHint::CreateRemoval(SourceRange(
RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleLoc));
LastMatchRuleEndLoc = RuleLoc;
continue;
}
// Parse the sub-rules.
StringRef SubRuleName = getIdentifier(Tok);
if (SubRuleName.empty()) {
diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
Tok.getLocation());
return true;
}
attr::SubjectMatchRule SubRule;
if (SubRuleName == "unless") {
SourceLocation SubRuleLoc = ConsumeToken();
BalancedDelimiterTracker Parens(*this, tok::l_paren);
if (Parens.expectAndConsume())
return true;
SubRuleName = getIdentifier(Tok);
if (SubRuleName.empty()) {
diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
SubRuleLoc);
return true;
}
auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/true);
if (!SubRuleOrNone) {
std::string SubRuleUnlessName = "unless(" + SubRuleName.str() + ")";
diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
SubRuleUnlessName, SubRuleLoc);
return true;
}
SubRule = *SubRuleOrNone;
ConsumeToken();
if (Parens.consumeClose())
return true;
} else {
auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/false);
if (!SubRuleOrNone) {
diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
SubRuleName, Tok.getLocation());
return true;
}
SubRule = *SubRuleOrNone;
ConsumeToken();
}
SourceLocation RuleEndLoc = Tok.getLocation();
LastMatchRuleEndLoc = RuleEndLoc;
if (Parens.consumeClose())
return true;
if (!SubjectMatchRules
.insert(std::make_pair(SubRule, SourceRange(RuleLoc, RuleEndLoc)))
.second) {
Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
<< attr::getSubjectMatchRuleSpelling(SubRule)
<< FixItHint::CreateRemoval(SourceRange(
RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleEndLoc));
continue;
}
} while (IsAny && TryConsumeToken(tok::comma));
if (IsAny)
if (AnyParens.consumeClose())
return true;
return false;
}
namespace {
/// Describes the stage at which attribute subject rule parsing was interrupted.
enum class MissingAttributeSubjectRulesRecoveryPoint {
Comma,
ApplyTo,
Equals,
Any,
None,
};
MissingAttributeSubjectRulesRecoveryPoint
getAttributeSubjectRulesRecoveryPointForToken(const Token &Tok) {
if (const auto *II = Tok.getIdentifierInfo()) {
if (II->isStr("apply_to"))
return MissingAttributeSubjectRulesRecoveryPoint::ApplyTo;
if (II->isStr("any"))
return MissingAttributeSubjectRulesRecoveryPoint::Any;
}
if (Tok.is(tok::equal))
return MissingAttributeSubjectRulesRecoveryPoint::Equals;
return MissingAttributeSubjectRulesRecoveryPoint::None;
}
/// Creates a diagnostic for the attribute subject rule parsing diagnostic that
/// suggests the possible attribute subject rules in a fix-it together with
/// any other missing tokens.
DiagnosticBuilder createExpectedAttributeSubjectRulesTokenDiagnostic(
unsigned DiagID, ParsedAttr &Attribute,
MissingAttributeSubjectRulesRecoveryPoint Point, Parser &PRef) {
SourceLocation Loc = PRef.getEndOfPreviousToken();
if (Loc.isInvalid())
Loc = PRef.getCurToken().getLocation();
auto Diagnostic = PRef.Diag(Loc, DiagID);
std::string FixIt;
MissingAttributeSubjectRulesRecoveryPoint EndPoint =
getAttributeSubjectRulesRecoveryPointForToken(PRef.getCurToken());
if (Point == MissingAttributeSubjectRulesRecoveryPoint::Comma)
FixIt = ", ";
if (Point <= MissingAttributeSubjectRulesRecoveryPoint::ApplyTo &&
EndPoint > MissingAttributeSubjectRulesRecoveryPoint::ApplyTo)
FixIt += "apply_to";
if (Point <= MissingAttributeSubjectRulesRecoveryPoint::Equals &&
EndPoint > MissingAttributeSubjectRulesRecoveryPoint::Equals)
FixIt += " = ";
SourceRange FixItRange(Loc);
if (EndPoint == MissingAttributeSubjectRulesRecoveryPoint::None) {
// Gather the subject match rules that are supported by the attribute.
SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4> SubjectMatchRuleSet;
Attribute.getMatchRules(PRef.getLangOpts(), SubjectMatchRuleSet);
if (SubjectMatchRuleSet.empty()) {
// FIXME: We can emit a "fix-it" with a subject list placeholder when
// placeholders will be supported by the fix-its.
return Diagnostic;
}
FixIt += "any(";
bool NeedsComma = false;
for (const auto &I : SubjectMatchRuleSet) {
// Ensure that the missing rule is reported in the fix-it only when it's
// supported in the current language mode.
if (!I.second)
continue;
if (NeedsComma)
FixIt += ", ";
else
NeedsComma = true;
FixIt += attr::getSubjectMatchRuleSpelling(I.first);
}
FixIt += ")";
// Check if we need to remove the range
PRef.SkipUntil(tok::eof, Parser::StopBeforeMatch);
FixItRange.setEnd(PRef.getCurToken().getLocation());
}
if (FixItRange.getBegin() == FixItRange.getEnd())
Diagnostic << FixItHint::CreateInsertion(FixItRange.getBegin(), FixIt);
else
Diagnostic << FixItHint::CreateReplacement(
CharSourceRange::getCharRange(FixItRange), FixIt);
return Diagnostic;
}
} // end anonymous namespace
void Parser::HandlePragmaAttribute() {
assert(Tok.is(tok::annot_pragma_attribute) &&
"Expected #pragma attribute annotation token");
SourceLocation PragmaLoc = Tok.getLocation();
auto *Info = static_cast<PragmaAttributeInfo *>(Tok.getAnnotationValue());
if (Info->Action == PragmaAttributeInfo::Pop) {
ConsumeAnnotationToken();
Actions.ActOnPragmaAttributePop(PragmaLoc, Info->Namespace);
return;
}
// Parse the actual attribute with its arguments.
assert((Info->Action == PragmaAttributeInfo::Push ||
Info->Action == PragmaAttributeInfo::Attribute) &&
"Unexpected #pragma attribute command");
if (Info->Action == PragmaAttributeInfo::Push && Info->Tokens.empty()) {
ConsumeAnnotationToken();
Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
return;
}
PP.EnterTokenStream(Info->Tokens, /*DisableMacroExpansion=*/false,
/*IsReinject=*/false);
ConsumeAnnotationToken();
ParsedAttributes &Attrs = Info->Attributes;
Attrs.clearListOnly();
auto SkipToEnd = [this]() {
SkipUntil(tok::eof, StopBeforeMatch);
ConsumeToken();
};
if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
// Parse the CXX11 style attribute.
ParseCXX11AttributeSpecifier(Attrs);
} else if (Tok.is(tok::kw___attribute)) {
ConsumeToken();
if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
"attribute"))
return SkipToEnd();
if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "("))
return SkipToEnd();
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_pragma_attribute_expected_attribute_name);
SkipToEnd();
return;
}
IdentifierInfo *AttrName = Tok.getIdentifierInfo();
SourceLocation AttrNameLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren))
Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
ParsedAttr::AS_GNU);
else
ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, /*EndLoc=*/nullptr,
/*ScopeName=*/nullptr,
/*ScopeLoc=*/SourceLocation(), ParsedAttr::AS_GNU,
/*Declarator=*/nullptr);
if (ExpectAndConsume(tok::r_paren))
return SkipToEnd();
if (ExpectAndConsume(tok::r_paren))
return SkipToEnd();
} else if (Tok.is(tok::kw___declspec)) {
ParseMicrosoftDeclSpecs(Attrs);
} else {
Diag(Tok, diag::err_pragma_attribute_expected_attribute_syntax);
if (Tok.getIdentifierInfo()) {
// If we suspect that this is an attribute suggest the use of
// '__attribute__'.
if (ParsedAttr::getParsedKind(
Tok.getIdentifierInfo(), /*ScopeName=*/nullptr,
ParsedAttr::AS_GNU) != ParsedAttr::UnknownAttribute) {
SourceLocation InsertStartLoc = Tok.getLocation();
ConsumeToken();
if (Tok.is(tok::l_paren)) {
ConsumeAnyToken();
SkipUntil(tok::r_paren, StopBeforeMatch);
if (Tok.isNot(tok::r_paren))
return SkipToEnd();
}
Diag(Tok, diag::note_pragma_attribute_use_attribute_kw)
<< FixItHint::CreateInsertion(InsertStartLoc, "__attribute__((")
<< FixItHint::CreateInsertion(Tok.getEndLoc(), "))");
}
}
SkipToEnd();
return;
}
if (Attrs.empty() || Attrs.begin()->isInvalid()) {
SkipToEnd();
return;
}
// Ensure that we don't have more than one attribute.
if (Attrs.size() > 1) {
SourceLocation Loc = Attrs[1].getLoc();
Diag(Loc, diag::err_pragma_attribute_multiple_attributes);
SkipToEnd();
return;
}
ParsedAttr &Attribute = *Attrs.begin();
if (!Attribute.isSupportedByPragmaAttribute()) {
Diag(PragmaLoc, diag::err_pragma_attribute_unsupported_attribute)
<< Attribute;
SkipToEnd();
return;
}
// Parse the subject-list.
if (!TryConsumeToken(tok::comma)) {
createExpectedAttributeSubjectRulesTokenDiagnostic(
diag::err_expected, Attribute,
MissingAttributeSubjectRulesRecoveryPoint::Comma, *this)
<< tok::comma;
SkipToEnd();
return;
}
if (Tok.isNot(tok::identifier)) {
createExpectedAttributeSubjectRulesTokenDiagnostic(
diag::err_pragma_attribute_invalid_subject_set_specifier, Attribute,
MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
SkipToEnd();
return;
}
const IdentifierInfo *II = Tok.getIdentifierInfo();
if (!II->isStr("apply_to")) {
createExpectedAttributeSubjectRulesTokenDiagnostic(
diag::err_pragma_attribute_invalid_subject_set_specifier, Attribute,
MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
SkipToEnd();
return;
}
ConsumeToken();
if (!TryConsumeToken(tok::equal)) {
createExpectedAttributeSubjectRulesTokenDiagnostic(
diag::err_expected, Attribute,
MissingAttributeSubjectRulesRecoveryPoint::Equals, *this)
<< tok::equal;
SkipToEnd();
return;
}
attr::ParsedSubjectMatchRuleSet SubjectMatchRules;
SourceLocation AnyLoc, LastMatchRuleEndLoc;
if (ParsePragmaAttributeSubjectMatchRuleSet(SubjectMatchRules, AnyLoc,
LastMatchRuleEndLoc)) {
SkipToEnd();
return;
}
// Tokens following an ill-formed attribute will remain in the token stream
// and must be removed.
if (Tok.isNot(tok::eof)) {
Diag(Tok, diag::err_pragma_attribute_extra_tokens_after_attribute);
SkipToEnd();
return;
}
// Consume the eof terminator token.
ConsumeToken();
// Handle a mixed push/attribute by desurging to a push, then an attribute.
if (Info->Action == PragmaAttributeInfo::Push)
Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
Actions.ActOnPragmaAttributeAttribute(Attribute, PragmaLoc,
std::move(SubjectMatchRules));
}
// #pragma GCC visibility comes in two variants:
// 'push' '(' [visibility] ')'
// 'pop'
void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &VisTok) {
SourceLocation VisLoc = VisTok.getLocation();
Token Tok;
PP.LexUnexpandedToken(Tok);
const IdentifierInfo *PushPop = Tok.getIdentifierInfo();
const IdentifierInfo *VisType;
if (PushPop && PushPop->isStr("pop")) {
VisType = nullptr;
} else if (PushPop && PushPop->isStr("push")) {
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
<< "visibility";
return;
}
PP.LexUnexpandedToken(Tok);
VisType = Tok.getIdentifierInfo();
if (!VisType) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
<< "visibility";
return;
}
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
<< "visibility";
return;
}
} else {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
<< "visibility";
return;
}
SourceLocation EndLoc = Tok.getLocation();
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "visibility";
return;
}
auto Toks = std::make_unique<Token[]>(1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_vis);
Toks[0].setLocation(VisLoc);
Toks[0].setAnnotationEndLoc(EndLoc);
Toks[0].setAnnotationValue(
const_cast<void *>(static_cast<const void *>(VisType)));
PP.EnterTokenStream(std::move(Toks), 1, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
// #pragma pack(...) comes in the following delicious flavors:
// pack '(' [integer] ')'
// pack '(' 'show' ')'
// pack '(' ('push' | 'pop') [',' identifier] [, integer] ')'
void PragmaPackHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &PackTok) {
SourceLocation PackLoc = PackTok.getLocation();
Token Tok;
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack";
return;
}
Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
StringRef SlotLabel;
Token Alignment;
Alignment.startToken();
PP.Lex(Tok);
if (Tok.is(tok::numeric_constant)) {
Alignment = Tok;
PP.Lex(Tok);
// In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
// the push/pop stack.
// In Apple gcc, #pragma pack(4) is equivalent to #pragma pack(push, 4)
Action =
PP.getLangOpts().ApplePragmaPack ? Sema::PSK_Push_Set : Sema::PSK_Set;
} else if (Tok.is(tok::identifier)) {
const IdentifierInfo *II = Tok.getIdentifierInfo();
if (II->isStr("show")) {
Action = Sema::PSK_Show;
PP.Lex(Tok);
} else {
if (II->isStr("push")) {
Action = Sema::PSK_Push;
} else if (II->isStr("pop")) {
Action = Sema::PSK_Pop;
} else {
PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack";
return;
}
PP.Lex(Tok);
if (Tok.is(tok::comma)) {
PP.Lex(Tok);
if (Tok.is(tok::numeric_constant)) {
Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
Alignment = Tok;
PP.Lex(Tok);
} else if (Tok.is(tok::identifier)) {
SlotLabel = Tok.getIdentifierInfo()->getName();
PP.Lex(Tok);
if (Tok.is(tok::comma)) {
PP.Lex(Tok);
if (Tok.isNot(tok::numeric_constant)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
return;
}
Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
Alignment = Tok;
PP.Lex(Tok);
}
} else {
PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
return;
}
}
}
} else if (PP.getLangOpts().ApplePragmaPack) {
// In MSVC/gcc, #pragma pack() resets the alignment without affecting
// the push/pop stack.
// In Apple gcc #pragma pack() is equivalent to #pragma pack(pop).
Action = Sema::PSK_Pop;
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack";
return;
}
SourceLocation RParenLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack";
return;
}
PragmaPackInfo *Info =
PP.getPreprocessorAllocator().Allocate<PragmaPackInfo>(1);
Info->Action = Action;
Info->SlotLabel = SlotLabel;
Info->Alignment = Alignment;
MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_pack);
Toks[0].setLocation(PackLoc);
Toks[0].setAnnotationEndLoc(RParenLoc);
Toks[0].setAnnotationValue(static_cast<void*>(Info));
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
// #pragma ms_struct on
// #pragma ms_struct off
void PragmaMSStructHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &MSStructTok) {
PragmaMSStructKind Kind = PMSST_OFF;
Token Tok;
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
return;
}
SourceLocation EndLoc = Tok.getLocation();
const IdentifierInfo *II = Tok.getIdentifierInfo();
if (II->isStr("on")) {
Kind = PMSST_ON;
PP.Lex(Tok);
}
else if (II->isStr("off") || II->isStr("reset"))
PP.Lex(Tok);
else {
PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
return;
}
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "ms_struct";
return;
}
MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_msstruct);
Toks[0].setLocation(MSStructTok.getLocation());
Toks[0].setAnnotationEndLoc(EndLoc);
Toks[0].setAnnotationValue(reinterpret_cast<void*>(
static_cast<uintptr_t>(Kind)));
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
// #pragma clang section bss="abc" data="" rodata="def" text="" relro=""
void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &FirstToken) {
Token Tok;
auto SecKind = Sema::PragmaClangSectionKind::PCSK_Invalid;
PP.Lex(Tok); // eat 'section'
while (Tok.isNot(tok::eod)) {
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
return;
}
const IdentifierInfo *SecType = Tok.getIdentifierInfo();
if (SecType->isStr("bss"))
SecKind = Sema::PragmaClangSectionKind::PCSK_BSS;
else if (SecType->isStr("data"))
SecKind = Sema::PragmaClangSectionKind::PCSK_Data;
else if (SecType->isStr("rodata"))
SecKind = Sema::PragmaClangSectionKind::PCSK_Rodata;
else if (SecType->isStr("relro"))
SecKind = Sema::PragmaClangSectionKind::PCSK_Relro;
else if (SecType->isStr("text"))
SecKind = Sema::PragmaClangSectionKind::PCSK_Text;
else {
PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
return;
}
PP.Lex(Tok); // eat ['bss'|'data'|'rodata'|'text']
if (Tok.isNot(tok::equal)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_clang_section_expected_equal) << SecKind;
return;
}
std::string SecName;
if (!PP.LexStringLiteral(Tok, SecName, "pragma clang section", false))
return;
Actions.ActOnPragmaClangSection(Tok.getLocation(),
(SecName.size()? Sema::PragmaClangSectionAction::PCSA_Set :
Sema::PragmaClangSectionAction::PCSA_Clear),
SecKind, SecName);
}
}
// #pragma 'align' '=' {'native','natural','mac68k','power','reset'}
// #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'}
static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok,
bool IsOptions) {
Token Tok;
if (IsOptions) {
PP.Lex(Tok);
if (Tok.isNot(tok::identifier) ||
!Tok.getIdentifierInfo()->isStr("align")) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align);
return;
}
}
PP.Lex(Tok);
if (Tok.isNot(tok::equal)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal)
<< IsOptions;
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
<< (IsOptions ? "options" : "align");
return;
}
Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural;
const IdentifierInfo *II = Tok.getIdentifierInfo();
if (II->isStr("native"))
Kind = Sema::POAK_Native;
else if (II->isStr("natural"))
Kind = Sema::POAK_Natural;
else if (II->isStr("packed"))
Kind = Sema::POAK_Packed;
else if (II->isStr("power"))
Kind = Sema::POAK_Power;
else if (II->isStr("mac68k"))
Kind = Sema::POAK_Mac68k;
else if (II->isStr("reset"))
Kind = Sema::POAK_Reset;
else {
PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option)
<< IsOptions;
return;
}
SourceLocation EndLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< (IsOptions ? "options" : "align");
return;
}
MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_align);
Toks[0].setLocation(FirstTok.getLocation());
Toks[0].setAnnotationEndLoc(EndLoc);
Toks[0].setAnnotationValue(reinterpret_cast<void*>(
static_cast<uintptr_t>(Kind)));
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
void PragmaAlignHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &AlignTok) {
ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false);
}
void PragmaOptionsHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &OptionsTok) {
ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true);
}
// #pragma unused(identifier)
void PragmaUnusedHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &UnusedTok) {
// FIXME: Should we be expanding macros here? My guess is no.
SourceLocation UnusedLoc = UnusedTok.getLocation();
// Lex the left '('.
Token Tok;
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused";
return;
}
// Lex the declaration reference(s).
SmallVector<Token, 5> Identifiers;
SourceLocation RParenLoc;
bool LexID = true;
while (true) {
PP.Lex(Tok);
if (LexID) {
if (Tok.is(tok::identifier)) {
Identifiers.push_back(Tok);
LexID = false;
continue;
}
// Illegal token!
PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var);
return;
}
// We are execting a ')' or a ','.
if (Tok.is(tok::comma)) {
LexID = true;
continue;
}
if (Tok.is(tok::r_paren)) {
RParenLoc = Tok.getLocation();
break;
}
// Illegal token!
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused";
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
"unused";
return;
}
// Verify that we have a location for the right parenthesis.
assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'");
assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments");
// For each identifier token, insert into the token stream a
// annot_pragma_unused token followed by the identifier token.
// This allows us to cache a "#pragma unused" that occurs inside an inline
// C++ member function.
MutableArrayRef<Token> Toks(
PP.getPreprocessorAllocator().Allocate<Token>(2 * Identifiers.size()),
2 * Identifiers.size());
for (unsigned i=0; i != Identifiers.size(); i++) {
Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1];
pragmaUnusedTok.startToken();
pragmaUnusedTok.setKind(tok::annot_pragma_unused);
pragmaUnusedTok.setLocation(UnusedLoc);
idTok = Identifiers[i];
}
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
// #pragma weak identifier
// #pragma weak identifier '=' identifier
void PragmaWeakHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &WeakTok) {
SourceLocation WeakLoc = WeakTok.getLocation();
Token Tok;
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak";
return;
}
Token WeakName = Tok;
bool HasAlias = false;
Token AliasName;
PP.Lex(Tok);
if (Tok.is(tok::equal)) {
HasAlias = true;
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
<< "weak";
return;
}
AliasName = Tok;
PP.Lex(Tok);
}
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak";
return;
}
if (HasAlias) {
MutableArrayRef<Token> Toks(
PP.getPreprocessorAllocator().Allocate<Token>(3), 3);
Token &pragmaUnusedTok = Toks[0];
pragmaUnusedTok.startToken();
pragmaUnusedTok.setKind(tok::annot_pragma_weakalias);
pragmaUnusedTok.setLocation(WeakLoc);
pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation());
Toks[1] = WeakName;
Toks[2] = AliasName;
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
} else {
MutableArrayRef<Token> Toks(
PP.getPreprocessorAllocator().Allocate<Token>(2), 2);
Token &pragmaUnusedTok = Toks[0];
pragmaUnusedTok.startToken();
pragmaUnusedTok.setKind(tok::annot_pragma_weak);
pragmaUnusedTok.setLocation(WeakLoc);
pragmaUnusedTok.setAnnotationEndLoc(WeakLoc);
Toks[1] = WeakName;
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
}
// #pragma redefine_extname identifier identifier
void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &RedefToken) {
SourceLocation RedefLoc = RedefToken.getLocation();
Token Tok;
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
"redefine_extname";
return;
}
Token RedefName = Tok;
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
<< "redefine_extname";
return;
}
Token AliasName = Tok;
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
"redefine_extname";
return;
}
MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(3),
3);
Token &pragmaRedefTok = Toks[0];
pragmaRedefTok.startToken();
pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname);
pragmaRedefTok.setLocation(RedefLoc);
pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation());
Toks[1] = RedefName;
Toks[2] = AliasName;
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
void PragmaFPContractHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
tok::OnOffSwitch OOS;
if (PP.LexOnOffSwitch(OOS))
return;
MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_fp_contract);
Toks[0].setLocation(Tok.getLocation());
Toks[0].setAnnotationEndLoc(Tok.getLocation());
Toks[0].setAnnotationValue(reinterpret_cast<void*>(
static_cast<uintptr_t>(OOS)));
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
}
void PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
PP.LexUnexpandedToken(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
"OPENCL";
return;
}
IdentifierInfo *Ext = Tok.getIdentifierInfo();
SourceLocation NameLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::colon)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << Ext;
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate) << 0;
return;
}
IdentifierInfo *Pred = Tok.getIdentifierInfo();
OpenCLExtState State;
if (Pred->isStr("enable")) {
State = Enable;
} else if (Pred->isStr("disable")) {
State = Disable;
} else if (Pred->isStr("begin"))
State = Begin;
else if (Pred->isStr("end"))
State = End;
else {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate)
<< Ext->isStr("all");
return;
}
SourceLocation StateLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
"OPENCL EXTENSION";
return;
}
auto Info = PP.getPreprocessorAllocator().Allocate<OpenCLExtData>(1);
Info->first = Ext;
Info->second = State;
MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1);
Toks[0].startToken();
Toks[0].setKind(tok::annot_pragma_opencl_extension);
Toks[0].setLocation(NameLoc);
Toks[0].setAnnotationValue(static_cast<void*>(Info));
Toks[0].setAnnotationEndLoc(StateLoc);
PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
if (PP.getPPCallbacks())
PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext,
StateLoc, State);
}
/// Handle '#pragma omp ...' when OpenMP is disabled.
///
void PragmaNoOpenMPHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &FirstTok) {
if (!PP.getDiagnostics().isIgnored(diag::warn_pragma_omp_ignored,
FirstTok.getLocation())) {
PP.Diag(FirstTok, diag::warn_pragma_omp_ignored);
PP.getDiagnostics().setSeverity(diag::warn_pragma_omp_ignored,
diag::Severity::Ignored, SourceLocation());
}
PP.DiscardUntilEndOfDirective();
}
/// Handle '#pragma omp ...' when OpenMP is enabled.
///
void PragmaOpenMPHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &FirstTok) {
SmallVector<Token, 16> Pragma;
Token Tok;
Tok.startToken();
Tok.setKind(tok::annot_pragma_openmp);
Tok.setLocation(Introducer.Loc);
while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) {
Pragma.push_back(Tok);
PP.Lex(Tok);
if (Tok.is(tok::annot_pragma_openmp)) {
PP.Diag(Tok, diag::err_omp_unexpected_directive) << 0;
unsigned InnerPragmaCnt = 1;
while (InnerPragmaCnt != 0) {
PP.Lex(Tok);
if (Tok.is(tok::annot_pragma_openmp))
++InnerPragmaCnt;
else if (Tok.is(tok::annot_pragma_openmp_end))
--InnerPragmaCnt;
}
PP.Lex(Tok);
}
}
SourceLocation EodLoc = Tok.getLocation();
Tok.startToken();
Tok.setKind(tok::annot_pragma_openmp_end);
Tok.setLocation(EodLoc);
Pragma.push_back(Tok);
auto Toks = std::make_unique<Token[]>(Pragma.size());
std::copy(Pragma.begin(), Pragma.end(), Toks.get());
PP.EnterTokenStream(std::move(Toks), Pragma.size(),
/*DisableMacroExpansion=*/false, /*IsReinject=*/false);
}
/// Handle '#pragma pointers_to_members'
// The grammar for this pragma is as follows:
//
// <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance'
//
// #pragma pointers_to_members '(' 'best_case' ')'
// #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')'
// #pragma pointers_to_members '(' inheritance-model ')'
void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
SourceLocation PointersToMembersLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen)
<< "pointers_to_members";
return;
}
PP.Lex(Tok);
const IdentifierInfo *Arg = Tok.getIdentifierInfo();
if (!Arg) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
<< "pointers_to_members";
return;
}
PP.Lex(Tok);
LangOptions::PragmaMSPointersToMembersKind RepresentationMethod;
if (Arg->isStr("best_case")) {
RepresentationMethod = LangOptions::PPTMK_BestCase;
} else {
if (Arg->isStr("full_generality")) {
if (Tok.is(tok::comma)) {
PP.Lex(Tok);
Arg = Tok.getIdentifierInfo();
if (!Arg) {
PP.Diag(Tok.getLocation(),
diag::err_pragma_pointers_to_members_unknown_kind)
<< Tok.getKind() << /*OnlyInheritanceModels*/ 0;
return;
}
PP.Lex(Tok);
} else if (Tok.is(tok::r_paren)) {
// #pragma pointers_to_members(full_generality) implicitly specifies
// virtual_inheritance.
Arg = nullptr;
RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance;
} else {
PP.Diag(Tok.getLocation(), diag::err_expected_punc)
<< "full_generality";
return;
}
}
if (Arg) {
if (Arg->isStr("single_inheritance")) {
RepresentationMethod =
LangOptions::PPTMK_FullGeneralitySingleInheritance;
} else if (Arg->isStr("multiple_inheritance")) {
RepresentationMethod =
LangOptions::PPTMK_FullGeneralityMultipleInheritance;
} else if (Arg->isStr("virtual_inheritance")) {
RepresentationMethod =
LangOptions::PPTMK_FullGeneralityVirtualInheritance;
} else {
PP.Diag(Tok.getLocation(),
diag::err_pragma_pointers_to_members_unknown_kind)
<< Arg << /*HasPointerDeclaration*/ 1;
return;
}
}
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after)
<< (Arg ? Arg->getName() : "full_generality");
return;
}
SourceLocation EndLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "pointers_to_members";
return;
}
Token AnnotTok;
AnnotTok.startToken();
AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members);
AnnotTok.setLocation(PointersToMembersLoc);
AnnotTok.setAnnotationEndLoc(EndLoc);
AnnotTok.setAnnotationValue(
reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod)));
PP.EnterToken(AnnotTok, /*IsReinject=*/true);
}
/// Handle '#pragma vtordisp'
// The grammar for this pragma is as follows:
//
// <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' )
//
// #pragma vtordisp '(' ['push' ','] vtordisp-mode ')'
// #pragma vtordisp '(' 'pop' ')'
// #pragma vtordisp '(' ')'
void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer, Token &Tok) {
SourceLocation VtorDispLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp";
return;
}
PP.Lex(Tok);
Sema::PragmaMsStackAction Action = Sema::PSK_Set;
const IdentifierInfo *II = Tok.getIdentifierInfo();
if (II) {
if (II->isStr("push")) {
// #pragma vtordisp(push, mode)
PP.Lex(Tok);
if (Tok.isNot(tok::comma)) {
PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp";
return;
}
PP.Lex(Tok);
Action = Sema::PSK_Push_Set;
// not push, could be on/off
} else if (II->isStr("pop")) {
// #pragma vtordisp(pop)
PP.Lex(Tok);
Action = Sema::PSK_Pop;
}
// not push or pop, could be on/off
} else {
if (Tok.is(tok::r_paren)) {
// #pragma vtordisp()
Action = Sema::PSK_Reset;
}
}
uint64_t Value = 0;
if (Action & Sema::PSK_Push || Action & Sema::PSK_Set) {
const IdentifierInfo *II = Tok.getIdentifierInfo();
if (II && II->isStr("off")) {
PP.Lex(Tok);
Value = 0;
} else if (II && II->isStr("on")) {
PP.Lex(Tok);
Value = 1;
} else if (Tok.is(tok::numeric_constant) &&
PP.parseSimpleIntegerLiteral(Tok, Value)) {
if (Value > 2) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer)
<< 0 << 2 << "vtordisp";
return;
}
} else {
PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
<< "vtordisp";
return;
}
}
// Finish the pragma: ')' $
if (Tok.isNot(tok::r_paren)) {
PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp";
return;
}
SourceLocation EndLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "vtordisp";
return;
}
// Enter the annotation.
Token AnnotTok;
AnnotTok.startToken();
AnnotTok.setKind(tok::annot_pragma_ms_vtordisp);
AnnotTok.setLocation(VtorDispLoc);
AnnotTok.setAnnotationEndLoc(EndLoc);
AnnotTok.setAnnotationValue(reinterpret_cast<void *>(
static_cast<uintptr_t>((Action << 16) | (Value & 0xFFFF))));
PP.EnterToken(AnnotTok, /*IsReinject=*/false);
}
/// Handle all MS pragmas. Simply forwards the tokens after inserting
/// an annotation token.
void PragmaMSPragma::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer, Token &Tok) {
Token EoF, AnnotTok;
EoF.startToken();
EoF.setKind(tok::eof);
AnnotTok.startToken();
AnnotTok.setKind(tok::annot_pragma_ms_pragma);
AnnotTok.setLocation(Tok.getLocation());
AnnotTok.setAnnotationEndLoc(Tok.getLocation());
SmallVector<Token, 8> TokenVector;
// Suck up all of the tokens before the eod.
for (; Tok.isNot(tok::eod); PP.Lex(Tok)) {
TokenVector.push_back(Tok);
AnnotTok.setAnnotationEndLoc(Tok.getLocation());
}
// Add a sentinel EoF token to the end of the list.
TokenVector.push_back(EoF);
// We must allocate this array with new because EnterTokenStream is going to
// delete it later.
auto TokenArray = std::make_unique<Token[]>(TokenVector.size());
std::copy(TokenVector.begin(), TokenVector.end(), TokenArray.get());
auto Value = new (PP.getPreprocessorAllocator())
std::pair<std::unique_ptr<Token[]>, size_t>(std::move(TokenArray),
TokenVector.size());
AnnotTok.setAnnotationValue(Value);
PP.EnterToken(AnnotTok, /*IsReinject*/ false);
}
/// Handle the Microsoft \#pragma detect_mismatch extension.
///
/// The syntax is:
/// \code
/// #pragma detect_mismatch("name", "value")
/// \endcode
/// Where 'name' and 'value' are quoted strings. The values are embedded in
/// the object file and passed along to the linker. If the linker detects a
/// mismatch in the object file's values for the given name, a LNK2038 error
/// is emitted. See MSDN for more details.
void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
SourceLocation DetectMismatchLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(DetectMismatchLoc, diag::err_expected) << tok::l_paren;
return;
}
// Read the name to embed, which must be a string literal.
std::string NameString;
if (!PP.LexStringLiteral(Tok, NameString,
"pragma detect_mismatch",
/*AllowMacroExpansion=*/true))
return;
// Read the comma followed by a second string literal.
std::string ValueString;
if (Tok.isNot(tok::comma)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
return;
}
if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch",
/*AllowMacroExpansion=*/true))
return;
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
return;
}
PP.Lex(Tok); // Eat the r_paren.
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
return;
}
// If the pragma is lexically sound, notify any interested PPCallbacks.
if (PP.getPPCallbacks())
PP.getPPCallbacks()->PragmaDetectMismatch(DetectMismatchLoc, NameString,
ValueString);
Actions.ActOnPragmaDetectMismatch(DetectMismatchLoc, NameString, ValueString);
}
/// Handle the microsoft \#pragma comment extension.
///
/// The syntax is:
/// \code
/// #pragma comment(linker, "foo")
/// \endcode
/// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
/// "foo" is a string, which is fully macro expanded, and permits string
/// concatenation, embedded escape characters etc. See MSDN for more details.
void PragmaCommentHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
SourceLocation CommentLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
return;
}
// Read the identifier.
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
return;
}
// Verify that this is one of the 5 whitelisted options.
IdentifierInfo *II = Tok.getIdentifierInfo();
PragmaMSCommentKind Kind =
llvm::StringSwitch<PragmaMSCommentKind>(II->getName())
.Case("linker", PCK_Linker)
.Case("lib", PCK_Lib)
.Case("compiler", PCK_Compiler)
.Case("exestr", PCK_ExeStr)
.Case("user", PCK_User)
.Default(PCK_Unknown);
if (Kind == PCK_Unknown) {
PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
return;
}
if (PP.getTargetInfo().getTriple().isOSBinFormatELF() && Kind != PCK_Lib) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
<< II->getName();
return;
}
// On PS4, issue a warning about any pragma comments other than
// #pragma comment lib.
if (PP.getTargetInfo().getTriple().isPS4() && Kind != PCK_Lib) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
<< II->getName();
return;
}
// Read the optional string if present.
PP.Lex(Tok);
std::string ArgumentString;
if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString,
"pragma comment",
/*AllowMacroExpansion=*/true))
return;
// FIXME: warn that 'exestr' is deprecated.
// FIXME: If the kind is "compiler" warn if the string is present (it is
// ignored).
// The MSDN docs say that "lib" and "linker" require a string and have a short
// whitelist of linker options they support, but in practice MSVC doesn't
// issue a diagnostic. Therefore neither does clang.
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
return;
}
PP.Lex(Tok); // eat the r_paren.
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
return;
}
// If the pragma is lexically sound, notify any interested PPCallbacks.
if (PP.getPPCallbacks())
PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString);
Actions.ActOnPragmaMSComment(CommentLoc, Kind, ArgumentString);
}
// #pragma clang optimize off
// #pragma clang optimize on
void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &FirstToken) {
Token Tok;
PP.Lex(Tok);
if (Tok.is(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
<< "clang optimize" << /*Expected=*/true << "'on' or 'off'";
return;
}
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
<< PP.getSpelling(Tok);
return;
}
const IdentifierInfo *II = Tok.getIdentifierInfo();
// The only accepted values are 'on' or 'off'.
bool IsOn = false;
if (II->isStr("on")) {
IsOn = true;
} else if (!II->isStr("off")) {
PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
<< PP.getSpelling(Tok);
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument)
<< PP.getSpelling(Tok);
return;
}
Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
}
namespace {
/// Used as the annotation value for tok::annot_pragma_fp.
struct TokFPAnnotValue {
enum FlagKinds { Contract };
enum FlagValues { On, Off, Fast };
FlagKinds FlagKind;
FlagValues FlagValue;
};
} // end anonymous namespace
void PragmaFPHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer, Token &Tok) {
// fp
Token PragmaName = Tok;
SmallVector<Token, 1> TokenList;
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
<< /*MissingOption=*/true << "";
return;
}
while (Tok.is(tok::identifier)) {
IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
auto FlagKind =
llvm::StringSwitch<llvm::Optional<TokFPAnnotValue::FlagKinds>>(
OptionInfo->getName())
.Case("contract", TokFPAnnotValue::Contract)
.Default(None);
if (!FlagKind) {
PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
<< /*MissingOption=*/false << OptionInfo;
return;
}
PP.Lex(Tok);
// Read '('
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
<< PP.getSpelling(Tok) << OptionInfo->getName();
return;
}
const IdentifierInfo *II = Tok.getIdentifierInfo();
auto FlagValue =
llvm::StringSwitch<llvm::Optional<TokFPAnnotValue::FlagValues>>(
II->getName())
.Case("on", TokFPAnnotValue::On)
.Case("off", TokFPAnnotValue::Off)
.Case("fast", TokFPAnnotValue::Fast)
.Default(llvm::None);
if (!FlagValue) {
PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
<< PP.getSpelling(Tok) << OptionInfo->getName();
return;
}
PP.Lex(Tok);
// Read ')'
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
return;
}
PP.Lex(Tok);
auto *AnnotValue = new (PP.getPreprocessorAllocator())
TokFPAnnotValue{*FlagKind, *FlagValue};
// Generate the loop hint token.
Token FPTok;
FPTok.startToken();
FPTok.setKind(tok::annot_pragma_fp);
FPTok.setLocation(PragmaName.getLocation());
FPTok.setAnnotationEndLoc(PragmaName.getLocation());
FPTok.setAnnotationValue(reinterpret_cast<void *>(AnnotValue));
TokenList.push_back(FPTok);
}
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "clang fp";
return;
}
auto TokenArray = std::make_unique<Token[]>(TokenList.size());
std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
/*DisableMacroExpansion=*/false, /*IsReinject=*/false);
}
void Parser::HandlePragmaFP() {
assert(Tok.is(tok::annot_pragma_fp));
auto *AnnotValue =
reinterpret_cast<TokFPAnnotValue *>(Tok.getAnnotationValue());
LangOptions::FPContractModeKind FPC;
switch (AnnotValue->FlagValue) {
case TokFPAnnotValue::On:
FPC = LangOptions::FPC_On;
break;
case TokFPAnnotValue::Fast:
FPC = LangOptions::FPC_Fast;
break;
case TokFPAnnotValue::Off:
FPC = LangOptions::FPC_Off;
break;
}
Actions.ActOnPragmaFPContract(FPC);
ConsumeAnnotationToken();
}
/// Parses loop or unroll pragma hint value and fills in Info.
static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName,
Token Option, bool ValueInParens,
PragmaLoopHintInfo &Info) {
SmallVector<Token, 1> ValueList;
int OpenParens = ValueInParens ? 1 : 0;
// Read constant expression.
while (Tok.isNot(tok::eod)) {
if (Tok.is(tok::l_paren))
OpenParens++;
else if (Tok.is(tok::r_paren)) {
OpenParens--;
if (OpenParens == 0 && ValueInParens)
break;
}
ValueList.push_back(Tok);
PP.Lex(Tok);
}
if (ValueInParens) {
// Read ')'
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
return true;
}
PP.Lex(Tok);
}
Token EOFTok;
EOFTok.startToken();
EOFTok.setKind(tok::eof);
EOFTok.setLocation(Tok.getLocation());
ValueList.push_back(EOFTok); // Terminates expression for parsing.
Info.Toks = llvm::makeArrayRef(ValueList).copy(PP.getPreprocessorAllocator());
Info.PragmaName = PragmaName;
Info.Option = Option;
return false;
}
/// Handle the \#pragma clang loop directive.
/// #pragma clang 'loop' loop-hints
///
/// loop-hints:
/// loop-hint loop-hints[opt]
///
/// loop-hint:
/// 'vectorize' '(' loop-hint-keyword ')'
/// 'interleave' '(' loop-hint-keyword ')'
/// 'unroll' '(' unroll-hint-keyword ')'
/// 'vectorize_predicate' '(' loop-hint-keyword ')'
/// 'vectorize_width' '(' loop-hint-value ')'
/// 'interleave_count' '(' loop-hint-value ')'
/// 'unroll_count' '(' loop-hint-value ')'
/// 'pipeline' '(' disable ')'
/// 'pipeline_initiation_interval' '(' loop-hint-value ')'
///
/// loop-hint-keyword:
/// 'enable'
/// 'disable'
/// 'assume_safety'
///
/// unroll-hint-keyword:
/// 'enable'
/// 'disable'
/// 'full'
///
/// loop-hint-value:
/// constant-expression
///
/// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to
/// try vectorizing the instructions of the loop it precedes. Specifying
/// interleave(enable) or interleave_count(_value_) instructs llvm to try
/// interleaving multiple iterations of the loop it precedes. The width of the
/// vector instructions is specified by vectorize_width() and the number of
/// interleaved loop iterations is specified by interleave_count(). Specifying a
/// value of 1 effectively disables vectorization/interleaving, even if it is
/// possible and profitable, and 0 is invalid. The loop vectorizer currently
/// only works on inner loops.
///
/// The unroll and unroll_count directives control the concatenation
/// unroller. Specifying unroll(enable) instructs llvm to unroll the loop
/// completely if the trip count is known at compile time and unroll partially
/// if the trip count is not known. Specifying unroll(full) is similar to
/// unroll(enable) but will unroll the loop only if the trip count is known at
/// compile time. Specifying unroll(disable) disables unrolling for the
/// loop. Specifying unroll_count(_value_) instructs llvm to try to unroll the
/// loop the number of times indicated by the value.
void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
// Incoming token is "loop" from "#pragma clang loop".
Token PragmaName = Tok;
SmallVector<Token, 1> TokenList;
// Lex the optimization option and verify it is an identifier.
PP.Lex(Tok);
if (Tok.isNot(tok::identifier)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
<< /*MissingOption=*/true << "";
return;
}
while (Tok.is(tok::identifier)) {
Token Option = Tok;
IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName())
.Case("vectorize", true)
.Case("interleave", true)
.Case("unroll", true)
.Case("distribute", true)
.Case("vectorize_predicate", true)
.Case("vectorize_width", true)
.Case("interleave_count", true)
.Case("unroll_count", true)
.Case("pipeline", true)
.Case("pipeline_initiation_interval", true)
.Default(false);
if (!OptionValid) {
PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
<< /*MissingOption=*/false << OptionInfo;
return;
}
PP.Lex(Tok);
// Read '('
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
return;
}
PP.Lex(Tok);
auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true,
*Info))
return;
// Generate the loop hint token.
Token LoopHintTok;
LoopHintTok.startToken();
LoopHintTok.setKind(tok::annot_pragma_loop_hint);
LoopHintTok.setLocation(PragmaName.getLocation());
LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation());
LoopHintTok.setAnnotationValue(static_cast<void *>(Info));
TokenList.push_back(LoopHintTok);
}
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "clang loop";
return;
}
auto TokenArray = std::make_unique<Token[]>(TokenList.size());
std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
/*DisableMacroExpansion=*/false, /*IsReinject=*/false);
}
/// Handle the loop unroll optimization pragmas.
/// #pragma unroll
/// #pragma unroll unroll-hint-value
/// #pragma unroll '(' unroll-hint-value ')'
/// #pragma nounroll
/// #pragma unroll_and_jam
/// #pragma unroll_and_jam unroll-hint-value
/// #pragma unroll_and_jam '(' unroll-hint-value ')'
/// #pragma nounroll_and_jam
///
/// unroll-hint-value:
/// constant-expression
///
/// Loop unrolling hints can be specified with '#pragma unroll' or
/// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally
/// contained in parentheses. With no argument the directive instructs llvm to
/// try to unroll the loop completely. A positive integer argument can be
/// specified to indicate the number of times the loop should be unrolled. To
/// maximize compatibility with other compilers the unroll count argument can be
/// specified with or without parentheses. Specifying, '#pragma nounroll'
/// disables unrolling of the loop.
void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
// Incoming token is "unroll" for "#pragma unroll", or "nounroll" for
// "#pragma nounroll".
Token PragmaName = Tok;
PP.Lex(Tok);
auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
if (Tok.is(tok::eod)) {
// nounroll or unroll pragma without an argument.
Info->PragmaName = PragmaName;
Info->Option.startToken();
} else if (PragmaName.getIdentifierInfo()->getName() == "nounroll" ||
PragmaName.getIdentifierInfo()->getName() == "nounroll_and_jam") {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< PragmaName.getIdentifierInfo()->getName();
return;
} else {
// Unroll pragma with an argument: "#pragma unroll N" or
// "#pragma unroll(N)".
// Read '(' if it exists.
bool ValueInParens = Tok.is(tok::l_paren);
if (ValueInParens)
PP.Lex(Tok);
Token Option;
Option.startToken();
if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info))
return;
// In CUDA, the argument to '#pragma unroll' should not be contained in
// parentheses.
if (PP.getLangOpts().CUDA && ValueInParens)
PP.Diag(Info->Toks[0].getLocation(),
diag::warn_pragma_unroll_cuda_value_in_parens);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "unroll";
return;
}
}
// Generate the hint token.
auto TokenArray = std::make_unique<Token[]>(1);
TokenArray[0].startToken();
TokenArray[0].setKind(tok::annot_pragma_loop_hint);
TokenArray[0].setLocation(PragmaName.getLocation());
TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation());
TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
PP.EnterTokenStream(std::move(TokenArray), 1,
/*DisableMacroExpansion=*/false, /*IsReinject=*/false);
}
/// Handle the Microsoft \#pragma intrinsic extension.
///
/// The syntax is:
/// \code
/// #pragma intrinsic(memset)
/// #pragma intrinsic(strlen, memcpy)
/// \endcode
///
/// Pragma intrisic tells the compiler to use a builtin version of the
/// function. Clang does it anyway, so the pragma doesn't really do anything.
/// Anyway, we emit a warning if the function specified in \#pragma intrinsic
/// isn't an intrinsic in clang and suggest to include intrin.h.
void PragmaMSIntrinsicHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
<< "intrinsic";
return;
}
PP.Lex(Tok);
bool SuggestIntrinH = !PP.isMacroDefined("__INTRIN_H");
while (Tok.is(tok::identifier)) {
IdentifierInfo *II = Tok.getIdentifierInfo();
if (!II->getBuiltinID())
PP.Diag(Tok.getLocation(), diag::warn_pragma_intrinsic_builtin)
<< II << SuggestIntrinH;
PP.Lex(Tok);
if (Tok.isNot(tok::comma))
break;
PP.Lex(Tok);
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
<< "intrinsic";
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::eod))
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "intrinsic";
}
// #pragma optimize("gsty", on|off)
void PragmaMSOptimizeHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &Tok) {
SourceLocation StartLoc = Tok.getLocation();
PP.Lex(Tok);
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "optimize";
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::string_literal)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_string) << "optimize";
return;
}
// We could syntax check the string but it's probably not worth the effort.
PP.Lex(Tok);
if (Tok.isNot(tok::comma)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_comma) << "optimize";
return;
}
PP.Lex(Tok);
if (Tok.is(tok::eod) || Tok.is(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_missing_argument)
<< "optimize" << /*Expected=*/true << "'on' or 'off'";
return;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
if (!II || (!II->isStr("on") && !II->isStr("off"))) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_argument)
<< PP.getSpelling(Tok) << "optimize" << /*Expected=*/true
<< "'on' or 'off'";
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "optimize";
return;
}
PP.Lex(Tok);
if (Tok.isNot(tok::eod)) {
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "optimize";
return;
}
PP.Diag(StartLoc, diag::warn_pragma_optimize);
}
void PragmaForceCUDAHostDeviceHandler::HandlePragma(
Preprocessor &PP, PragmaIntroducer Introducer, Token &Tok) {
Token FirstTok = Tok;
PP.Lex(Tok);
IdentifierInfo *Info = Tok.getIdentifierInfo();
if (!Info || (!Info->isStr("begin") && !Info->isStr("end"))) {
PP.Diag(FirstTok.getLocation(),
diag::warn_pragma_force_cuda_host_device_bad_arg);
return;
}
if (Info->isStr("begin"))
Actions.PushForceCUDAHostDevice();
else if (!Actions.PopForceCUDAHostDevice())
PP.Diag(FirstTok.getLocation(),
diag::err_pragma_cannot_end_force_cuda_host_device);
PP.Lex(Tok);
if (!Tok.is(tok::eod))
PP.Diag(FirstTok.getLocation(),
diag::warn_pragma_force_cuda_host_device_bad_arg);
}
/// Handle the #pragma clang attribute directive.
///
/// The syntax is:
/// \code
/// #pragma clang attribute push (attribute, subject-set)
/// #pragma clang attribute push
/// #pragma clang attribute (attribute, subject-set)
/// #pragma clang attribute pop
/// \endcode
///
/// There are also 'namespace' variants of push and pop directives. The bare
/// '#pragma clang attribute (attribute, subject-set)' version doesn't require a
/// namespace, since it always applies attributes to the most recently pushed
/// group, regardless of namespace.
/// \code
/// #pragma clang attribute namespace.push (attribute, subject-set)
/// #pragma clang attribute namespace.push
/// #pragma clang attribute namespace.pop
/// \endcode
///
/// The subject-set clause defines the set of declarations which receive the
/// attribute. Its exact syntax is described in the LanguageExtensions document
/// in Clang's documentation.
///
/// This directive instructs the compiler to begin/finish applying the specified
/// attribute to the set of attribute-specific declarations in the active range
/// of the pragma.
void PragmaAttributeHandler::HandlePragma(Preprocessor &PP,
PragmaIntroducer Introducer,
Token &FirstToken) {
Token Tok;
PP.Lex(Tok);
auto *Info = new (PP.getPreprocessorAllocator())
PragmaAttributeInfo(AttributesForPragmaAttribute);
// Parse the optional namespace followed by a period.
if (Tok.is(tok::identifier)) {
IdentifierInfo *II = Tok.getIdentifierInfo();
if (!II->isStr("push") && !II->isStr("pop")) {
Info->Namespace = II;
PP.Lex(Tok);
if (!Tok.is(tok::period)) {
PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_period)
<< II;
return;
}
PP.Lex(Tok);
}
}
if (!Tok.isOneOf(tok::identifier, tok::l_paren)) {
PP.Diag(Tok.getLocation(),
diag::err_pragma_attribute_expected_push_pop_paren);
return;
}
// Determine what action this pragma clang attribute represents.
if (Tok.is(tok::l_paren)) {
if (Info->Namespace) {
PP.Diag(Tok.getLocation(),
diag::err_pragma_attribute_namespace_on_attribute);
PP.Diag(Tok.getLocation(),
diag::note_pragma_attribute_namespace_on_attribute);
return;
}
Info->Action = PragmaAttributeInfo::Attribute;
} else {
const IdentifierInfo *II = Tok.getIdentifierInfo();
if (II->isStr("push"))
Info->Action = PragmaAttributeInfo::Push;
else if (II->isStr("pop"))
Info->Action = PragmaAttributeInfo::Pop;
else {
PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_invalid_argument)
<< PP.getSpelling(Tok);
return;
}
PP.Lex(Tok);
}
// Parse the actual attribute.
if ((Info->Action == PragmaAttributeInfo::Push && Tok.isNot(tok::eod)) ||
Info->Action == PragmaAttributeInfo::Attribute) {
if (Tok.isNot(tok::l_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
return;
}
PP.Lex(Tok);
// Lex the attribute tokens.
SmallVector<Token, 16> AttributeTokens;
int OpenParens = 1;
while (Tok.isNot(tok::eod)) {
if (Tok.is(tok::l_paren))
OpenParens++;
else if (Tok.is(tok::r_paren)) {
OpenParens--;
if (OpenParens == 0)
break;
}
AttributeTokens.push_back(Tok);
PP.Lex(Tok);
}
if (AttributeTokens.empty()) {
PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_attribute);
return;
}
if (Tok.isNot(tok::r_paren)) {
PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
return;
}
SourceLocation EndLoc = Tok.getLocation();
PP.Lex(Tok);
// Terminate the attribute for parsing.
Token EOFTok;
EOFTok.startToken();
EOFTok.setKind(tok::eof);
EOFTok.setLocation(EndLoc);
AttributeTokens.push_back(EOFTok);
Info->Tokens =
llvm::makeArrayRef(AttributeTokens).copy(PP.getPreprocessorAllocator());
}
if (Tok.isNot(tok::eod))
PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
<< "clang attribute";
// Generate the annotated pragma token.
auto TokenArray = std::make_unique<Token[]>(1);
TokenArray[0].startToken();
TokenArray[0].setKind(tok::annot_pragma_attribute);
TokenArray[0].setLocation(FirstToken.getLocation());
TokenArray[0].setAnnotationEndLoc(FirstToken.getLocation());
TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
PP.EnterTokenStream(std::move(TokenArray), 1,
/*DisableMacroExpansion=*/false, /*IsReinject=*/false);
}
|