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
|
//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for declarations.
//
//===----------------------------------------------------------------------===//
#include "Sema.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Builtins.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "clang/Parse/DeclSpec.h"
#include "clang/Parse/Scope.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/SourceManager.h"
// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/HeaderSearch.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/DenseSet.h"
using namespace clang;
Sema::DeclTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
isa<ObjCInterfaceDecl>(IIDecl) ||
isa<TagDecl>(IIDecl)))
return IIDecl;
return 0;
}
void Sema::PushDeclContext(DeclContext *DC) {
assert( ( (isa<ObjCMethodDecl>(DC) && isa<TranslationUnitDecl>(CurContext))
|| DC->getParent() == CurContext ) &&
"The next DeclContext should be directly contained in the current one.");
CurContext = DC;
}
void Sema::PopDeclContext() {
assert(CurContext && "DeclContext imbalance!");
// If CurContext is a ObjC method, getParent() will return NULL.
CurContext = isa<ObjCMethodDecl>(CurContext)
? Context.getTranslationUnitDecl()
: CurContext->getParent();
}
/// Add this decl to the scope shadowed decl chains.
void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
S->AddDecl(D);
// C++ [basic.scope]p4:
// -- exactly one declaration shall declare a class name or
// enumeration name that is not a typedef name and the other
// declarations shall all refer to the same object or
// enumerator, or all refer to functions and function templates;
// in this case the class name or enumeration name is hidden.
if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
// We are pushing the name of a tag (enum or class).
IdentifierResolver::ctx_iterator
CIT = IdResolver.ctx_begin(TD->getIdentifier(), TD->getDeclContext());
if (CIT != IdResolver.ctx_end(TD->getIdentifier()) &&
IdResolver.isDeclInScope(*CIT, TD->getDeclContext(), S)) {
// There is already a declaration with the same name in the same
// scope. It must be found before we find the new declaration,
// so swap the order on the shadowed declaration chain.
IdResolver.AddShadowedDecl(TD, *CIT);
return;
}
}
IdResolver.AddDecl(D);
}
void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
if (S->decl_empty()) return;
assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
// We only want to remove the decls from the identifier decl chains for local
// scopes, when inside a function/method.
if (S->getFnParent() == 0)
return;
for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
I != E; ++I) {
Decl *TmpD = static_cast<Decl*>(*I);
assert(TmpD && "This decl didn't get pushed??");
ScopedDecl *D = dyn_cast<ScopedDecl>(TmpD);
assert(D && "This decl isn't a ScopedDecl?");
IdentifierInfo *II = D->getIdentifier();
if (!II) continue;
// Unlink this decl from the identifier.
IdResolver.RemoveDecl(D);
// This will have to be revisited for C++: there we want to nest stuff in
// namespace decls etc. Even for C, we might want a top-level translation
// unit decl or something.
if (!CurFunctionDecl)
continue;
// Chain this decl to the containing function, it now owns the memory for
// the decl.
D->setNext(CurFunctionDecl->getDeclChain());
CurFunctionDecl->setDeclChain(D);
}
}
/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
/// return 0 if one not found.
ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
// The third "scope" argument is 0 since we aren't enabling lazy built-in
// creation from this context.
Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
}
/// LookupDecl - Look up the inner-most declaration in the specified
/// namespace.
Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
Scope *S, bool enableLazyBuiltinCreation) {
if (II == 0) return 0;
unsigned NS = NSI;
if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
NS |= Decl::IDNS_Tag;
// Scan up the scope chain looking for a decl that matches this identifier
// that is in the appropriate namespace. This search should not take long, as
// shadowing of names is uncommon, and deep shadowing is extremely uncommon.
for (IdentifierResolver::iterator
I = IdResolver.begin(II, CurContext), E = IdResolver.end(II); I != E; ++I)
if ((*I)->getIdentifierNamespace() & NS)
return *I;
// If we didn't find a use of this identifier, and if the identifier
// corresponds to a compiler builtin, create the decl object for the builtin
// now, injecting it into translation unit scope, and return it.
if (NS & Decl::IDNS_Ordinary) {
if (enableLazyBuiltinCreation) {
// If this is a builtin on this (or all) targets, create the decl.
if (unsigned BuiltinID = II->getBuiltinID())
return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
}
if (getLangOptions().ObjC1) {
// @interface and @compatibility_alias introduce typedef-like names.
// Unlike typedef's, they can only be introduced at file-scope (and are
// therefore not scoped decls). They can, however, be shadowed by
// other names in IDNS_Ordinary.
ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
if (IDI != ObjCInterfaceDecls.end())
return IDI->second;
ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
if (I != ObjCAliasDecls.end())
return I->second->getClassInterface();
}
}
return 0;
}
void Sema::InitBuiltinVaListType() {
if (!Context.getBuiltinVaListType().isNull())
return;
IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
}
/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
/// lazily create a decl for it.
ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Scope *S) {
Builtin::ID BID = (Builtin::ID)bid;
if (BID == Builtin::BI__builtin_va_start ||
BID == Builtin::BI__builtin_va_copy ||
BID == Builtin::BI__builtin_va_end)
InitBuiltinVaListType();
QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
FunctionDecl *New = FunctionDecl::Create(Context,
Context.getTranslationUnitDecl(),
SourceLocation(), II, R,
FunctionDecl::Extern, false, 0);
// Create Decl objects for each parameter, adding them to the
// FunctionDecl.
if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
llvm::SmallVector<ParmVarDecl*, 16> Params;
for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
FT->getArgType(i), VarDecl::None, 0,
0));
New->setParams(&Params[0], Params.size());
}
// TUScope is the translation-unit scope to insert this function into.
PushOnScopeChains(New, TUScope);
return New;
}
/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
/// and scope as a previous declaration 'Old'. Figure out how to resolve this
/// situation, merging decls or emitting diagnostics as appropriate.
///
TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
// Verify the old decl was also a typedef.
TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind,
New->getName());
Diag(OldD->getLocation(), diag::err_previous_definition);
return New;
}
// Allow multiple definitions for ObjC built-in typedefs.
// FIXME: Verify the underlying types are equivalent!
if (getLangOptions().ObjC1 && isBuiltinObjCType(New))
return Old;
// Redeclaration of a type is a constraint violation (6.7.2.3p1).
// Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
// *either* declaration is in a system header. The code below implements
// this adhoc compatibility rule. FIXME: The following code will not
// work properly when compiling ".i" files (containing preprocessed output).
SourceManager &SrcMgr = Context.getSourceManager();
const FileEntry *OldDeclFile = SrcMgr.getFileEntryForLoc(Old->getLocation());
const FileEntry *NewDeclFile = SrcMgr.getFileEntryForLoc(New->getLocation());
HeaderSearch &HdrInfo = PP.getHeaderSearchInfo();
DirectoryLookup::DirType OldDirType = HdrInfo.getFileDirFlavor(OldDeclFile);
DirectoryLookup::DirType NewDirType = HdrInfo.getFileDirFlavor(NewDeclFile);
// Allow reclarations in both SystemHeaderDir and ExternCSystemHeaderDir.
if ((OldDirType != DirectoryLookup::NormalHeaderDir ||
NewDirType != DirectoryLookup::NormalHeaderDir) ||
getLangOptions().Microsoft)
return New;
// TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
// TODO: This is totally simplistic. It should handle merging functions
// together etc, merging extern int X; int X; ...
Diag(New->getLocation(), diag::err_redefinition, New->getName());
Diag(Old->getLocation(), diag::err_previous_definition);
return New;
}
/// DeclhasAttr - returns true if decl Declaration already has the target attribute.
static bool DeclHasAttr(const Decl *decl, const Attr *target) {
for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
if (attr->getKind() == target->getKind())
return true;
return false;
}
/// MergeAttributes - append attributes from the Old decl to the New one.
static void MergeAttributes(Decl *New, Decl *Old) {
Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
// FIXME: fix this code to cleanup the Old attrs correctly
while (attr) {
tmp = attr;
attr = attr->getNext();
if (!DeclHasAttr(New, tmp)) {
New->addAttr(tmp);
} else {
tmp->setNext(0);
delete(tmp);
}
}
}
/// MergeFunctionDecl - We just parsed a function 'New' from
/// declarator D which has the same name and scope as a previous
/// declaration 'Old'. Figure out how to resolve this situation,
/// merging decls or emitting diagnostics as appropriate.
/// Redeclaration will be set true if thisNew is a redeclaration OldD.
FunctionDecl *
Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Redeclaration = false;
// Verify the old decl was also a function.
FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind,
New->getName());
Diag(OldD->getLocation(), diag::err_previous_definition);
return New;
}
QualType OldQType = Context.getCanonicalType(Old->getType());
QualType NewQType = Context.getCanonicalType(New->getType());
// C++ [dcl.fct]p3:
// All declarations for a function shall agree exactly in both the
// return type and the parameter-type-list.
if (getLangOptions().CPlusPlus && OldQType == NewQType) {
MergeAttributes(New, Old);
Redeclaration = true;
return MergeCXXFunctionDecl(New, Old);
}
// C: Function types need to be compatible, not identical. This handles
// duplicate function decls like "void f(int); void f(enum X);" properly.
if (!getLangOptions().CPlusPlus &&
Context.functionTypesAreCompatible(OldQType, NewQType)) {
MergeAttributes(New, Old);
Redeclaration = true;
return New;
}
// A function that has already been declared has been redeclared or defined
// with a different type- show appropriate diagnostic
diag::kind PrevDiag;
if (Old->isThisDeclarationADefinition())
PrevDiag = diag::err_previous_definition;
else if (Old->isImplicit())
PrevDiag = diag::err_previous_implicit_declaration;
else
PrevDiag = diag::err_previous_declaration;
// TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
// TODO: This is totally simplistic. It should handle merging functions
// together etc, merging extern int X; int X; ...
Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
Diag(Old->getLocation(), PrevDiag);
return New;
}
/// equivalentArrayTypes - Used to determine whether two array types are
/// equivalent.
/// We need to check this explicitly as an incomplete array definition is
/// considered a VariableArrayType, so will not match a complete array
/// definition that would be otherwise equivalent.
static bool areEquivalentArrayTypes(QualType NewQType, QualType OldQType) {
const ArrayType *NewAT = NewQType->getAsArrayType();
const ArrayType *OldAT = OldQType->getAsArrayType();
if (!NewAT || !OldAT)
return false;
// If either (or both) array types in incomplete we need to strip off the
// outer VariableArrayType. Once the outer VAT is removed the remaining
// types must be identical if the array types are to be considered
// equivalent.
// eg. int[][1] and int[1][1] become
// VAT(null, CAT(1, int)) and CAT(1, CAT(1, int))
// removing the outermost VAT gives
// CAT(1, int) and CAT(1, int)
// which are equal, therefore the array types are equivalent.
if (NewAT->isIncompleteArrayType() || OldAT->isIncompleteArrayType()) {
if (NewAT->getIndexTypeQualifier() != OldAT->getIndexTypeQualifier())
return false;
NewQType = NewAT->getElementType().getCanonicalType();
OldQType = OldAT->getElementType().getCanonicalType();
}
return NewQType == OldQType;
}
/// MergeVarDecl - We just parsed a variable 'New' which has the same name
/// and scope as a previous declaration 'Old'. Figure out how to resolve this
/// situation, merging decls or emitting diagnostics as appropriate.
///
/// FIXME: Need to carefully consider tentative definition rules (C99 6.9.2p2).
/// For example, we incorrectly complain about i1, i4 from C99 6.9.2p4.
///
VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
// Verify the old decl was also a variable.
VarDecl *Old = dyn_cast<VarDecl>(OldD);
if (!Old) {
Diag(New->getLocation(), diag::err_redefinition_different_kind,
New->getName());
Diag(OldD->getLocation(), diag::err_previous_definition);
return New;
}
MergeAttributes(New, Old);
// Verify the types match.
QualType OldCType = Context.getCanonicalType(Old->getType());
QualType NewCType = Context.getCanonicalType(New->getType());
if (OldCType != NewCType && !areEquivalentArrayTypes(NewCType, OldCType)) {
Diag(New->getLocation(), diag::err_redefinition, New->getName());
Diag(Old->getLocation(), diag::err_previous_definition);
return New;
}
// C99 6.2.2p4: Check if we have a static decl followed by a non-static.
if (New->getStorageClass() == VarDecl::Static &&
(Old->getStorageClass() == VarDecl::None ||
Old->getStorageClass() == VarDecl::Extern)) {
Diag(New->getLocation(), diag::err_static_non_static, New->getName());
Diag(Old->getLocation(), diag::err_previous_definition);
return New;
}
// C99 6.2.2p4: Check if we have a non-static decl followed by a static.
if (New->getStorageClass() != VarDecl::Static &&
Old->getStorageClass() == VarDecl::Static) {
Diag(New->getLocation(), diag::err_non_static_static, New->getName());
Diag(Old->getLocation(), diag::err_previous_definition);
return New;
}
// We've verified the types match, now handle "tentative" definitions.
if (Old->isFileVarDecl() && New->isFileVarDecl()) {
// Handle C "tentative" external object definitions (C99 6.9.2).
bool OldIsTentative = false;
bool NewIsTentative = false;
if (!Old->getInit() &&
(Old->getStorageClass() == VarDecl::None ||
Old->getStorageClass() == VarDecl::Static))
OldIsTentative = true;
// FIXME: this check doesn't work (since the initializer hasn't been
// attached yet). This check should be moved to FinalizeDeclaratorGroup.
// Unfortunately, by the time we get to FinializeDeclaratorGroup, we've
// thrown out the old decl.
if (!New->getInit() &&
(New->getStorageClass() == VarDecl::None ||
New->getStorageClass() == VarDecl::Static))
; // change to NewIsTentative = true; once the code is moved.
if (NewIsTentative || OldIsTentative)
return New;
}
if (Old->getStorageClass() != VarDecl::Extern &&
New->getStorageClass() != VarDecl::Extern) {
Diag(New->getLocation(), diag::err_redefinition, New->getName());
Diag(Old->getLocation(), diag::err_previous_definition);
}
return New;
}
/// CheckParmsForFunctionDef - Check that the parameters of the given
/// function are appropriate for the definition of a function. This
/// takes care of any checks that cannot be performed on the
/// declaration itself, e.g., that the types of each of the function
/// parameters are complete.
bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
bool HasInvalidParm = false;
for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
ParmVarDecl *Param = FD->getParamDecl(p);
// C99 6.7.5.3p4: the parameters in a parameter type list in a
// function declarator that is part of a function definition of
// that function shall not have incomplete type.
if (Param->getType()->isIncompleteType() &&
!Param->isInvalidDecl()) {
Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
Param->getType().getAsString());
Param->setInvalidDecl();
HasInvalidParm = true;
}
}
return HasInvalidParm;
}
/// CreateImplicitParameter - Creates an implicit function parameter
/// in the scope S and with the given type. This routine is used, for
/// example, to create the implicit "self" parameter in an Objective-C
/// method.
ParmVarDecl *
Sema::CreateImplicitParameter(Scope *S, IdentifierInfo *Id,
SourceLocation IdLoc, QualType Type) {
ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, IdLoc, Id, Type,
VarDecl::None, 0, 0);
if (Id)
PushOnScopeChains(New, S);
return New;
}
/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
/// no declarator (e.g. "struct foo;") is parsed.
Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
// TODO: emit error on 'int;' or 'const enum foo;'.
// TODO: emit error on 'typedef int;'
// if (!DS.isMissingDeclaratorOk()) Diag(...);
return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
}
bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
// Get the type before calling CheckSingleAssignmentConstraints(), since
// it can promote the expression.
QualType InitType = Init->getType();
AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
InitType, Init, "initializing");
}
bool Sema::CheckInitExpr(Expr *expr, InitListExpr *IList, unsigned slot,
QualType ElementType) {
Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
if (CheckSingleInitializer(expr, ElementType))
return true; // types weren't compatible.
if (savExpr != expr) // The type was promoted, update initializer list.
IList->setInit(slot, expr);
return false;
}
bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
if (const IncompleteArrayType *IAT = DeclT->getAsIncompleteArrayType()) {
// C99 6.7.8p14. We have an array of character type with unknown size
// being initialized to a string literal.
llvm::APSInt ConstVal(32);
ConstVal = strLiteral->getByteLength() + 1;
// Return a new array type (C99 6.7.8p22).
DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
ArrayType::Normal, 0);
} else if (const ConstantArrayType *CAT = DeclT->getAsConstantArrayType()) {
// C99 6.7.8p14. We have an array of character type with known size.
if (strLiteral->getByteLength() > (unsigned)CAT->getMaximumElements())
Diag(strLiteral->getSourceRange().getBegin(),
diag::warn_initializer_string_for_char_array_too_long,
strLiteral->getSourceRange());
} else {
assert(0 && "HandleStringLiteralInit(): Invalid array type");
}
// Set type from "char *" to "constant array of char".
strLiteral->setType(DeclT);
// For now, we always return false (meaning success).
return false;
}
StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
const ArrayType *AT = DeclType->getAsArrayType();
if (AT && AT->getElementType()->isCharType()) {
return dyn_cast<StringLiteral>(Init);
}
return 0;
}
// CheckInitializerListTypes - Checks the types of elements of an initializer
// list. This function is recursive: it calls itself to initialize subelements
// of aggregate types. Note that the topLevel parameter essentially refers to
// whether this expression "owns" the initializer list passed in, or if this
// initialization is taking elements out of a parent initializer. Each
// call to this function adds zero or more to startIndex, reports any errors,
// and returns true if it found any inconsistent types.
bool Sema::CheckInitializerListTypes(InitListExpr*& IList, QualType &DeclType,
bool topLevel, unsigned& startIndex) {
bool hadError = false;
if (DeclType->isScalarType()) {
// The simplest case: initializing a single scalar
if (topLevel) {
Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init,
IList->getSourceRange());
}
if (startIndex < IList->getNumInits()) {
Expr* expr = IList->getInit(startIndex);
if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
// FIXME: Should an error be reported here instead?
unsigned newIndex = 0;
CheckInitializerListTypes(SubInitList, DeclType, true, newIndex);
} else {
hadError |= CheckInitExpr(expr, IList, startIndex, DeclType);
}
++startIndex;
}
// FIXME: Should an error be reported for empty initializer list + scalar?
} else if (DeclType->isVectorType()) {
if (startIndex < IList->getNumInits()) {
const VectorType *VT = DeclType->getAsVectorType();
int maxElements = VT->getNumElements();
QualType elementType = VT->getElementType();
for (int i = 0; i < maxElements; ++i) {
// Don't attempt to go past the end of the init list
if (startIndex >= IList->getNumInits())
break;
Expr* expr = IList->getInit(startIndex);
if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
unsigned newIndex = 0;
hadError |= CheckInitializerListTypes(SubInitList, elementType,
true, newIndex);
++startIndex;
} else {
hadError |= CheckInitializerListTypes(IList, elementType,
false, startIndex);
}
}
}
} else if (DeclType->isAggregateType() || DeclType->isUnionType()) {
if (DeclType->isStructureType() || DeclType->isUnionType()) {
if (startIndex < IList->getNumInits() && !topLevel &&
Context.typesAreCompatible(IList->getInit(startIndex)->getType(),
DeclType)) {
// We found a compatible struct; per the standard, this initializes the
// struct. (The C standard technically says that this only applies for
// initializers for declarations with automatic scope; however, this
// construct is unambiguous anyway because a struct cannot contain
// a type compatible with itself. We'll output an error when we check
// if the initializer is constant.)
// FIXME: Is a call to CheckSingleInitializer required here?
++startIndex;
} else {
RecordDecl* structDecl = DeclType->getAsRecordType()->getDecl();
// If the record is invalid, some of it's members are invalid. To avoid
// confusion, we forgo checking the intializer for the entire record.
if (structDecl->isInvalidDecl())
return true;
// If structDecl is a forward declaration, this loop won't do anything;
// That's okay, because an error should get printed out elsewhere. It
// might be worthwhile to skip over the rest of the initializer, though.
int numMembers = structDecl->getNumMembers() -
structDecl->hasFlexibleArrayMember();
for (int i = 0; i < numMembers; i++) {
// Don't attempt to go past the end of the init list
if (startIndex >= IList->getNumInits())
break;
FieldDecl * curField = structDecl->getMember(i);
if (!curField->getIdentifier()) {
// Don't initialize unnamed fields, e.g. "int : 20;"
continue;
}
QualType fieldType = curField->getType();
Expr* expr = IList->getInit(startIndex);
if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
unsigned newStart = 0;
hadError |= CheckInitializerListTypes(SubInitList, fieldType,
true, newStart);
++startIndex;
} else {
hadError |= CheckInitializerListTypes(IList, fieldType,
false, startIndex);
}
if (DeclType->isUnionType())
break;
}
// FIXME: Implement flexible array initialization GCC extension (it's a
// really messy extension to implement, unfortunately...the necessary
// information isn't actually even here!)
}
} else if (DeclType->isArrayType()) {
// Check for the special-case of initializing an array with a string.
if (startIndex < IList->getNumInits()) {
if (StringLiteral *lit = IsStringLiteralInit(IList->getInit(startIndex),
DeclType)) {
CheckStringLiteralInit(lit, DeclType);
++startIndex;
if (topLevel && startIndex < IList->getNumInits()) {
// We have leftover initializers; warn
Diag(IList->getInit(startIndex)->getLocStart(),
diag::err_excess_initializers_in_char_array_initializer,
IList->getInit(startIndex)->getSourceRange());
}
return false;
}
}
int maxElements;
if (DeclType->isIncompleteArrayType()) {
// FIXME: use a proper constant
maxElements = 0x7FFFFFFF;
} else if (const VariableArrayType *VAT =
DeclType->getAsVariableArrayType()) {
// Check for VLAs; in standard C it would be possible to check this
// earlier, but I don't know where clang accepts VLAs (gcc accepts
// them in all sorts of strange places).
Diag(VAT->getSizeExpr()->getLocStart(),
diag::err_variable_object_no_init,
VAT->getSizeExpr()->getSourceRange());
hadError = true;
maxElements = 0x7FFFFFFF;
} else {
const ConstantArrayType *CAT = DeclType->getAsConstantArrayType();
maxElements = static_cast<int>(CAT->getSize().getZExtValue());
}
QualType elementType = DeclType->getAsArrayType()->getElementType();
int numElements = 0;
for (int i = 0; i < maxElements; ++i, ++numElements) {
// Don't attempt to go past the end of the init list
if (startIndex >= IList->getNumInits())
break;
Expr* expr = IList->getInit(startIndex);
if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
unsigned newIndex = 0;
hadError |= CheckInitializerListTypes(SubInitList, elementType,
true, newIndex);
++startIndex;
} else {
hadError |= CheckInitializerListTypes(IList, elementType,
false, startIndex);
}
}
if (DeclType->isIncompleteArrayType()) {
// If this is an incomplete array type, the actual type needs to
// be calculated here
if (numElements == 0) {
// Sizing an array implicitly to zero is not allowed
// (It could in theory be allowed, but it doesn't really matter.)
Diag(IList->getLocStart(),
diag::err_at_least_one_initializer_needed_to_size_array);
hadError = true;
} else {
llvm::APSInt ConstVal(32);
ConstVal = numElements;
DeclType = Context.getConstantArrayType(elementType, ConstVal,
ArrayType::Normal, 0);
}
}
} else {
assert(0 && "Aggregate that isn't a function or array?!");
}
} else {
// In C, all types are either scalars or aggregates, but
// additional handling is needed here for C++ (and possibly others?).
assert(0 && "Unsupported initializer type");
}
// If this init list is a base list, we set the type; an initializer doesn't
// fundamentally have a type, but this makes the ASTs a bit easier to read
if (topLevel)
IList->setType(DeclType);
if (topLevel && startIndex < IList->getNumInits()) {
// We have leftover initializers; warn
Diag(IList->getInit(startIndex)->getLocStart(),
diag::warn_excess_initializers,
IList->getInit(startIndex)->getSourceRange());
}
return hadError;
}
bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
// C99 6.7.8p3: The type of the entity to be initialized shall be an array
// of unknown size ("[]") or an object type that is not a variable array type.
if (const VariableArrayType *VAT = DeclType->getAsVariableArrayType())
return Diag(VAT->getSizeExpr()->getLocStart(),
diag::err_variable_object_no_init,
VAT->getSizeExpr()->getSourceRange());
InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
if (!InitList) {
// FIXME: Handle wide strings
if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
return CheckStringLiteralInit(strLiteral, DeclType);
if (DeclType->isArrayType())
return Diag(Init->getLocStart(),
diag::err_array_init_list_required,
Init->getSourceRange());
return CheckSingleInitializer(Init, DeclType);
}
#if 1
unsigned newIndex = 0;
return CheckInitializerListTypes(InitList, DeclType, true, newIndex);
#else
InitListChecker CheckInitList(this, InitList, DeclType);
return CheckInitList.HadError();
#endif
}
Sema::DeclTy *
Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
IdentifierInfo *II = D.getIdentifier();
// All of these full declarators require an identifier. If it doesn't have
// one, the ParsedFreeStandingDeclSpec action should be used.
if (II == 0) {
Diag(D.getDeclSpec().getSourceRange().getBegin(),
diag::err_declarator_need_ident,
D.getDeclSpec().getSourceRange(), D.getSourceRange());
return 0;
}
// The scope passed in may not be a decl scope. Zip up the scope tree until
// we find one that is.
while ((S->getFlags() & Scope::DeclScope) == 0)
S = S->getParent();
// See if this is a redefinition of a variable in the same scope.
Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
ScopedDecl *New;
bool InvalidDecl = false;
// In C++, the previous declaration we find might be a tag type
// (class or enum). In this case, the new declaration will hide the
// tag type.
if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
PrevDecl = 0;
QualType R = GetTypeForDeclarator(D, S);
assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
// Check that there are no default arguments (C++ only).
if (getLangOptions().CPlusPlus)
CheckExtraCXXDefaultArguments(D);
TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
if (!NewTD) return 0;
// Handle attributes prior to checking for duplicates in MergeVarDecl
HandleDeclAttributes(NewTD, D.getDeclSpec().getAttributes(),
D.getAttributes());
// Merge the decl with the existing one if appropriate. If the decl is
// in an outer scope, it isn't the same thing.
if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
if (NewTD == 0) return 0;
}
New = NewTD;
if (S->getFnParent() == 0) {
// C99 6.7.7p2: If a typedef name specifies a variably modified type
// then it shall have block scope.
if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
// FIXME: Diagnostic needs to be fixed.
Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
InvalidDecl = true;
}
}
} else if (R.getTypePtr()->isFunctionType()) {
FunctionDecl::StorageClass SC = FunctionDecl::None;
switch (D.getDeclSpec().getStorageClassSpec()) {
default: assert(0 && "Unknown storage class!");
case DeclSpec::SCS_auto:
case DeclSpec::SCS_register:
Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
R.getAsString());
InvalidDecl = true;
break;
case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
}
bool isInline = D.getDeclSpec().isInlineSpecified();
FunctionDecl *NewFD = FunctionDecl::Create(Context, CurContext,
D.getIdentifierLoc(),
II, R, SC, isInline,
LastDeclarator);
// Handle attributes.
HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
D.getAttributes());
// Copy the parameter declarations from the declarator D to
// the function declaration NewFD, if they are available.
if (D.getNumTypeObjects() > 0 &&
D.getTypeObject(0).Fun.hasPrototype) {
DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
// Create Decl objects for each parameter, adding them to the
// FunctionDecl.
llvm::SmallVector<ParmVarDecl*, 16> Params;
// Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
// function that takes no arguments, not a function that takes a
// single void argument.
if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
FTI.ArgInfo[0].Param &&
!((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
// empty arg list, don't push any params.
ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
// In C++, the empty parameter-type-list must be spelled "void"; a
// typedef of void is not permitted.
if (getLangOptions().CPlusPlus &&
Param->getType() != Context.VoidTy) {
Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
}
} else {
for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
}
NewFD->setParams(&Params[0], Params.size());
}
// Merge the decl with the existing one if appropriate. Since C functions
// are in a flat namespace, make sure we consider decls in outer scopes.
if (PrevDecl &&
(!getLangOptions().CPlusPlus ||
IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
bool Redeclaration = false;
NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
if (NewFD == 0) return 0;
if (Redeclaration) {
// Note that the new declaration is a redeclaration of the
// older declaration. Then return the older declaration: the
// new one is only kept within the set of previous
// declarations for this function.
FunctionDecl *OldFD = (FunctionDecl *)PrevDecl;
OldFD->AddRedeclaration(NewFD);
return OldFD;
}
}
New = NewFD;
// In C++, check default arguments now that we have merged decls.
if (getLangOptions().CPlusPlus)
CheckCXXDefaultArguments(NewFD);
} else {
// Check that there are no default arguments (C++ only).
if (getLangOptions().CPlusPlus)
CheckExtraCXXDefaultArguments(D);
if (R.getTypePtr()->isObjCInterfaceType()) {
Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
D.getIdentifier()->getName());
InvalidDecl = true;
}
VarDecl *NewVD;
VarDecl::StorageClass SC;
switch (D.getDeclSpec().getStorageClassSpec()) {
default: assert(0 && "Unknown storage class!");
case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
case DeclSpec::SCS_static: SC = VarDecl::Static; break;
case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
case DeclSpec::SCS_register: SC = VarDecl::Register; break;
case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
}
if (S->getFnParent() == 0) {
// C99 6.9p2: The storage-class specifiers auto and register shall not
// appear in the declaration specifiers in an external declaration.
if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
R.getAsString());
InvalidDecl = true;
}
NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
II, R, SC, LastDeclarator);
} else {
NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
II, R, SC, LastDeclarator);
}
// Handle attributes prior to checking for duplicates in MergeVarDecl
HandleDeclAttributes(NewVD, D.getDeclSpec().getAttributes(),
D.getAttributes());
// Emit an error if an address space was applied to decl with local storage.
// This includes arrays of objects with address space qualifiers, but not
// automatic variables that point to other address spaces.
// ISO/IEC TR 18037 S5.1.2
if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
InvalidDecl = true;
}
// Merge the decl with the existing one if appropriate. If the decl is
// in an outer scope, it isn't the same thing.
if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
NewVD = MergeVarDecl(NewVD, PrevDecl);
if (NewVD == 0) return 0;
}
New = NewVD;
}
// If this has an identifier, add it to the scope stack.
if (II)
PushOnScopeChains(New, S);
// If any semantic error occurred, mark the decl as invalid.
if (D.getInvalidType() || InvalidDecl)
New->setInvalidDecl();
return New;
}
bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
SourceLocation loc;
// FIXME: Remove the isReference check and handle assignment to a reference.
if (!DclT->isReferenceType() && !Init->isConstantExpr(Context, &loc)) {
assert(loc.isValid() && "isConstantExpr didn't return a loc!");
Diag(loc, diag::err_init_element_not_constant, Init->getSourceRange());
return true;
}
return false;
}
void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Decl *RealDecl = static_cast<Decl *>(dcl);
Expr *Init = static_cast<Expr *>(init);
assert(Init && "missing initializer");
// If there is no declaration, there was an error parsing it. Just ignore
// the initializer.
if (RealDecl == 0) {
delete Init;
return;
}
VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
if (!VDecl) {
Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
diag::err_illegal_initializer);
RealDecl->setInvalidDecl();
return;
}
// Get the decls type and save a reference for later, since
// CheckInitializerTypes may change it.
QualType DclT = VDecl->getType(), SavT = DclT;
if (VDecl->isBlockVarDecl()) {
VarDecl::StorageClass SC = VDecl->getStorageClass();
if (SC == VarDecl::Extern) { // C99 6.7.8p5
Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
VDecl->setInvalidDecl();
} else if (!VDecl->isInvalidDecl()) {
if (CheckInitializerTypes(Init, DclT))
VDecl->setInvalidDecl();
if (SC == VarDecl::Static) // C99 6.7.8p4.
CheckForConstantInitializer(Init, DclT);
}
} else if (VDecl->isFileVarDecl()) {
if (VDecl->getStorageClass() == VarDecl::Extern)
Diag(VDecl->getLocation(), diag::warn_extern_init);
if (!VDecl->isInvalidDecl())
if (CheckInitializerTypes(Init, DclT))
VDecl->setInvalidDecl();
// C99 6.7.8p4. All file scoped initializers need to be constant.
CheckForConstantInitializer(Init, DclT);
}
// If the type changed, it means we had an incomplete type that was
// completed by the initializer. For example:
// int ary[] = { 1, 3, 5 };
// "ary" transitions from a VariableArrayType to a ConstantArrayType.
if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
VDecl->setType(DclT);
Init->setType(DclT);
}
// Attach the initializer to the decl.
VDecl->setInit(Init);
return;
}
/// The declarators are chained together backwards, reverse the list.
Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
// Often we have single declarators, handle them quickly.
Decl *GroupDecl = static_cast<Decl*>(group);
if (GroupDecl == 0)
return 0;
ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
ScopedDecl *NewGroup = 0;
if (Group->getNextDeclarator() == 0)
NewGroup = Group;
else { // reverse the list.
while (Group) {
ScopedDecl *Next = Group->getNextDeclarator();
Group->setNextDeclarator(NewGroup);
NewGroup = Group;
Group = Next;
}
}
// Perform semantic analysis that depends on having fully processed both
// the declarator and initializer.
for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
VarDecl *IDecl = dyn_cast<VarDecl>(ID);
if (!IDecl)
continue;
QualType T = IDecl->getType();
// C99 6.7.5.2p2: If an identifier is declared to be an object with
// static storage duration, it shall not have a variable length array.
if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
IDecl->getStorageClass() == VarDecl::Static) {
if (T->getAsVariableArrayType()) {
Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
IDecl->setInvalidDecl();
}
}
// Block scope. C99 6.7p7: If an identifier for an object is declared with
// no linkage (C99 6.2.2p6), the type for the object shall be complete...
if (IDecl->isBlockVarDecl() &&
IDecl->getStorageClass() != VarDecl::Extern) {
if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
T.getAsString());
IDecl->setInvalidDecl();
}
}
// File scope. C99 6.9.2p2: A declaration of an identifier for and
// object that has file scope without an initializer, and without a
// storage-class specifier or with the storage-class specifier "static",
// constitutes a tentative definition. Note: A tentative definition with
// external linkage is valid (C99 6.2.2p5).
if (IDecl && !IDecl->getInit() &&
(IDecl->getStorageClass() == VarDecl::Static ||
IDecl->getStorageClass() == VarDecl::None)) {
if (T->isIncompleteArrayType()) {
// C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
// array to be completed. Don't issue a diagnostic.
} else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
// C99 6.9.2p3: If the declaration of an identifier for an object is
// a tentative definition and has internal linkage (C99 6.2.2p3), the
// declared type shall not be an incomplete type.
Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
T.getAsString());
IDecl->setInvalidDecl();
}
}
}
return NewGroup;
}
/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
/// to introduce parameters into function prototype scope.
Sema::DeclTy *
Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
DeclSpec &DS = D.getDeclSpec();
// Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
DS.getStorageClassSpec() != DeclSpec::SCS_register) {
Diag(DS.getStorageClassSpecLoc(),
diag::err_invalid_storage_class_in_func_decl);
DS.ClearStorageClassSpecs();
}
if (DS.isThreadSpecified()) {
Diag(DS.getThreadSpecLoc(),
diag::err_invalid_storage_class_in_func_decl);
DS.ClearStorageClassSpecs();
}
// Check that there are no default arguments inside the type of this
// parameter (C++ only).
if (getLangOptions().CPlusPlus)
CheckExtraCXXDefaultArguments(D);
// In this context, we *do not* check D.getInvalidType(). If the declarator
// type was invalid, GetTypeForDeclarator() still returns a "valid" type,
// though it will not reflect the user specified type.
QualType parmDeclType = GetTypeForDeclarator(D, S);
assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
// TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
// Can this happen for params? We already checked that they don't conflict
// among each other. Here they can only shadow globals, which is ok.
IdentifierInfo *II = D.getIdentifier();
if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
if (S->isDeclScope(PrevDecl)) {
Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
dyn_cast<NamedDecl>(PrevDecl)->getName());
// Recover by removing the name
II = 0;
D.SetIdentifier(0, D.getIdentifierLoc());
}
}
// Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
// Doing the promotion here has a win and a loss. The win is the type for
// both Decl's and DeclRefExpr's will match (a convenient invariant for the
// code generator). The loss is the orginal type isn't preserved. For example:
//
// void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
// int blockvardecl[5];
// sizeof(parmvardecl); // size == 4
// sizeof(blockvardecl); // size == 20
// }
//
// For expressions, all implicit conversions are captured using the
// ImplicitCastExpr AST node (we have no such mechanism for Decl's).
//
// FIXME: If a source translation tool needs to see the original type, then
// we need to consider storing both types (in ParmVarDecl)...
//
if (parmDeclType->isArrayType()) {
// int x[restrict 4] -> int *restrict
parmDeclType = Context.getArrayDecayedType(parmDeclType);
} else if (parmDeclType->isFunctionType())
parmDeclType = Context.getPointerType(parmDeclType);
ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
D.getIdentifierLoc(), II,
parmDeclType, VarDecl::None,
0, 0);
if (D.getInvalidType())
New->setInvalidDecl();
if (II)
PushOnScopeChains(New, S);
HandleDeclAttributes(New, D.getDeclSpec().getAttributes(),
D.getAttributes());
return New;
}
Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
assert(CurFunctionDecl == 0 && "Function parsing confused");
assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
"Not a function declarator!");
DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
// Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
// for a K&R function.
if (!FTI.hasPrototype) {
for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
if (FTI.ArgInfo[i].Param == 0) {
Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
FTI.ArgInfo[i].Ident->getName());
// Implicitly declare the argument as type 'int' for lack of a better
// type.
DeclSpec DS;
const char* PrevSpec; // unused
DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
PrevSpec);
Declarator ParamD(DS, Declarator::KNRTypeListContext);
ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
}
}
// Since this is a function definition, act as though we have information
// about the arguments.
if (FTI.NumArgs)
FTI.hasPrototype = true;
} else {
// FIXME: Diagnose arguments without names in C.
}
Scope *GlobalScope = FnBodyScope->getParent();
// See if this is a redefinition.
Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
GlobalScope);
if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
const FunctionDecl *Definition;
if (FD->getBody(Definition)) {
Diag(D.getIdentifierLoc(), diag::err_redefinition,
D.getIdentifier()->getName());
Diag(Definition->getLocation(), diag::err_previous_definition);
}
}
}
Decl *decl = static_cast<Decl*>(ActOnDeclarator(GlobalScope, D, 0));
FunctionDecl *FD = cast<FunctionDecl>(decl);
CurFunctionDecl = FD;
PushDeclContext(FD);
// Check the validity of our function parameters
CheckParmsForFunctionDef(FD);
// Introduce our parameters into the function scope
for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
ParmVarDecl *Param = FD->getParamDecl(p);
// If this has an identifier, add it to the scope stack.
if (Param->getIdentifier())
PushOnScopeChains(Param, FnBodyScope);
}
return FD;
}
Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
Decl *dcl = static_cast<Decl *>(D);
if (FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
FD->setBody((Stmt*)Body);
assert(FD == CurFunctionDecl && "Function parsing confused");
CurFunctionDecl = 0;
} else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(dcl)) {
MD->setBody((Stmt*)Body);
CurMethodDecl = 0;
}
PopDeclContext();
// Verify and clean out per-function state.
// Check goto/label use.
for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
// Verify that we have no forward references left. If so, there was a goto
// or address of a label taken, but no definition of it. Label fwd
// definitions are indicated with a null substmt.
if (I->second->getSubStmt() == 0) {
LabelStmt *L = I->second;
// Emit error.
Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
// At this point, we have gotos that use the bogus label. Stitch it into
// the function body so that they aren't leaked and that the AST is well
// formed.
if (Body) {
L->setSubStmt(new NullStmt(L->getIdentLoc()));
cast<CompoundStmt>((Stmt*)Body)->push_back(L);
} else {
// The whole function wasn't parsed correctly, just delete this.
delete L;
}
}
}
LabelMap.clear();
return D;
}
/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
IdentifierInfo &II, Scope *S) {
// Extension in C99. Legal in C90, but warn about it.
if (getLangOptions().C99)
Diag(Loc, diag::ext_implicit_function_decl, II.getName());
else
Diag(Loc, diag::warn_implicit_function_decl, II.getName());
// FIXME: handle stuff like:
// void foo() { extern float X(); }
// void bar() { X(); } <-- implicit decl for X in another scope.
// Set a Declarator for the implicit definition: int foo();
const char *Dummy;
DeclSpec DS;
bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Error = Error; // Silence warning.
assert(!Error && "Error setting up implicit decl!");
Declarator D(DS, Declarator::BlockContext);
D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
D.SetIdentifier(&II, Loc);
// Insert this function into translation-unit scope.
DeclContext *PrevDC = CurContext;
CurContext = Context.getTranslationUnitDecl();
FunctionDecl *FD =
dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
FD->setImplicit();
CurContext = PrevDC;
return FD;
}
TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
ScopedDecl *LastDeclarator) {
assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
// Scope manipulation handled by caller.
TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
D.getIdentifierLoc(),
D.getIdentifier(),
T, LastDeclarator);
if (D.getInvalidType())
NewTD->setInvalidDecl();
return NewTD;
}
/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
/// former case, Name will be non-null. In the later case, Name will be null.
/// TagType indicates what kind of tag this is. TK indicates whether this is a
/// reference/declaration/definition of a tag.
Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
SourceLocation KWLoc, IdentifierInfo *Name,
SourceLocation NameLoc, AttributeList *Attr) {
// If this is a use of an existing tag, it must have a name.
assert((Name != 0 || TK == TK_Definition) &&
"Nameless record must be a definition!");
Decl::Kind Kind;
switch (TagType) {
default: assert(0 && "Unknown tag type!");
case DeclSpec::TST_struct: Kind = Decl::Struct; break;
case DeclSpec::TST_union: Kind = Decl::Union; break;
case DeclSpec::TST_class: Kind = Decl::Class; break;
case DeclSpec::TST_enum: Kind = Decl::Enum; break;
}
// If this is a named struct, check to see if there was a previous forward
// declaration or definition.
// Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
if (ScopedDecl *PrevDecl =
dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) {
assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
"unexpected Decl type");
if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
// If this is a use of a previous tag, or if the tag is already declared in
// the same scope (so that the definition/declaration completes or
// rementions the tag), reuse the decl.
if (TK == TK_Reference ||
IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
// Make sure that this wasn't declared as an enum and now used as a struct
// or something similar.
if (PrevDecl->getKind() != Kind) {
Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
Diag(PrevDecl->getLocation(), diag::err_previous_use);
}
// If this is a use or a forward declaration, we're good.
if (TK != TK_Definition)
return PrevDecl;
// Diagnose attempts to redefine a tag.
if (PrevTagDecl->isDefinition()) {
Diag(NameLoc, diag::err_redefinition, Name->getName());
Diag(PrevDecl->getLocation(), diag::err_previous_definition);
// If this is a redefinition, recover by making this struct be
// anonymous, which will make any later references get the previous
// definition.
Name = 0;
} else {
// Okay, this is definition of a previously declared or referenced tag.
// Move the location of the decl to be the definition site.
PrevDecl->setLocation(NameLoc);
return PrevDecl;
}
}
// If we get here, this is a definition of a new struct type in a nested
// scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
// type.
} else {
// The tag name clashes with a namespace name, issue an error and recover
// by making this tag be anonymous.
Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Name = 0;
}
}
// If there is an identifier, use the location of the identifier as the
// location of the decl, otherwise use the location of the struct/union
// keyword.
SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
// Otherwise, if this is the first time we've seen this tag, create the decl.
TagDecl *New;
switch (Kind) {
default: assert(0 && "Unknown tag kind!");
case Decl::Enum:
// FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
// enum X { A, B, C } D; D should chain to X.
New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
// If this is an undefined enum, warn.
if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
break;
case Decl::Union:
case Decl::Struct:
case Decl::Class:
// FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
// struct X { int A; } D; D should chain to X.
New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0);
break;
}
// If this has an identifier, add it to the scope stack.
if (Name) {
// The scope passed in may not be a decl scope. Zip up the scope tree until
// we find one that is.
while ((S->getFlags() & Scope::DeclScope) == 0)
S = S->getParent();
// Add it to the decl chain.
PushOnScopeChains(New, S);
}
HandleDeclAttributes(New, Attr, 0);
return New;
}
/// ActOnField - Each field of a struct/union/class is passed into this in order
/// to create a FieldDecl object for it.
Sema::DeclTy *Sema::ActOnField(Scope *S,
SourceLocation DeclStart,
Declarator &D, ExprTy *BitfieldWidth) {
IdentifierInfo *II = D.getIdentifier();
Expr *BitWidth = (Expr*)BitfieldWidth;
SourceLocation Loc = DeclStart;
if (II) Loc = D.getIdentifierLoc();
// FIXME: Unnamed fields can be handled in various different ways, for
// example, unnamed unions inject all members into the struct namespace!
if (BitWidth) {
// TODO: Validate.
//printf("WARNING: BITFIELDS IGNORED!\n");
// 6.7.2.1p3
// 6.7.2.1p4
} else {
// Not a bitfield.
// validate II.
}
QualType T = GetTypeForDeclarator(D, S);
assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
bool InvalidDecl = false;
// C99 6.7.2.1p8: A member of a structure or union may have any type other
// than a variably modified type.
if (T->isVariablyModifiedType()) {
// FIXME: This diagnostic needs work
Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
InvalidDecl = true;
}
// FIXME: Chain fielddecls together.
FieldDecl *NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
HandleDeclAttributes(NewFD, D.getDeclSpec().getAttributes(),
D.getAttributes());
if (D.getInvalidType() || InvalidDecl)
NewFD->setInvalidDecl();
return NewFD;
}
/// TranslateIvarVisibility - Translate visibility from a token ID to an
/// AST enum value.
static ObjCIvarDecl::AccessControl
TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
switch (ivarVisibility) {
case tok::objc_private: return ObjCIvarDecl::Private;
case tok::objc_public: return ObjCIvarDecl::Public;
case tok::objc_protected: return ObjCIvarDecl::Protected;
case tok::objc_package: return ObjCIvarDecl::Package;
default: assert(false && "Unknown visitibility kind");
}
}
/// ActOnIvar - Each ivar field of an objective-c class is passed into this
/// in order to create an IvarDecl object for it.
Sema::DeclTy *Sema::ActOnIvar(Scope *S,
SourceLocation DeclStart,
Declarator &D, ExprTy *BitfieldWidth,
tok::ObjCKeywordKind Visibility) {
IdentifierInfo *II = D.getIdentifier();
Expr *BitWidth = (Expr*)BitfieldWidth;
SourceLocation Loc = DeclStart;
if (II) Loc = D.getIdentifierLoc();
// FIXME: Unnamed fields can be handled in various different ways, for
// example, unnamed unions inject all members into the struct namespace!
if (BitWidth) {
// TODO: Validate.
//printf("WARNING: BITFIELDS IGNORED!\n");
// 6.7.2.1p3
// 6.7.2.1p4
} else {
// Not a bitfield.
// validate II.
}
QualType T = GetTypeForDeclarator(D, S);
assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
bool InvalidDecl = false;
// C99 6.7.2.1p8: A member of a structure or union may have any type other
// than a variably modified type.
if (T->isVariablyModifiedType()) {
// FIXME: This diagnostic needs work
Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
InvalidDecl = true;
}
ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T);
HandleDeclAttributes(NewID, D.getDeclSpec().getAttributes(),
D.getAttributes());
if (D.getInvalidType() || InvalidDecl)
NewID->setInvalidDecl();
// If we have visibility info, make sure the AST is set accordingly.
if (Visibility != tok::objc_not_keyword)
NewID->setAccessControl(TranslateIvarVisibility(Visibility));
return NewID;
}
void Sema::ActOnFields(Scope* S,
SourceLocation RecLoc, DeclTy *RecDecl,
DeclTy **Fields, unsigned NumFields,
SourceLocation LBrac, SourceLocation RBrac) {
Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
assert(EnclosingDecl && "missing record or interface decl");
RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
if (Record && Record->isDefinition()) {
// Diagnose code like:
// struct S { struct S {} X; };
// We discover this when we complete the outer S. Reject and ignore the
// outer S.
Diag(Record->getLocation(), diag::err_nested_redefinition,
Record->getKindName());
Diag(RecLoc, diag::err_previous_definition);
Record->setInvalidDecl();
return;
}
// Verify that all the fields are okay.
unsigned NumNamedMembers = 0;
llvm::SmallVector<FieldDecl*, 32> RecFields;
llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
for (unsigned i = 0; i != NumFields; ++i) {
FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
assert(FD && "missing field decl");
// Remember all fields.
RecFields.push_back(FD);
// Get the type for the field.
Type *FDTy = FD->getType().getTypePtr();
// C99 6.7.2.1p2 - A field may not be a function type.
if (FDTy->isFunctionType()) {
Diag(FD->getLocation(), diag::err_field_declared_as_function,
FD->getName());
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
// C99 6.7.2.1p2 - A field may not be an incomplete type except...
if (FDTy->isIncompleteType()) {
if (!Record) { // Incomplete ivar type is always an error.
Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
if (i != NumFields-1 || // ... that the last member ...
Record->getKind() != Decl::Struct || // ... of a structure ...
!FDTy->isArrayType()) { //... may have incomplete array type.
Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
if (NumNamedMembers < 1) { //... must have more than named member ...
Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
FD->getName());
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
// Okay, we have a legal flexible array member at the end of the struct.
if (Record)
Record->setHasFlexibleArrayMember(true);
}
/// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
/// field of another structure or the element of an array.
if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
// If this is a member of a union, then entire union becomes "flexible".
if (Record && Record->getKind() == Decl::Union) {
Record->setHasFlexibleArrayMember(true);
} else {
// If this is a struct/class and this is not the last element, reject
// it. Note that GCC supports variable sized arrays in the middle of
// structures.
if (i != NumFields-1) {
Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
FD->getName());
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
// We support flexible arrays at the end of structs in other structs
// as an extension.
Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
FD->getName());
if (Record)
Record->setHasFlexibleArrayMember(true);
}
}
}
/// A field cannot be an Objective-c object
if (FDTy->isObjCInterfaceType()) {
Diag(FD->getLocation(), diag::err_statically_allocated_object,
FD->getName());
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
// Keep track of the number of named members.
if (IdentifierInfo *II = FD->getIdentifier()) {
// Detect duplicate member names.
if (!FieldIDs.insert(II)) {
Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
// Find the previous decl.
SourceLocation PrevLoc;
for (unsigned i = 0, e = RecFields.size(); ; ++i) {
assert(i != e && "Didn't find previous def!");
if (RecFields[i]->getIdentifier() == II) {
PrevLoc = RecFields[i]->getLocation();
break;
}
}
Diag(PrevLoc, diag::err_previous_definition);
FD->setInvalidDecl();
EnclosingDecl->setInvalidDecl();
continue;
}
++NumNamedMembers;
}
}
// Okay, we successfully defined 'Record'.
if (Record) {
Record->defineBody(&RecFields[0], RecFields.size());
Consumer.HandleTagDeclDefinition(Record);
} else {
ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
else if (ObjCImplementationDecl *IMPDecl =
dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
}
}
}
Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
DeclTy *lastEnumConst,
SourceLocation IdLoc, IdentifierInfo *Id,
SourceLocation EqualLoc, ExprTy *val) {
EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
EnumConstantDecl *LastEnumConst =
cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
Expr *Val = static_cast<Expr*>(val);
// The scope passed in may not be a decl scope. Zip up the scope tree until
// we find one that is.
while ((S->getFlags() & Scope::DeclScope) == 0)
S = S->getParent();
// Verify that there isn't already something declared with this name in this
// scope.
if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
if (isa<EnumConstantDecl>(PrevDecl))
Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
else
Diag(IdLoc, diag::err_redefinition, Id->getName());
Diag(PrevDecl->getLocation(), diag::err_previous_definition);
delete Val;
return 0;
}
}
llvm::APSInt EnumVal(32);
QualType EltTy;
if (Val) {
// Make sure to promote the operand type to int.
UsualUnaryConversions(Val);
// C99 6.7.2.2p2: Make sure we have an integer constant expression.
SourceLocation ExpLoc;
if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
Id->getName());
delete Val;
Val = 0; // Just forget about it.
} else {
EltTy = Val->getType();
}
}
if (!Val) {
if (LastEnumConst) {
// Assign the last value + 1.
EnumVal = LastEnumConst->getInitVal();
++EnumVal;
// Check for overflow on increment.
if (EnumVal < LastEnumConst->getInitVal())
Diag(IdLoc, diag::warn_enum_value_overflow);
EltTy = LastEnumConst->getType();
} else {
// First value, set to zero.
EltTy = Context.IntTy;
EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
}
}
EnumConstantDecl *New =
EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Val, EnumVal,
LastEnumConst);
// Register this decl in the current scope stack.
PushOnScopeChains(New, S);
return New;
}
void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
DeclTy **Elements, unsigned NumElements) {
EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
assert(!Enum->isDefinition() && "Enum redefinitions can't reach here");
// TODO: If the result value doesn't fit in an int, it must be a long or long
// long value. ISO C does not support this, but GCC does as an extension,
// emit a warning.
unsigned IntWidth = Context.Target.getIntWidth();
// Verify that all the values are okay, compute the size of the values, and
// reverse the list.
unsigned NumNegativeBits = 0;
unsigned NumPositiveBits = 0;
// Keep track of whether all elements have type int.
bool AllElementsInt = true;
EnumConstantDecl *EltList = 0;
for (unsigned i = 0; i != NumElements; ++i) {
EnumConstantDecl *ECD =
cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
if (!ECD) continue; // Already issued a diagnostic.
// If the enum value doesn't fit in an int, emit an extension warning.
const llvm::APSInt &InitVal = ECD->getInitVal();
assert(InitVal.getBitWidth() >= IntWidth &&
"Should have promoted value to int");
if (InitVal.getBitWidth() > IntWidth) {
llvm::APSInt V(InitVal);
V.trunc(IntWidth);
V.extend(InitVal.getBitWidth());
if (V != InitVal)
Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
InitVal.toString());
}
// Keep track of the size of positive and negative values.
if (InitVal.isUnsigned() || InitVal.isNonNegative())
NumPositiveBits = std::max(NumPositiveBits,
(unsigned)InitVal.getActiveBits());
else
NumNegativeBits = std::max(NumNegativeBits,
(unsigned)InitVal.getMinSignedBits());
// Keep track of whether every enum element has type int (very commmon).
if (AllElementsInt)
AllElementsInt = ECD->getType() == Context.IntTy;
ECD->setNextDeclarator(EltList);
EltList = ECD;
}
// Figure out the type that should be used for this enum.
// FIXME: Support attribute(packed) on enums and -fshort-enums.
QualType BestType;
unsigned BestWidth;
if (NumNegativeBits) {
// If there is a negative value, figure out the smallest integer type (of
// int/long/longlong) that fits.
if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
BestType = Context.IntTy;
BestWidth = IntWidth;
} else {
BestWidth = Context.Target.getLongWidth();
if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
BestType = Context.LongTy;
else {
BestWidth = Context.Target.getLongLongWidth();
if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Diag(Enum->getLocation(), diag::warn_enum_too_large);
BestType = Context.LongLongTy;
}
}
} else {
// If there is no negative value, figure out which of uint, ulong, ulonglong
// fits.
if (NumPositiveBits <= IntWidth) {
BestType = Context.UnsignedIntTy;
BestWidth = IntWidth;
} else if (NumPositiveBits <=
(BestWidth = Context.Target.getLongWidth())) {
BestType = Context.UnsignedLongTy;
} else {
BestWidth = Context.Target.getLongLongWidth();
assert(NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?");
BestType = Context.UnsignedLongLongTy;
}
}
// Loop over all of the enumerator constants, changing their types to match
// the type of the enum if needed.
for (unsigned i = 0; i != NumElements; ++i) {
EnumConstantDecl *ECD =
cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
if (!ECD) continue; // Already issued a diagnostic.
// Standard C says the enumerators have int type, but we allow, as an
// extension, the enumerators to be larger than int size. If each
// enumerator value fits in an int, type it as an int, otherwise type it the
// same as the enumerator decl itself. This means that in "enum { X = 1U }"
// that X has type 'int', not 'unsigned'.
if (ECD->getType() == Context.IntTy) {
// Make sure the init value is signed.
llvm::APSInt IV = ECD->getInitVal();
IV.setIsSigned(true);
ECD->setInitVal(IV);
continue; // Already int type.
}
// Determine whether the value fits into an int.
llvm::APSInt InitVal = ECD->getInitVal();
bool FitsInInt;
if (InitVal.isUnsigned() || !InitVal.isNegative())
FitsInInt = InitVal.getActiveBits() < IntWidth;
else
FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
// If it fits into an integer type, force it. Otherwise force it to match
// the enum decl type.
QualType NewTy;
unsigned NewWidth;
bool NewSign;
if (FitsInInt) {
NewTy = Context.IntTy;
NewWidth = IntWidth;
NewSign = true;
} else if (ECD->getType() == BestType) {
// Already the right type!
continue;
} else {
NewTy = BestType;
NewWidth = BestWidth;
NewSign = BestType->isSignedIntegerType();
}
// Adjust the APSInt value.
InitVal.extOrTrunc(NewWidth);
InitVal.setIsSigned(NewSign);
ECD->setInitVal(InitVal);
// Adjust the Expr initializer and type.
ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
ECD->setType(NewTy);
}
Enum->defineElements(EltList, BestType);
Consumer.HandleTagDeclDefinition(Enum);
}
Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
ExprTy *expr) {
StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
return FileScopeAsmDecl::Create(Context, Loc, AsmString);
}
Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
SourceLocation LBrace,
SourceLocation RBrace,
const char *Lang,
unsigned StrSize,
DeclTy *D) {
LinkageSpecDecl::LanguageIDs Language;
Decl *dcl = static_cast<Decl *>(D);
if (strncmp(Lang, "\"C\"", StrSize) == 0)
Language = LinkageSpecDecl::lang_c;
else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
Language = LinkageSpecDecl::lang_cxx;
else {
Diag(Loc, diag::err_bad_language);
return 0;
}
// FIXME: Add all the various semantics of linkage specifications
return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
}
void Sema::HandleDeclAttribute(Decl *New, AttributeList *Attr) {
switch (Attr->getKind()) {
case AttributeList::AT_vector_size:
if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
QualType newType = HandleVectorTypeAttribute(vDecl->getType(), Attr);
if (!newType.isNull()) // install the new vector type into the decl
vDecl->setType(newType);
}
if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
QualType newType = HandleVectorTypeAttribute(tDecl->getUnderlyingType(),
Attr);
if (!newType.isNull()) // install the new vector type into the decl
tDecl->setUnderlyingType(newType);
}
break;
case AttributeList::AT_ext_vector_type:
if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New))
HandleExtVectorTypeAttribute(tDecl, Attr);
else
Diag(Attr->getLoc(),
diag::err_typecheck_ext_vector_not_typedef);
break;
case AttributeList::AT_address_space:
if (TypedefDecl *tDecl = dyn_cast<TypedefDecl>(New)) {
QualType newType = HandleAddressSpaceTypeAttribute(
tDecl->getUnderlyingType(),
Attr);
tDecl->setUnderlyingType(newType);
} else if (ValueDecl *vDecl = dyn_cast<ValueDecl>(New)) {
QualType newType = HandleAddressSpaceTypeAttribute(vDecl->getType(),
Attr);
// install the new addr spaced type into the decl
vDecl->setType(newType);
}
break;
case AttributeList::AT_deprecated:
HandleDeprecatedAttribute(New, Attr);
break;
case AttributeList::AT_visibility:
HandleVisibilityAttribute(New, Attr);
break;
case AttributeList::AT_weak:
HandleWeakAttribute(New, Attr);
break;
case AttributeList::AT_dllimport:
HandleDLLImportAttribute(New, Attr);
break;
case AttributeList::AT_dllexport:
HandleDLLExportAttribute(New, Attr);
break;
case AttributeList::AT_nothrow:
HandleNothrowAttribute(New, Attr);
break;
case AttributeList::AT_stdcall:
HandleStdCallAttribute(New, Attr);
break;
case AttributeList::AT_fastcall:
HandleFastCallAttribute(New, Attr);
break;
case AttributeList::AT_aligned:
HandleAlignedAttribute(New, Attr);
break;
case AttributeList::AT_packed:
HandlePackedAttribute(New, Attr);
break;
case AttributeList::AT_annotate:
HandleAnnotateAttribute(New, Attr);
break;
case AttributeList::AT_noreturn:
HandleNoReturnAttribute(New, Attr);
break;
case AttributeList::AT_format:
HandleFormatAttribute(New, Attr);
break;
case AttributeList::AT_transparent_union:
HandleTransparentUnionAttribute(New, Attr);
break;
default:
#if 0
// TODO: when we have the full set of attributes, warn about unknown ones.
Diag(Attr->getLoc(), diag::warn_attribute_ignored,
Attr->getName()->getName());
#endif
break;
}
}
void Sema::HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
AttributeList *declarator_postfix) {
while (declspec_prefix) {
HandleDeclAttribute(New, declspec_prefix);
declspec_prefix = declspec_prefix->getNext();
}
while (declarator_postfix) {
HandleDeclAttribute(New, declarator_postfix);
declarator_postfix = declarator_postfix->getNext();
}
}
void Sema::HandleExtVectorTypeAttribute(TypedefDecl *tDecl,
AttributeList *rawAttr) {
QualType curType = tDecl->getUnderlyingType();
// check the attribute arguments.
if (rawAttr->getNumArgs() != 1) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("1"));
return;
}
Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
llvm::APSInt vecSize(32);
if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
"ext_vector_type", sizeExpr->getSourceRange());
return;
}
// unlike gcc's vector_size attribute, we do not allow vectors to be defined
// in conjunction with complex types (pointers, arrays, functions, etc.).
Type *canonType = curType.getCanonicalType().getTypePtr();
if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
curType.getCanonicalType().getAsString());
return;
}
// unlike gcc's vector_size attribute, the size is specified as the
// number of elements, not the number of bytes.
unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
if (vectorSize == 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
sizeExpr->getSourceRange());
return;
}
// Instantiate/Install the vector type, the number of elements is > 0.
tDecl->setUnderlyingType(Context.getExtVectorType(curType, vectorSize));
// Remember this typedef decl, we will need it later for diagnostics.
ExtVectorDecls.push_back(tDecl);
}
QualType Sema::HandleVectorTypeAttribute(QualType curType,
AttributeList *rawAttr) {
// check the attribute arugments.
if (rawAttr->getNumArgs() != 1) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("1"));
return QualType();
}
Expr *sizeExpr = static_cast<Expr *>(rawAttr->getArg(0));
llvm::APSInt vecSize(32);
if (!sizeExpr->isIntegerConstantExpr(vecSize, Context)) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
"vector_size", sizeExpr->getSourceRange());
return QualType();
}
// navigate to the base type - we need to provide for vector pointers,
// vector arrays, and functions returning vectors.
Type *canonType = curType.getCanonicalType().getTypePtr();
if (canonType->isPointerType() || canonType->isArrayType() ||
canonType->isFunctionType()) {
assert(0 && "HandleVector(): Complex type construction unimplemented");
/* FIXME: rebuild the type from the inside out, vectorizing the inner type.
do {
if (PointerType *PT = dyn_cast<PointerType>(canonType))
canonType = PT->getPointeeType().getTypePtr();
else if (ArrayType *AT = dyn_cast<ArrayType>(canonType))
canonType = AT->getElementType().getTypePtr();
else if (FunctionType *FT = dyn_cast<FunctionType>(canonType))
canonType = FT->getResultType().getTypePtr();
} while (canonType->isPointerType() || canonType->isArrayType() ||
canonType->isFunctionType());
*/
}
// the base type must be integer or float.
if (!(canonType->isIntegerType() || canonType->isRealFloatingType())) {
Diag(rawAttr->getLoc(), diag::err_attribute_invalid_vector_type,
curType.getCanonicalType().getAsString());
return QualType();
}
unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(curType));
// vecSize is specified in bytes - convert to bits.
unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
// the vector size needs to be an integral multiple of the type size.
if (vectorSize % typeSize) {
Diag(rawAttr->getLoc(), diag::err_attribute_invalid_size,
sizeExpr->getSourceRange());
return QualType();
}
if (vectorSize == 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_zero_size,
sizeExpr->getSourceRange());
return QualType();
}
// Instantiate the vector type, the number of elements is > 0, and not
// required to be a power of 2, unlike GCC.
return Context.getVectorType(curType, vectorSize/typeSize);
}
void Sema::HandlePackedAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() > 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
if (TagDecl *TD = dyn_cast<TagDecl>(d))
TD->addAttr(new PackedAttr);
else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
// If the alignment is less than or equal to 8 bits, the packed attribute
// has no effect.
if (!FD->getType()->isIncompleteType() &&
Context.getTypeAlign(FD->getType()) <= 8)
Diag(rawAttr->getLoc(),
diag::warn_attribute_ignored_for_field_of_type,
rawAttr->getName()->getName(), FD->getType().getAsString());
else
FD->addAttr(new PackedAttr);
} else
Diag(rawAttr->getLoc(), diag::warn_attribute_ignored,
rawAttr->getName()->getName());
}
void Sema::HandleNoReturnAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
if (!Fn) {
Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
"noreturn", "function");
return;
}
d->addAttr(new NoReturnAttr());
}
void Sema::HandleDeprecatedAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
d->addAttr(new DeprecatedAttr());
}
void Sema::HandleVisibilityAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 1) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("1"));
return;
}
Expr *Arg = static_cast<Expr*>(rawAttr->getArg(0));
Arg = Arg->IgnoreParenCasts();
StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
if (Str == 0 || Str->isWide()) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
"visibility", std::string("1"));
return;
}
const char *TypeStr = Str->getStrData();
unsigned TypeLen = Str->getByteLength();
llvm::GlobalValue::VisibilityTypes type;
if (TypeLen == 7 && !memcmp(TypeStr, "default", 7))
type = llvm::GlobalValue::DefaultVisibility;
else if (TypeLen == 6 && !memcmp(TypeStr, "hidden", 6))
type = llvm::GlobalValue::HiddenVisibility;
else if (TypeLen == 8 && !memcmp(TypeStr, "internal", 8))
type = llvm::GlobalValue::HiddenVisibility; // FIXME
else if (TypeLen == 9 && !memcmp(TypeStr, "protected", 9))
type = llvm::GlobalValue::ProtectedVisibility;
else {
Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
"visibility", TypeStr);
return;
}
d->addAttr(new VisibilityAttr(type));
}
void Sema::HandleWeakAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
d->addAttr(new WeakAttr());
}
void Sema::HandleDLLImportAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
d->addAttr(new DLLImportAttr());
}
void Sema::HandleDLLExportAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
d->addAttr(new DLLExportAttr());
}
void Sema::HandleStdCallAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
d->addAttr(new StdCallAttr());
}
void Sema::HandleFastCallAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
d->addAttr(new FastCallAttr());
}
void Sema::HandleNothrowAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
d->addAttr(new NoThrowAttr());
}
static const FunctionTypeProto *getFunctionProto(Decl *d) {
QualType Ty;
if (ValueDecl *decl = dyn_cast<ValueDecl>(d))
Ty = decl->getType();
else if (FieldDecl *decl = dyn_cast<FieldDecl>(d))
Ty = decl->getType();
else if (TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
Ty = decl->getUnderlyingType();
else
return 0;
if (Ty->isFunctionPointerType()) {
const PointerType *PtrTy = Ty->getAsPointerType();
Ty = PtrTy->getPointeeType();
}
if (const FunctionType *FnTy = Ty->getAsFunctionType())
return dyn_cast<FunctionTypeProto>(FnTy->getAsFunctionType());
return 0;
}
static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
if (!T->isPointerType())
return false;
T = T->getAsPointerType()->getPointeeType().getCanonicalType();
ObjCInterfaceType* ClsT = dyn_cast<ObjCInterfaceType>(T.getTypePtr());
if (!ClsT)
return false;
IdentifierInfo* ClsName = ClsT->getDecl()->getIdentifier();
// FIXME: Should we walk the chain of classes?
return ClsName == &Ctx.Idents.get("NSString") ||
ClsName == &Ctx.Idents.get("NSMutableString");
}
/// Handle __attribute__((format(type,idx,firstarg))) attributes
/// based on http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
void Sema::HandleFormatAttribute(Decl *d, AttributeList *rawAttr) {
if (!rawAttr->getParameterName()) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_string,
"format", std::string("1"));
return;
}
if (rawAttr->getNumArgs() != 2) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("3"));
return;
}
// GCC ignores the format attribute on K&R style function
// prototypes, so we ignore it as well
const FunctionTypeProto *proto = getFunctionProto(d);
if (!proto) {
Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
"format", "function");
return;
}
// FIXME: in C++ the implicit 'this' function parameter also counts.
// this is needed in order to be compatible with GCC
// the index must start in 1 and the limit is numargs+1
unsigned NumArgs = proto->getNumArgs();
unsigned FirstIdx = 1;
const char *Format = rawAttr->getParameterName()->getName();
unsigned FormatLen = rawAttr->getParameterName()->getLength();
// Normalize the argument, __foo__ becomes foo.
if (FormatLen > 4 && Format[0] == '_' && Format[1] == '_' &&
Format[FormatLen - 2] == '_' && Format[FormatLen - 1] == '_') {
Format += 2;
FormatLen -= 4;
}
bool Supported = false;
bool is_NSString = false;
bool is_strftime = false;
switch (FormatLen) {
default: break;
case 5:
Supported = !memcmp(Format, "scanf", 5);
break;
case 6:
Supported = !memcmp(Format, "printf", 6);
break;
case 7:
Supported = !memcmp(Format, "strfmon", 7);
break;
case 8:
Supported = (is_strftime = !memcmp(Format, "strftime", 8)) ||
(is_NSString = !memcmp(Format, "NSString", 8));
break;
}
if (!Supported) {
Diag(rawAttr->getLoc(), diag::warn_attribute_type_not_supported,
"format", rawAttr->getParameterName()->getName());
return;
}
// checks for the 2nd argument
Expr *IdxExpr = static_cast<Expr *>(rawAttr->getArg(0));
llvm::APSInt Idx(Context.getTypeSize(IdxExpr->getType()));
if (!IdxExpr->isIntegerConstantExpr(Idx, Context)) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
"format", std::string("2"), IdxExpr->getSourceRange());
return;
}
if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
"format", std::string("2"), IdxExpr->getSourceRange());
return;
}
// FIXME: Do we need to bounds check?
unsigned ArgIdx = Idx.getZExtValue() - 1;
// make sure the format string is really a string
QualType Ty = proto->getArgType(ArgIdx);
if (is_NSString) {
// FIXME: do we need to check if the type is NSString*? What are
// the semantics?
if (!isNSStringType(Ty, Context)) {
// FIXME: Should highlight the actual expression that has the
// wrong type.
Diag(rawAttr->getLoc(), diag::err_format_attribute_not_NSString,
IdxExpr->getSourceRange());
return;
}
}
else if (!Ty->isPointerType() ||
!Ty->getAsPointerType()->getPointeeType()->isCharType()) {
// FIXME: Should highlight the actual expression that has the
// wrong type.
Diag(rawAttr->getLoc(), diag::err_format_attribute_not_string,
IdxExpr->getSourceRange());
return;
}
// check the 3rd argument
Expr *FirstArgExpr = static_cast<Expr *>(rawAttr->getArg(1));
llvm::APSInt FirstArg(Context.getTypeSize(FirstArgExpr->getType()));
if (!FirstArgExpr->isIntegerConstantExpr(FirstArg, Context)) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_n_not_int,
"format", std::string("3"), FirstArgExpr->getSourceRange());
return;
}
// check if the function is variadic if the 3rd argument non-zero
if (FirstArg != 0) {
if (proto->isVariadic()) {
++NumArgs; // +1 for ...
} else {
Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
return;
}
}
// strftime requires FirstArg to be 0 because it doesn't read from any variable
// the input is just the current time + the format string
if (is_strftime) {
if (FirstArg != 0) {
Diag(rawAttr->getLoc(), diag::err_format_strftime_third_parameter,
FirstArgExpr->getSourceRange());
return;
}
// if 0 it disables parameter checking (to use with e.g. va_list)
} else if (FirstArg != 0 && FirstArg != NumArgs) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_out_of_bounds,
"format", std::string("3"), FirstArgExpr->getSourceRange());
return;
}
d->addAttr(new FormatAttr(std::string(Format, FormatLen),
Idx.getZExtValue(), FirstArg.getZExtValue()));
}
void Sema::HandleTransparentUnionAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 0) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("0"));
return;
}
TypeDecl *decl = dyn_cast<TypeDecl>(d);
if (!decl || !Context.getTypeDeclType(decl)->isUnionType()) {
Diag(rawAttr->getLoc(), diag::warn_attribute_wrong_decl_type,
"transparent_union", "union");
return;
}
//QualType QTy = Context.getTypeDeclType(decl);
//const RecordType *Ty = QTy->getAsUnionType();
// FIXME
// Ty->addAttr(new TransparentUnionAttr());
}
void Sema::HandleAnnotateAttribute(Decl *d, AttributeList *rawAttr) {
// check the attribute arguments.
if (rawAttr->getNumArgs() != 1) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("1"));
return;
}
Expr *argExpr = static_cast<Expr *>(rawAttr->getArg(0));
StringLiteral *SE = dyn_cast<StringLiteral>(argExpr);
// Make sure that there is a string literal as the annotation's single
// argument.
if (!SE) {
Diag(rawAttr->getLoc(), diag::err_attribute_annotate_no_string);
return;
}
d->addAttr(new AnnotateAttr(std::string(SE->getStrData(),
SE->getByteLength())));
}
void Sema::HandleAlignedAttribute(Decl *d, AttributeList *rawAttr)
{
// check the attribute arguments.
if (rawAttr->getNumArgs() > 1) {
Diag(rawAttr->getLoc(), diag::err_attribute_wrong_number_arguments,
std::string("1"));
return;
}
unsigned Align = 0;
if (rawAttr->getNumArgs() == 0) {
// FIXME: This should be the target specific maximum alignment.
// (For now we just use 128 bits which is the maximum on X86.
Align = 128;
return;
} else {
Expr *alignmentExpr = static_cast<Expr *>(rawAttr->getArg(0));
llvm::APSInt alignment(32);
if (!alignmentExpr->isIntegerConstantExpr(alignment, Context)) {
Diag(rawAttr->getLoc(), diag::err_attribute_argument_not_int,
"aligned", alignmentExpr->getSourceRange());
return;
}
Align = alignment.getZExtValue() * 8;
}
d->addAttr(new AlignedAttr(Align));
}
|