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
|
//===----- SemaObjC.cpp ---- Semantic Analysis for Objective-C ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements semantic analysis for Objective-C.
///
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaObjC.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/EvaluatedExprVisitor.h"
#include "clang/AST/StmtObjC.h"
#include "clang/Basic/DiagnosticSema.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Attr.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedAttr.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/TemplateDeduction.h"
#include "llvm/Support/ConvertUTF.h"
namespace clang {
SemaObjC::SemaObjC(Sema &S)
: SemaBase(S), NSNumberDecl(nullptr), NSValueDecl(nullptr),
NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
DictionaryWithObjectsMethod(nullptr) {}
StmtResult SemaObjC::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc) {
ASTContext &Context = getASTContext();
SemaRef.setFunctionHasBranchProtectedScope();
ExprResult CollectionExprResult =
CheckObjCForCollectionOperand(ForLoc, collection);
if (First) {
QualType FirstType;
if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
if (!DS->isSingleDecl())
return StmtError(Diag((*DS->decl_begin())->getLocation(),
diag::err_toomany_element_decls));
VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
if (!D || D->isInvalidDecl())
return StmtError();
FirstType = D->getType();
// C99 6.8.5p3: The declaration part of a 'for' statement shall only
// declare identifiers for objects having storage class 'auto' or
// 'register'.
if (!D->hasLocalStorage())
return StmtError(
Diag(D->getLocation(), diag::err_non_local_variable_decl_in_for));
// If the type contained 'auto', deduce the 'auto' to 'id'.
if (FirstType->getContainedAutoType()) {
SourceLocation Loc = D->getLocation();
OpaqueValueExpr OpaqueId(Loc, Context.getObjCIdType(), VK_PRValue);
Expr *DeducedInit = &OpaqueId;
sema::TemplateDeductionInfo Info(Loc);
FirstType = QualType();
TemplateDeductionResult Result = SemaRef.DeduceAutoType(
D->getTypeSourceInfo()->getTypeLoc(), DeducedInit, FirstType, Info);
if (Result != TemplateDeductionResult::Success &&
Result != TemplateDeductionResult::AlreadyDiagnosed)
SemaRef.DiagnoseAutoDeductionFailure(D, DeducedInit);
if (FirstType.isNull()) {
D->setInvalidDecl();
return StmtError();
}
D->setType(FirstType);
if (!SemaRef.inTemplateInstantiation()) {
SourceLocation Loc =
D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
Diag(Loc, diag::warn_auto_var_is_id) << D->getDeclName();
}
}
} else {
Expr *FirstE = cast<Expr>(First);
if (!FirstE->isTypeDependent() && !FirstE->isLValue())
return StmtError(
Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
<< First->getSourceRange());
FirstType = static_cast<Expr *>(First)->getType();
if (FirstType.isConstQualified())
Diag(ForLoc, diag::err_selector_element_const_type)
<< FirstType << First->getSourceRange();
}
if (!FirstType->isDependentType() &&
!FirstType->isObjCObjectPointerType() &&
!FirstType->isBlockPointerType())
return StmtError(Diag(ForLoc, diag::err_selector_element_type)
<< FirstType << First->getSourceRange());
}
if (CollectionExprResult.isInvalid())
return StmtError();
CollectionExprResult = SemaRef.ActOnFinishFullExpr(CollectionExprResult.get(),
/*DiscardedValue*/ false);
if (CollectionExprResult.isInvalid())
return StmtError();
return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
nullptr, ForLoc, RParenLoc);
}
ExprResult SemaObjC::CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection) {
ASTContext &Context = getASTContext();
if (!collection)
return ExprError();
// Bail out early if we've got a type-dependent expression.
if (collection->isTypeDependent())
return collection;
// Perform normal l-value conversion.
ExprResult result = SemaRef.DefaultFunctionArrayLvalueConversion(collection);
if (result.isInvalid())
return ExprError();
collection = result.get();
// The operand needs to have object-pointer type.
// TODO: should we do a contextual conversion?
const ObjCObjectPointerType *pointerType =
collection->getType()->getAs<ObjCObjectPointerType>();
if (!pointerType)
return Diag(forLoc, diag::err_collection_expr_type)
<< collection->getType() << collection->getSourceRange();
// Check that the operand provides
// - countByEnumeratingWithState:objects:count:
const ObjCObjectType *objectType = pointerType->getObjectType();
ObjCInterfaceDecl *iface = objectType->getInterface();
// If we have a forward-declared type, we can't do this check.
// Under ARC, it is an error not to have a forward-declared class.
if (iface &&
(getLangOpts().ObjCAutoRefCount
? SemaRef.RequireCompleteType(forLoc, QualType(objectType, 0),
diag::err_arc_collection_forward,
collection)
: !SemaRef.isCompleteType(forLoc, QualType(objectType, 0)))) {
// Otherwise, if we have any useful type information, check that
// the type declares the appropriate method.
} else if (iface || !objectType->qual_empty()) {
const IdentifierInfo *selectorIdents[] = {
&Context.Idents.get("countByEnumeratingWithState"),
&Context.Idents.get("objects"), &Context.Idents.get("count")};
Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
ObjCMethodDecl *method = nullptr;
// If there's an interface, look in both the public and private APIs.
if (iface) {
method = iface->lookupInstanceMethod(selector);
if (!method)
method = iface->lookupPrivateMethod(selector);
}
// Also check protocol qualifiers.
if (!method)
method = LookupMethodInQualifiedType(selector, pointerType,
/*instance*/ true);
// If we didn't find it anywhere, give up.
if (!method) {
Diag(forLoc, diag::warn_collection_expr_type)
<< collection->getType() << selector << collection->getSourceRange();
}
// TODO: check for an incompatible signature?
}
// Wrap up any cleanups in the expression.
return collection;
}
StmtResult SemaObjC::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
if (!S || !B)
return StmtError();
ObjCForCollectionStmt *ForStmt = cast<ObjCForCollectionStmt>(S);
ForStmt->setBody(B);
return S;
}
StmtResult SemaObjC::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
SourceLocation RParen, Decl *Parm,
Stmt *Body) {
ASTContext &Context = getASTContext();
VarDecl *Var = cast_or_null<VarDecl>(Parm);
if (Var && Var->isInvalidDecl())
return StmtError();
return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
}
StmtResult SemaObjC::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
ASTContext &Context = getASTContext();
return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
}
StmtResult SemaObjC::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg CatchStmts,
Stmt *Finally) {
ASTContext &Context = getASTContext();
if (!getLangOpts().ObjCExceptions)
Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
// Objective-C try is incompatible with SEH __try.
sema::FunctionScopeInfo *FSI = SemaRef.getCurFunction();
if (FSI->FirstSEHTryLoc.isValid()) {
Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1;
Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
}
FSI->setHasObjCTry(AtLoc);
unsigned NumCatchStmts = CatchStmts.size();
return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
NumCatchStmts, Finally);
}
StmtResult SemaObjC::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
ASTContext &Context = getASTContext();
if (Throw) {
ExprResult Result = SemaRef.DefaultLvalueConversion(Throw);
if (Result.isInvalid())
return StmtError();
Result =
SemaRef.ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
if (Result.isInvalid())
return StmtError();
Throw = Result.get();
QualType ThrowType = Throw->getType();
// Make sure the expression type is an ObjC pointer or "void *".
if (!ThrowType->isDependentType() &&
!ThrowType->isObjCObjectPointerType()) {
const PointerType *PT = ThrowType->getAs<PointerType>();
if (!PT || !PT->getPointeeType()->isVoidType())
return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
<< Throw->getType() << Throw->getSourceRange());
}
}
return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
}
StmtResult SemaObjC::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope) {
if (!getLangOpts().ObjCExceptions)
Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
if (!Throw) {
// @throw without an expression designates a rethrow (which must occur
// in the context of an @catch clause).
Scope *AtCatchParent = CurScope;
while (AtCatchParent && !AtCatchParent->isAtCatchScope())
AtCatchParent = AtCatchParent->getParent();
if (!AtCatchParent)
return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
}
return BuildObjCAtThrowStmt(AtLoc, Throw);
}
ExprResult SemaObjC::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand) {
ExprResult result = SemaRef.DefaultLvalueConversion(operand);
if (result.isInvalid())
return ExprError();
operand = result.get();
// Make sure the expression type is an ObjC pointer or "void *".
QualType type = operand->getType();
if (!type->isDependentType() && !type->isObjCObjectPointerType()) {
const PointerType *pointerType = type->getAs<PointerType>();
if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
if (getLangOpts().CPlusPlus) {
if (SemaRef.RequireCompleteType(atLoc, type,
diag::err_incomplete_receiver_type))
return Diag(atLoc, diag::err_objc_synchronized_expects_object)
<< type << operand->getSourceRange();
ExprResult result =
SemaRef.PerformContextuallyConvertToObjCPointer(operand);
if (result.isInvalid())
return ExprError();
if (!result.isUsable())
return Diag(atLoc, diag::err_objc_synchronized_expects_object)
<< type << operand->getSourceRange();
operand = result.get();
} else {
return Diag(atLoc, diag::err_objc_synchronized_expects_object)
<< type << operand->getSourceRange();
}
}
}
// The operand to @synchronized is a full-expression.
return SemaRef.ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
}
StmtResult SemaObjC::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SyncExpr,
Stmt *SyncBody) {
ASTContext &Context = getASTContext();
// We can't jump into or indirect-jump out of a @synchronized block.
SemaRef.setFunctionHasBranchProtectedScope();
return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
}
StmtResult SemaObjC::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc,
Stmt *Body) {
ASTContext &Context = getASTContext();
SemaRef.setFunctionHasBranchProtectedScope();
return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
}
TypeResult SemaObjC::actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc, ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc) {
ASTContext &Context = getASTContext();
// Form id<protocol-list>.
QualType Result = Context.getObjCObjectType(
Context.ObjCBuiltinIdTy, {},
llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
protocols.size()),
false);
Result = Context.getObjCObjectPointerType(Result);
TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
TypeLoc ResultTL = ResultTInfo->getTypeLoc();
auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
auto ObjCObjectTL =
ObjCObjectPointerTL.getPointeeLoc().castAs<ObjCObjectTypeLoc>();
ObjCObjectTL.setHasBaseTypeAsWritten(false);
ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
// No type arguments.
ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
// Fill in protocol qualifiers.
ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
for (unsigned i = 0, n = protocols.size(); i != n; ++i)
ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
// We're done. Return the completed type to the parser.
return SemaRef.CreateParsedType(Result, ResultTInfo);
}
TypeResult SemaObjC::actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S, SourceLocation Loc, ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc) {
ASTContext &Context = getASTContext();
TypeSourceInfo *BaseTypeInfo = nullptr;
QualType T = SemaRef.GetTypeFromParser(BaseType, &BaseTypeInfo);
if (T.isNull())
return true;
// Handle missing type-source info.
if (!BaseTypeInfo)
BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
// Extract type arguments.
SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
TypeSourceInfo *TypeArgInfo = nullptr;
QualType TypeArg = SemaRef.GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
if (TypeArg.isNull()) {
ActualTypeArgInfos.clear();
break;
}
assert(TypeArgInfo && "No type source info?");
ActualTypeArgInfos.push_back(TypeArgInfo);
}
// Build the object type.
QualType Result = BuildObjCObjectType(
T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
ProtocolLAngleLoc,
llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
Protocols.size()),
ProtocolLocs, ProtocolRAngleLoc,
/*FailOnError=*/false,
/*Rebuilding=*/false);
if (Result == T)
return BaseType;
// Create source information for this type.
TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
TypeLoc ResultTL = ResultTInfo->getTypeLoc();
// For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
// object pointer type. Fill in source information for it.
if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
// The '*' is implicit.
ObjCObjectPointerTL.setStarLoc(SourceLocation());
ResultTL = ObjCObjectPointerTL.getPointeeLoc();
}
if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
// Protocol qualifier information.
if (OTPTL.getNumProtocols() > 0) {
assert(OTPTL.getNumProtocols() == Protocols.size());
OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
}
// We're done. Return the completed type to the parser.
return SemaRef.CreateParsedType(Result, ResultTInfo);
}
auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
// Type argument information.
if (ObjCObjectTL.getNumTypeArgs() > 0) {
assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
} else {
ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
}
// Protocol qualifier information.
if (ObjCObjectTL.getNumProtocols() > 0) {
assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
} else {
ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
}
// Base type.
ObjCObjectTL.setHasBaseTypeAsWritten(true);
if (ObjCObjectTL.getType() == T)
ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
else
ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
// We're done. Return the completed type to the parser.
return SemaRef.CreateParsedType(Result, ResultTInfo);
}
QualType SemaObjC::BuildObjCTypeParamType(
const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
bool FailOnError) {
ASTContext &Context = getASTContext();
QualType Result = QualType(Decl->getTypeForDecl(), 0);
if (!Protocols.empty()) {
bool HasError;
Result = Context.applyObjCProtocolQualifiers(Result, Protocols, HasError);
if (HasError) {
Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
<< SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
if (FailOnError)
Result = QualType();
}
if (FailOnError && Result.isNull())
return QualType();
}
return Result;
}
/// Apply Objective-C type arguments to the given type.
static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
ArrayRef<TypeSourceInfo *> typeArgs,
SourceRange typeArgsRange, bool failOnError,
bool rebuilding) {
// We can only apply type arguments to an Objective-C class type.
const auto *objcObjectType = type->getAs<ObjCObjectType>();
if (!objcObjectType || !objcObjectType->getInterface()) {
S.Diag(loc, diag::err_objc_type_args_non_class) << type << typeArgsRange;
if (failOnError)
return QualType();
return type;
}
// The class type must be parameterized.
ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
if (!typeParams) {
S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
<< objcClass->getDeclName() << FixItHint::CreateRemoval(typeArgsRange);
if (failOnError)
return QualType();
return type;
}
// The type must not already be specialized.
if (objcObjectType->isSpecialized()) {
S.Diag(loc, diag::err_objc_type_args_specialized_class)
<< type << FixItHint::CreateRemoval(typeArgsRange);
if (failOnError)
return QualType();
return type;
}
// Check the type arguments.
SmallVector<QualType, 4> finalTypeArgs;
unsigned numTypeParams = typeParams->size();
bool anyPackExpansions = false;
for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
TypeSourceInfo *typeArgInfo = typeArgs[i];
QualType typeArg = typeArgInfo->getType();
// Type arguments cannot have explicit qualifiers or nullability.
// We ignore indirect sources of these, e.g. behind typedefs or
// template arguments.
if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
bool diagnosed = false;
SourceRange rangeToRemove;
if (auto attr = qual.getAs<AttributedTypeLoc>()) {
rangeToRemove = attr.getLocalSourceRange();
if (attr.getTypePtr()->getImmediateNullability()) {
typeArg = attr.getTypePtr()->getModifiedType();
S.Diag(attr.getBeginLoc(),
diag::err_objc_type_arg_explicit_nullability)
<< typeArg << FixItHint::CreateRemoval(rangeToRemove);
diagnosed = true;
}
}
// When rebuilding, qualifiers might have gotten here through a
// final substitution.
if (!rebuilding && !diagnosed) {
S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
<< typeArg << typeArg.getQualifiers().getAsString()
<< FixItHint::CreateRemoval(rangeToRemove);
}
}
// Remove qualifiers even if they're non-local.
typeArg = typeArg.getUnqualifiedType();
finalTypeArgs.push_back(typeArg);
if (typeArg->getAs<PackExpansionType>())
anyPackExpansions = true;
// Find the corresponding type parameter, if there is one.
ObjCTypeParamDecl *typeParam = nullptr;
if (!anyPackExpansions) {
if (i < numTypeParams) {
typeParam = typeParams->begin()[i];
} else {
// Too many arguments.
S.Diag(loc, diag::err_objc_type_args_wrong_arity)
<< false << objcClass->getDeclName() << (unsigned)typeArgs.size()
<< numTypeParams;
S.Diag(objcClass->getLocation(), diag::note_previous_decl) << objcClass;
if (failOnError)
return QualType();
return type;
}
}
// Objective-C object pointer types must be substitutable for the bounds.
if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
// If we don't have a type parameter to match against, assume
// everything is fine. There was a prior pack expansion that
// means we won't be able to match anything.
if (!typeParam) {
assert(anyPackExpansions && "Too many arguments?");
continue;
}
// Retrieve the bound.
QualType bound = typeParam->getUnderlyingType();
const auto *boundObjC = bound->castAs<ObjCObjectPointerType>();
// Determine whether the type argument is substitutable for the bound.
if (typeArgObjC->isObjCIdType()) {
// When the type argument is 'id', the only acceptable type
// parameter bound is 'id'.
if (boundObjC->isObjCIdType())
continue;
} else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
// Otherwise, we follow the assignability rules.
continue;
}
// Diagnose the mismatch.
S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
diag::err_objc_type_arg_does_not_match_bound)
<< typeArg << bound << typeParam->getDeclName();
S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
<< typeParam->getDeclName();
if (failOnError)
return QualType();
return type;
}
// Block pointer types are permitted for unqualified 'id' bounds.
if (typeArg->isBlockPointerType()) {
// If we don't have a type parameter to match against, assume
// everything is fine. There was a prior pack expansion that
// means we won't be able to match anything.
if (!typeParam) {
assert(anyPackExpansions && "Too many arguments?");
continue;
}
// Retrieve the bound.
QualType bound = typeParam->getUnderlyingType();
if (bound->isBlockCompatibleObjCPointerType(S.Context))
continue;
// Diagnose the mismatch.
S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
diag::err_objc_type_arg_does_not_match_bound)
<< typeArg << bound << typeParam->getDeclName();
S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
<< typeParam->getDeclName();
if (failOnError)
return QualType();
return type;
}
// Types that have __attribute__((NSObject)) are permitted.
if (typeArg->isObjCNSObjectType()) {
continue;
}
// Dependent types will be checked at instantiation time.
if (typeArg->isDependentType()) {
continue;
}
// Diagnose non-id-compatible type arguments.
S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
diag::err_objc_type_arg_not_id_compatible)
<< typeArg << typeArgInfo->getTypeLoc().getSourceRange();
if (failOnError)
return QualType();
return type;
}
// Make sure we didn't have the wrong number of arguments.
if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
S.Diag(loc, diag::err_objc_type_args_wrong_arity)
<< (typeArgs.size() < typeParams->size()) << objcClass->getDeclName()
<< (unsigned)finalTypeArgs.size() << (unsigned)numTypeParams;
S.Diag(objcClass->getLocation(), diag::note_previous_decl) << objcClass;
if (failOnError)
return QualType();
return type;
}
// Success. Form the specialized type.
return S.Context.getObjCObjectType(type, finalTypeArgs, {}, false);
}
QualType SemaObjC::BuildObjCObjectType(
QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
bool FailOnError, bool Rebuilding) {
ASTContext &Context = getASTContext();
QualType Result = BaseType;
if (!TypeArgs.empty()) {
Result =
applyObjCTypeArgs(SemaRef, Loc, Result, TypeArgs,
SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
FailOnError, Rebuilding);
if (FailOnError && Result.isNull())
return QualType();
}
if (!Protocols.empty()) {
bool HasError;
Result = Context.applyObjCProtocolQualifiers(Result, Protocols, HasError);
if (HasError) {
Diag(Loc, diag::err_invalid_protocol_qualifiers)
<< SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
if (FailOnError)
Result = QualType();
}
if (FailOnError && Result.isNull())
return QualType();
}
return Result;
}
ParsedType SemaObjC::ActOnObjCInstanceType(SourceLocation Loc) {
ASTContext &Context = getASTContext();
QualType T = Context.getObjCInstanceType();
TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
return SemaRef.CreateParsedType(T, TInfo);
}
//===--- CHECK: Objective-C retain cycles ----------------------------------//
namespace {
struct RetainCycleOwner {
VarDecl *Variable = nullptr;
SourceRange Range;
SourceLocation Loc;
bool Indirect = false;
RetainCycleOwner() = default;
void setLocsFrom(Expr *e) {
Loc = e->getExprLoc();
Range = e->getSourceRange();
}
};
} // namespace
/// Consider whether capturing the given variable can possibly lead to
/// a retain cycle.
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
// In ARC, it's captured strongly iff the variable has __strong
// lifetime. In MRR, it's captured strongly if the variable is
// __block and has an appropriate type.
if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
return false;
owner.Variable = var;
if (ref)
owner.setLocsFrom(ref);
return true;
}
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
while (true) {
e = e->IgnoreParens();
if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
switch (cast->getCastKind()) {
case CK_BitCast:
case CK_LValueBitCast:
case CK_LValueToRValue:
case CK_ARCReclaimReturnedObject:
e = cast->getSubExpr();
continue;
default:
return false;
}
}
if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
ObjCIvarDecl *ivar = ref->getDecl();
if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
return false;
// Try to find a retain cycle in the base.
if (!findRetainCycleOwner(S, ref->getBase(), owner))
return false;
if (ref->isFreeIvar())
owner.setLocsFrom(ref);
owner.Indirect = true;
return true;
}
if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
if (!var)
return false;
return considerVariable(var, ref, owner);
}
if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
if (member->isArrow())
return false;
// Don't count this as an indirect ownership.
e = member->getBase();
continue;
}
if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
// Only pay attention to pseudo-objects on property references.
ObjCPropertyRefExpr *pre = dyn_cast<ObjCPropertyRefExpr>(
pseudo->getSyntacticForm()->IgnoreParens());
if (!pre)
return false;
if (pre->isImplicitProperty())
return false;
ObjCPropertyDecl *property = pre->getExplicitProperty();
if (!property->isRetaining() &&
!(property->getPropertyIvarDecl() &&
property->getPropertyIvarDecl()->getType().getObjCLifetime() ==
Qualifiers::OCL_Strong))
return false;
owner.Indirect = true;
if (pre->isSuperReceiver()) {
owner.Variable = S.getCurMethodDecl()->getSelfDecl();
if (!owner.Variable)
return false;
owner.Loc = pre->getLocation();
owner.Range = pre->getSourceRange();
return true;
}
e = const_cast<Expr *>(
cast<OpaqueValueExpr>(pre->getBase())->getSourceExpr());
continue;
}
// Array ivars?
return false;
}
}
namespace {
struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
VarDecl *Variable;
Expr *Capturer = nullptr;
bool VarWillBeReased = false;
FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
: EvaluatedExprVisitor<FindCaptureVisitor>(Context), Variable(variable) {}
void VisitDeclRefExpr(DeclRefExpr *ref) {
if (ref->getDecl() == Variable && !Capturer)
Capturer = ref;
}
void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
if (Capturer)
return;
Visit(ref->getBase());
if (Capturer && ref->isFreeIvar())
Capturer = ref;
}
void VisitBlockExpr(BlockExpr *block) {
// Look inside nested blocks
if (block->getBlockDecl()->capturesVariable(Variable))
Visit(block->getBlockDecl()->getBody());
}
void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
if (Capturer)
return;
if (OVE->getSourceExpr())
Visit(OVE->getSourceExpr());
}
void VisitBinaryOperator(BinaryOperator *BinOp) {
if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
return;
Expr *LHS = BinOp->getLHS();
if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
if (DRE->getDecl() != Variable)
return;
if (Expr *RHS = BinOp->getRHS()) {
RHS = RHS->IgnoreParenCasts();
std::optional<llvm::APSInt> Value;
VarWillBeReased =
(RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
*Value == 0);
}
}
}
};
} // namespace
/// Check whether the given argument is a block which captures a
/// variable.
static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
assert(owner.Variable && owner.Loc.isValid());
e = e->IgnoreParenCasts();
// Look through [^{...} copy] and Block_copy(^{...}).
if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
Selector Cmd = ME->getSelector();
if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
e = ME->getInstanceReceiver();
if (!e)
return nullptr;
e = e->IgnoreParenCasts();
}
} else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
if (CE->getNumArgs() == 1) {
FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
if (Fn) {
const IdentifierInfo *FnI = Fn->getIdentifier();
if (FnI && FnI->isStr("_Block_copy")) {
e = CE->getArg(0)->IgnoreParenCasts();
}
}
}
}
BlockExpr *block = dyn_cast<BlockExpr>(e);
if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
return nullptr;
FindCaptureVisitor visitor(S.Context, owner.Variable);
visitor.Visit(block->getBlockDecl()->getBody());
return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
}
static void diagnoseRetainCycle(Sema &S, Expr *capturer,
RetainCycleOwner &owner) {
assert(capturer);
assert(owner.Variable && owner.Loc.isValid());
S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
<< owner.Variable << capturer->getSourceRange();
S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
<< owner.Indirect << owner.Range;
}
/// Check for a keyword selector that starts with the word 'add' or
/// 'set'.
static bool isSetterLikeSelector(Selector sel) {
if (sel.isUnarySelector())
return false;
StringRef str = sel.getNameForSlot(0);
str = str.ltrim('_');
if (str.starts_with("set"))
str = str.substr(3);
else if (str.starts_with("add")) {
// Specially allow 'addOperationWithBlock:'.
if (sel.getNumArgs() == 1 && str.starts_with("addOperationWithBlock"))
return false;
str = str.substr(3);
} else
return false;
if (str.empty())
return true;
return !isLowercase(str.front());
}
static std::optional<int>
GetNSMutableArrayArgumentIndex(SemaObjC &S, ObjCMessageExpr *Message) {
bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(), NSAPI::ClassId_NSMutableArray);
if (!IsMutableArray) {
return std::nullopt;
}
Selector Sel = Message->getSelector();
std::optional<NSAPI::NSArrayMethodKind> MKOpt =
S.NSAPIObj->getNSArrayMethodKind(Sel);
if (!MKOpt) {
return std::nullopt;
}
NSAPI::NSArrayMethodKind MK = *MKOpt;
switch (MK) {
case NSAPI::NSMutableArr_addObject:
case NSAPI::NSMutableArr_insertObjectAtIndex:
case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
return 0;
case NSAPI::NSMutableArr_replaceObjectAtIndex:
return 1;
default:
return std::nullopt;
}
return std::nullopt;
}
static std::optional<int>
GetNSMutableDictionaryArgumentIndex(SemaObjC &S, ObjCMessageExpr *Message) {
bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(), NSAPI::ClassId_NSMutableDictionary);
if (!IsMutableDictionary) {
return std::nullopt;
}
Selector Sel = Message->getSelector();
std::optional<NSAPI::NSDictionaryMethodKind> MKOpt =
S.NSAPIObj->getNSDictionaryMethodKind(Sel);
if (!MKOpt) {
return std::nullopt;
}
NSAPI::NSDictionaryMethodKind MK = *MKOpt;
switch (MK) {
case NSAPI::NSMutableDict_setObjectForKey:
case NSAPI::NSMutableDict_setValueForKey:
case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
return 0;
default:
return std::nullopt;
}
return std::nullopt;
}
static std::optional<int> GetNSSetArgumentIndex(SemaObjC &S,
ObjCMessageExpr *Message) {
bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(), NSAPI::ClassId_NSMutableSet);
bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
Message->getReceiverInterface(), NSAPI::ClassId_NSMutableOrderedSet);
if (!IsMutableSet && !IsMutableOrderedSet) {
return std::nullopt;
}
Selector Sel = Message->getSelector();
std::optional<NSAPI::NSSetMethodKind> MKOpt =
S.NSAPIObj->getNSSetMethodKind(Sel);
if (!MKOpt) {
return std::nullopt;
}
NSAPI::NSSetMethodKind MK = *MKOpt;
switch (MK) {
case NSAPI::NSMutableSet_addObject:
case NSAPI::NSOrderedSet_setObjectAtIndex:
case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
case NSAPI::NSOrderedSet_insertObjectAtIndex:
return 0;
case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
return 1;
}
return std::nullopt;
}
void SemaObjC::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
if (!Message->isInstanceMessage()) {
return;
}
std::optional<int> ArgOpt;
if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
!(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
!(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
return;
}
int ArgIndex = *ArgOpt;
Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
Arg = OE->getSourceExpr()->IgnoreImpCasts();
}
if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
if (ArgRE->isObjCSelfExpr()) {
Diag(Message->getSourceRange().getBegin(),
diag::warn_objc_circular_container)
<< ArgRE->getDecl() << StringRef("'super'");
}
}
} else {
Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
Receiver = OE->getSourceExpr()->IgnoreImpCasts();
}
if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
ValueDecl *Decl = ReceiverRE->getDecl();
Diag(Message->getSourceRange().getBegin(),
diag::warn_objc_circular_container)
<< Decl << Decl;
if (!ArgRE->isObjCSelfExpr()) {
Diag(Decl->getLocation(),
diag::note_objc_circular_container_declared_here)
<< Decl;
}
}
}
} else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
ObjCIvarDecl *Decl = IvarRE->getDecl();
Diag(Message->getSourceRange().getBegin(),
diag::warn_objc_circular_container)
<< Decl << Decl;
Diag(Decl->getLocation(),
diag::note_objc_circular_container_declared_here)
<< Decl;
}
}
}
}
}
/// Check a message send to see if it's likely to cause a retain cycle.
void SemaObjC::checkRetainCycles(ObjCMessageExpr *msg) {
// Only check instance methods whose selector looks like a setter.
if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
return;
// Try to find a variable that the receiver is strongly owned by.
RetainCycleOwner owner;
if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
if (!findRetainCycleOwner(SemaRef, msg->getInstanceReceiver(), owner))
return;
} else {
assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
owner.Variable = SemaRef.getCurMethodDecl()->getSelfDecl();
owner.Loc = msg->getSuperLoc();
owner.Range = msg->getSuperLoc();
}
// Check whether the receiver is captured by any of the arguments.
const ObjCMethodDecl *MD = msg->getMethodDecl();
for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
if (Expr *capturer = findCapturingExpr(SemaRef, msg->getArg(i), owner)) {
// noescape blocks should not be retained by the method.
if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
continue;
return diagnoseRetainCycle(SemaRef, capturer, owner);
}
}
}
/// Check a property assign to see if it's likely to cause a retain cycle.
void SemaObjC::checkRetainCycles(Expr *receiver, Expr *argument) {
RetainCycleOwner owner;
if (!findRetainCycleOwner(SemaRef, receiver, owner))
return;
if (Expr *capturer = findCapturingExpr(SemaRef, argument, owner))
diagnoseRetainCycle(SemaRef, capturer, owner);
}
void SemaObjC::checkRetainCycles(VarDecl *Var, Expr *Init) {
RetainCycleOwner Owner;
if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
return;
// Because we don't have an expression for the variable, we have to set the
// location explicitly here.
Owner.Loc = Var->getLocation();
Owner.Range = Var->getSourceRange();
if (Expr *Capturer = findCapturingExpr(SemaRef, Init, Owner))
diagnoseRetainCycle(SemaRef, Capturer, Owner);
}
/// CheckObjCString - Checks that the argument to the builtin
/// CFString constructor is correct
/// Note: It might also make sense to do the UTF-16 conversion here (would
/// simplify the backend).
bool SemaObjC::CheckObjCString(Expr *Arg) {
Arg = Arg->IgnoreParenCasts();
StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
if (!Literal || !Literal->isOrdinary()) {
Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
<< Arg->getSourceRange();
return true;
}
if (Literal->containsNonAsciiOrNull()) {
StringRef String = Literal->getString();
unsigned NumBytes = String.size();
SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
llvm::UTF16 *ToPtr = &ToBuf[0];
llvm::ConversionResult Result =
llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
ToPtr + NumBytes, llvm::strictConversion);
// Check for conversion failure.
if (Result != llvm::conversionOK)
Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
<< Arg->getSourceRange();
}
return false;
}
bool SemaObjC::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
ArrayRef<const Expr *> Args) {
VariadicCallType CallType = Method->isVariadic()
? VariadicCallType::Method
: VariadicCallType::DoesNotApply;
SemaRef.checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
/*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
CallType);
SemaRef.CheckTCBEnforcement(lbrac, Method);
return false;
}
const DeclContext *SemaObjC::getCurObjCLexicalContext() const {
const DeclContext *DC = SemaRef.getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// Retrieve the identifier "NSError".
IdentifierInfo *SemaObjC::getNSErrorIdent() {
if (!Ident_NSError)
Ident_NSError = SemaRef.PP.getIdentifierInfo("NSError");
return Ident_NSError;
}
void SemaObjC::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
assert(
IDecl->getLexicalParent() == SemaRef.CurContext &&
"The next DeclContext should be lexically contained in the current one.");
SemaRef.CurContext = IDecl;
}
void SemaObjC::ActOnObjCContainerFinishDefinition() {
// Exit this scope of this interface definition.
SemaRef.PopDeclContext();
}
void SemaObjC::ActOnObjCTemporaryExitContainerContext(
ObjCContainerDecl *ObjCCtx) {
assert(ObjCCtx == SemaRef.CurContext && "Mismatch of container contexts");
SemaRef.OriginalLexicalContext = ObjCCtx;
ActOnObjCContainerFinishDefinition();
}
void SemaObjC::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
ActOnObjCContainerStartDefinition(ObjCCtx);
SemaRef.OriginalLexicalContext = nullptr;
}
/// Find the protocol with the given name, if any.
ObjCProtocolDecl *SemaObjC::LookupProtocol(IdentifierInfo *II,
SourceLocation IdLoc,
RedeclarationKind Redecl) {
Decl *D = SemaRef.LookupSingleName(SemaRef.TUScope, II, IdLoc,
Sema::LookupObjCProtocolName, Redecl);
return cast_or_null<ObjCProtocolDecl>(D);
}
/// Determine whether this is an Objective-C writeback conversion,
/// used for parameter passing when performing automatic reference counting.
///
/// \param FromType The type we're converting form.
///
/// \param ToType The type we're converting to.
///
/// \param ConvertedType The type that will be produced after applying
/// this conversion.
bool SemaObjC::isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType) {
ASTContext &Context = getASTContext();
if (!getLangOpts().ObjCAutoRefCount ||
Context.hasSameUnqualifiedType(FromType, ToType))
return false;
// Parameter must be a pointer to __autoreleasing (with no other qualifiers).
QualType ToPointee;
if (const PointerType *ToPointer = ToType->getAs<PointerType>())
ToPointee = ToPointer->getPointeeType();
else
return false;
Qualifiers ToQuals = ToPointee.getQualifiers();
if (!ToPointee->isObjCLifetimeType() ||
ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
!ToQuals.withoutObjCLifetime().empty())
return false;
// Argument must be a pointer to __strong to __weak.
QualType FromPointee;
if (const PointerType *FromPointer = FromType->getAs<PointerType>())
FromPointee = FromPointer->getPointeeType();
else
return false;
Qualifiers FromQuals = FromPointee.getQualifiers();
if (!FromPointee->isObjCLifetimeType() ||
(FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
return false;
// Make sure that we have compatible qualifiers.
FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
if (!ToQuals.compatiblyIncludes(FromQuals, getASTContext()))
return false;
// Remove qualifiers from the pointee type we're converting from; they
// aren't used in the compatibility check belong, and we'll be adding back
// qualifiers (with __autoreleasing) if the compatibility check succeeds.
FromPointee = FromPointee.getUnqualifiedType();
// The unqualified form of the pointee types must be compatible.
ToPointee = ToPointee.getUnqualifiedType();
bool IncompatibleObjC;
if (Context.typesAreCompatible(FromPointee, ToPointee))
FromPointee = ToPointee;
else if (!SemaRef.isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
IncompatibleObjC))
return false;
/// Construct the type we're converting to, which is a pointer to
/// __autoreleasing pointee.
FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
ConvertedType = Context.getPointerType(FromPointee);
return true;
}
/// CheckSubscriptingKind - This routine decide what type
/// of indexing represented by "FromE" is being done.
SemaObjC::ObjCSubscriptKind SemaObjC::CheckSubscriptingKind(Expr *FromE) {
// If the expression already has integral or enumeration type, we're golden.
QualType T = FromE->getType();
if (T->isIntegralOrEnumerationType())
return SemaObjC::OS_Array;
// If we don't have a class type in C++, there's no way we can get an
// expression of integral or enumeration type.
const RecordType *RecordTy = T->getAs<RecordType>();
if (!RecordTy && (T->isObjCObjectPointerType() || T->isVoidPointerType()))
// All other scalar cases are assumed to be dictionary indexing which
// caller handles, with diagnostics if needed.
return SemaObjC::OS_Dictionary;
if (!getLangOpts().CPlusPlus || !RecordTy || RecordTy->isIncompleteType()) {
// No indexing can be done. Issue diagnostics and quit.
const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
if (isa<StringLiteral>(IndexExpr))
Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
<< T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
else
Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion) << T;
return SemaObjC::OS_Error;
}
// We must have a complete class type.
if (SemaRef.RequireCompleteType(FromE->getExprLoc(), T,
diag::err_objc_index_incomplete_class_type,
FromE))
return SemaObjC::OS_Error;
// Look for a conversion to an integral, enumeration type, or
// objective-C pointer type.
int NoIntegrals = 0, NoObjCIdPointers = 0;
SmallVector<CXXConversionDecl *, 4> ConversionDecls;
for (NamedDecl *D : cast<CXXRecordDecl>(RecordTy->getDecl())
->getVisibleConversionFunctions()) {
if (CXXConversionDecl *Conversion =
dyn_cast<CXXConversionDecl>(D->getUnderlyingDecl())) {
QualType CT = Conversion->getConversionType().getNonReferenceType();
if (CT->isIntegralOrEnumerationType()) {
++NoIntegrals;
ConversionDecls.push_back(Conversion);
} else if (CT->isObjCIdType() || CT->isBlockPointerType()) {
++NoObjCIdPointers;
ConversionDecls.push_back(Conversion);
}
}
}
if (NoIntegrals == 1 && NoObjCIdPointers == 0)
return SemaObjC::OS_Array;
if (NoIntegrals == 0 && NoObjCIdPointers == 1)
return SemaObjC::OS_Dictionary;
if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
// No conversion function was found. Issue diagnostic and return.
Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
<< FromE->getType();
return SemaObjC::OS_Error;
}
Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
<< FromE->getType();
for (unsigned int i = 0; i < ConversionDecls.size(); i++)
Diag(ConversionDecls[i]->getLocation(),
diag::note_conv_function_declared_at);
return SemaObjC::OS_Error;
}
void SemaObjC::AddCFAuditedAttribute(Decl *D) {
ASTContext &Context = getASTContext();
auto IdLoc = SemaRef.PP.getPragmaARCCFCodeAuditedInfo();
if (!IdLoc.getLoc().isValid())
return;
// Don't add a redundant or conflicting attribute.
if (D->hasAttr<CFAuditedTransferAttr>() ||
D->hasAttr<CFUnknownTransferAttr>())
return;
AttributeCommonInfo Info(IdLoc.getIdentifierInfo(),
SourceRange(IdLoc.getLoc()),
AttributeCommonInfo::Form::Pragma());
D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
}
bool SemaObjC::isCFError(RecordDecl *RD) {
// If we already know about CFError, test it directly.
if (CFError)
return CFError == RD;
// Check whether this is CFError, which we identify based on its bridge to
// NSError. CFErrorRef used to be declared with "objc_bridge" but is now
// declared with "objc_bridge_mutable", so look for either one of the two
// attributes.
if (RD->getTagKind() == TagTypeKind::Struct) {
IdentifierInfo *bridgedType = nullptr;
if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
bridgedType = bridgeAttr->getBridgedType();
else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
bridgedType = bridgeAttr->getBridgedType();
if (bridgedType == getNSErrorIdent()) {
CFError = RD;
return true;
}
}
return false;
}
bool SemaObjC::isNSStringType(QualType T, bool AllowNSAttributedString) {
const auto *PT = T->getAs<ObjCObjectPointerType>();
if (!PT)
return false;
ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
if (!Cls)
return false;
IdentifierInfo *ClsName = Cls->getIdentifier();
if (AllowNSAttributedString &&
ClsName == &getASTContext().Idents.get("NSAttributedString"))
return true;
// FIXME: Should we walk the chain of classes?
return ClsName == &getASTContext().Idents.get("NSString") ||
ClsName == &getASTContext().Idents.get("NSMutableString");
}
bool SemaObjC::isCFStringType(QualType T) {
const auto *PT = T->getAs<PointerType>();
if (!PT)
return false;
const auto *RT = PT->getPointeeType()->getAs<RecordType>();
if (!RT)
return false;
const RecordDecl *RD = RT->getDecl();
if (RD->getTagKind() != TagTypeKind::Struct)
return false;
return RD->getIdentifier() == &getASTContext().Idents.get("__CFString");
}
static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
// The IBOutlet/IBOutletCollection attributes only apply to instance
// variables or properties of Objective-C classes. The outlet must also
// have an object reference type.
if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
<< AL << VD->getType() << 0;
return false;
}
} else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
<< AL << PD->getType() << 1;
return false;
}
} else {
S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
return false;
}
return true;
}
void SemaObjC::handleIBOutlet(Decl *D, const ParsedAttr &AL) {
if (!checkIBOutletCommon(SemaRef, D, AL))
return;
D->addAttr(::new (getASTContext()) IBOutletAttr(getASTContext(), AL));
}
void SemaObjC::handleIBOutletCollection(Decl *D, const ParsedAttr &AL) {
ASTContext &Context = getASTContext();
// The iboutletcollection attribute can have zero or one arguments.
if (AL.getNumArgs() > 1) {
Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
return;
}
if (!checkIBOutletCommon(SemaRef, D, AL))
return;
ParsedType PT;
if (AL.hasParsedType())
PT = AL.getTypeArg();
else {
PT = SemaRef.getTypeName(
Context.Idents.get("NSObject"), AL.getLoc(),
SemaRef.getScopeForContext(D->getDeclContext()->getParent()));
if (!PT) {
Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
return;
}
}
TypeSourceInfo *QTLoc = nullptr;
QualType QT = SemaRef.GetTypeFromParser(PT, &QTLoc);
if (!QTLoc)
QTLoc = Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
// Diagnose use of non-object type in iboutletcollection attribute.
// FIXME. Gnu attribute extension ignores use of builtin types in
// attributes. So, __attribute__((iboutletcollection(char))) will be
// treated as __attribute__((iboutletcollection())).
if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
Diag(AL.getLoc(), QT->isBuiltinType()
? diag::err_iboutletcollection_builtintype
: diag::err_iboutletcollection_type)
<< QT;
return;
}
D->addAttr(::new (Context) IBOutletCollectionAttr(Context, AL, QTLoc));
}
void SemaObjC::handleSuppresProtocolAttr(Decl *D, const ParsedAttr &AL) {
if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
<< AL << AL.getRange();
return;
}
D->addAttr(::new (getASTContext())
ObjCExplicitProtocolImplAttr(getASTContext(), AL));
}
void SemaObjC::handleDirectAttr(Decl *D, const ParsedAttr &AL) {
// objc_direct cannot be set on methods declared in the context of a protocol
if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
return;
}
if (getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
handleSimpleAttribute<ObjCDirectAttr>(*this, D, AL);
} else {
Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
}
}
void SemaObjC::handleDirectMembersAttr(Decl *D, const ParsedAttr &AL) {
if (getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
handleSimpleAttribute<ObjCDirectMembersAttr>(*this, D, AL);
} else {
Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
}
}
void SemaObjC::handleMethodFamilyAttr(Decl *D, const ParsedAttr &AL) {
const auto *M = cast<ObjCMethodDecl>(D);
if (!AL.isArgIdent(0)) {
Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
<< AL << 1 << AANT_ArgumentIdentifier;
return;
}
IdentifierLoc *IL = AL.getArgAsIdent(0);
ObjCMethodFamilyAttr::FamilyKind F;
if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(
IL->getIdentifierInfo()->getName(), F)) {
Diag(IL->getLoc(), diag::warn_attribute_type_not_supported)
<< AL << IL->getIdentifierInfo();
return;
}
if (F == ObjCMethodFamilyAttr::OMF_init &&
!M->getReturnType()->isObjCObjectPointerType()) {
Diag(M->getLocation(), diag::err_init_method_bad_return_type)
<< M->getReturnType();
// Ignore the attribute.
return;
}
D->addAttr(new (getASTContext())
ObjCMethodFamilyAttr(getASTContext(), AL, F));
}
void SemaObjC::handleNSObject(Decl *D, const ParsedAttr &AL) {
if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
QualType T = TD->getUnderlyingType();
if (!T->isCARCBridgableType()) {
Diag(TD->getLocation(), diag::err_nsobject_attribute);
return;
}
} else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
QualType T = PD->getType();
if (!T->isCARCBridgableType()) {
Diag(PD->getLocation(), diag::err_nsobject_attribute);
return;
}
} else {
// It is okay to include this attribute on properties, e.g.:
//
// @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
//
// In this case it follows tradition and suppresses an error in the above
// case.
Diag(D->getLocation(), diag::warn_nsobject_attribute);
}
D->addAttr(::new (getASTContext()) ObjCNSObjectAttr(getASTContext(), AL));
}
void SemaObjC::handleIndependentClass(Decl *D, const ParsedAttr &AL) {
if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
QualType T = TD->getUnderlyingType();
if (!T->isObjCObjectPointerType()) {
Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
return;
}
} else {
Diag(D->getLocation(), diag::warn_independentclass_attribute);
return;
}
D->addAttr(::new (getASTContext())
ObjCIndependentClassAttr(getASTContext(), AL));
}
void SemaObjC::handleBlocksAttr(Decl *D, const ParsedAttr &AL) {
if (!AL.isArgIdent(0)) {
Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
<< AL << 1 << AANT_ArgumentIdentifier;
return;
}
IdentifierInfo *II = AL.getArgAsIdent(0)->getIdentifierInfo();
BlocksAttr::BlockType type;
if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
return;
}
D->addAttr(::new (getASTContext()) BlocksAttr(getASTContext(), AL, type));
}
static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
return QT->isDependentType() || QT->isObjCRetainableType();
}
static bool isValidSubjectOfNSAttribute(QualType QT) {
return QT->isDependentType() || QT->isObjCObjectPointerType() ||
QT->isObjCNSObjectType();
}
static bool isValidSubjectOfCFAttribute(QualType QT) {
return QT->isDependentType() || QT->isPointerType() ||
isValidSubjectOfNSAttribute(QT);
}
static bool isValidSubjectOfOSAttribute(QualType QT) {
if (QT->isDependentType())
return true;
QualType PT = QT->getPointeeType();
return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
}
void SemaObjC::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
Sema::RetainOwnershipKind K,
bool IsTemplateInstantiation) {
ValueDecl *VD = cast<ValueDecl>(D);
switch (K) {
case Sema::RetainOwnershipKind::OS:
handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
*this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
diag::warn_ns_attribute_wrong_parameter_type,
/*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
return;
case Sema::RetainOwnershipKind::NS:
handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
*this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
// These attributes are normally just advisory, but in ARC, ns_consumed
// is significant. Allow non-dependent code to contain inappropriate
// attributes even in ARC, but require template instantiations to be
// set up correctly.
((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
? diag::err_ns_attribute_wrong_parameter_type
: diag::warn_ns_attribute_wrong_parameter_type),
/*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
return;
case Sema::RetainOwnershipKind::CF:
handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
*this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
diag::warn_ns_attribute_wrong_parameter_type,
/*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
return;
}
}
Sema::RetainOwnershipKind
SemaObjC::parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
switch (AL.getKind()) {
case ParsedAttr::AT_CFConsumed:
case ParsedAttr::AT_CFReturnsRetained:
case ParsedAttr::AT_CFReturnsNotRetained:
return Sema::RetainOwnershipKind::CF;
case ParsedAttr::AT_OSConsumesThis:
case ParsedAttr::AT_OSConsumed:
case ParsedAttr::AT_OSReturnsRetained:
case ParsedAttr::AT_OSReturnsNotRetained:
case ParsedAttr::AT_OSReturnsRetainedOnZero:
case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
return Sema::RetainOwnershipKind::OS;
case ParsedAttr::AT_NSConsumesSelf:
case ParsedAttr::AT_NSConsumed:
case ParsedAttr::AT_NSReturnsRetained:
case ParsedAttr::AT_NSReturnsNotRetained:
case ParsedAttr::AT_NSReturnsAutoreleased:
return Sema::RetainOwnershipKind::NS;
default:
llvm_unreachable("Wrong argument supplied");
}
}
bool SemaObjC::checkNSReturnsRetainedReturnType(SourceLocation Loc,
QualType QT) {
if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
return false;
Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
<< "'ns_returns_retained'" << 0 << 0;
return true;
}
/// \return whether the parameter is a pointer to OSObject pointer.
bool SemaObjC::isValidOSObjectOutParameter(const Decl *D) {
const auto *PVD = dyn_cast<ParmVarDecl>(D);
if (!PVD)
return false;
QualType QT = PVD->getType();
QualType PT = QT->getPointeeType();
return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
}
void SemaObjC::handleXReturnsXRetainedAttr(Decl *D, const ParsedAttr &AL) {
QualType ReturnType;
Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
ReturnType = MD->getReturnType();
} else if (getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
(AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
return; // ignore: was handled as a type attribute
} else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
ReturnType = PD->getType();
} else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
ReturnType = FD->getReturnType();
} else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
// Attributes on parameters are used for out-parameters,
// passed as pointers-to-pointers.
unsigned DiagID = K == Sema::RetainOwnershipKind::CF
? /*pointer-to-CF-pointer*/ 2
: /*pointer-to-OSObject-pointer*/ 3;
ReturnType = Param->getType()->getPointeeType();
if (ReturnType.isNull()) {
Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
<< AL << DiagID << AL.getRange();
return;
}
} else if (AL.isUsedAsTypeAttr()) {
return;
} else {
AttributeDeclKind ExpectedDeclKind;
switch (AL.getKind()) {
default:
llvm_unreachable("invalid ownership attribute");
case ParsedAttr::AT_NSReturnsRetained:
case ParsedAttr::AT_NSReturnsAutoreleased:
case ParsedAttr::AT_NSReturnsNotRetained:
ExpectedDeclKind = ExpectedFunctionOrMethod;
break;
case ParsedAttr::AT_OSReturnsRetained:
case ParsedAttr::AT_OSReturnsNotRetained:
case ParsedAttr::AT_CFReturnsRetained:
case ParsedAttr::AT_CFReturnsNotRetained:
ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
break;
}
Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
<< AL.getRange() << AL << AL.isRegularKeywordAttribute()
<< ExpectedDeclKind;
return;
}
bool TypeOK;
bool Cf;
unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
switch (AL.getKind()) {
default:
llvm_unreachable("invalid ownership attribute");
case ParsedAttr::AT_NSReturnsRetained:
TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
Cf = false;
break;
case ParsedAttr::AT_NSReturnsAutoreleased:
case ParsedAttr::AT_NSReturnsNotRetained:
TypeOK = isValidSubjectOfNSAttribute(ReturnType);
Cf = false;
break;
case ParsedAttr::AT_CFReturnsRetained:
case ParsedAttr::AT_CFReturnsNotRetained:
TypeOK = isValidSubjectOfCFAttribute(ReturnType);
Cf = true;
break;
case ParsedAttr::AT_OSReturnsRetained:
case ParsedAttr::AT_OSReturnsNotRetained:
TypeOK = isValidSubjectOfOSAttribute(ReturnType);
Cf = true;
ParmDiagID = 3; // Pointer-to-OSObject-pointer
break;
}
if (!TypeOK) {
if (AL.isUsedAsTypeAttr())
return;
if (isa<ParmVarDecl>(D)) {
Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
<< AL << ParmDiagID << AL.getRange();
} else {
// Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
enum : unsigned { Function, Method, Property } SubjectKind = Function;
if (isa<ObjCMethodDecl>(D))
SubjectKind = Method;
else if (isa<ObjCPropertyDecl>(D))
SubjectKind = Property;
Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
<< AL << SubjectKind << Cf << AL.getRange();
}
return;
}
switch (AL.getKind()) {
default:
llvm_unreachable("invalid ownership attribute");
case ParsedAttr::AT_NSReturnsAutoreleased:
handleSimpleAttribute<NSReturnsAutoreleasedAttr>(*this, D, AL);
return;
case ParsedAttr::AT_CFReturnsNotRetained:
handleSimpleAttribute<CFReturnsNotRetainedAttr>(*this, D, AL);
return;
case ParsedAttr::AT_NSReturnsNotRetained:
handleSimpleAttribute<NSReturnsNotRetainedAttr>(*this, D, AL);
return;
case ParsedAttr::AT_CFReturnsRetained:
handleSimpleAttribute<CFReturnsRetainedAttr>(*this, D, AL);
return;
case ParsedAttr::AT_NSReturnsRetained:
handleSimpleAttribute<NSReturnsRetainedAttr>(*this, D, AL);
return;
case ParsedAttr::AT_OSReturnsRetained:
handleSimpleAttribute<OSReturnsRetainedAttr>(*this, D, AL);
return;
case ParsedAttr::AT_OSReturnsNotRetained:
handleSimpleAttribute<OSReturnsNotRetainedAttr>(*this, D, AL);
return;
};
}
void SemaObjC::handleReturnsInnerPointerAttr(Decl *D, const ParsedAttr &Attrs) {
const int EP_ObjCMethod = 1;
const int EP_ObjCProperty = 2;
SourceLocation loc = Attrs.getLoc();
QualType resultType;
if (isa<ObjCMethodDecl>(D))
resultType = cast<ObjCMethodDecl>(D)->getReturnType();
else
resultType = cast<ObjCPropertyDecl>(D)->getType();
if (!resultType->isReferenceType() &&
(!resultType->isPointerType() || resultType->isObjCRetainableType())) {
Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
<< SourceRange(loc) << Attrs
<< (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
<< /*non-retainable pointer*/ 2;
// Drop the attribute.
return;
}
D->addAttr(::new (getASTContext())
ObjCReturnsInnerPointerAttr(getASTContext(), Attrs));
}
void SemaObjC::handleRequiresSuperAttr(Decl *D, const ParsedAttr &Attrs) {
const auto *Method = cast<ObjCMethodDecl>(D);
const DeclContext *DC = Method->getDeclContext();
if (const auto *PDecl = dyn_cast_if_present<ObjCProtocolDecl>(DC)) {
Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol)
<< Attrs << 0;
Diag(PDecl->getLocation(), diag::note_protocol_decl);
return;
}
if (Method->getMethodFamily() == OMF_dealloc) {
Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol)
<< Attrs << 1;
return;
}
D->addAttr(::new (getASTContext())
ObjCRequiresSuperAttr(getASTContext(), Attrs));
}
void SemaObjC::handleNSErrorDomain(Decl *D, const ParsedAttr &Attr) {
if (!isa<TagDecl>(D)) {
Diag(D->getBeginLoc(), diag::err_nserrordomain_invalid_decl) << 0;
return;
}
IdentifierLoc *IdentLoc =
Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
if (!IdentLoc || !IdentLoc->getIdentifierInfo()) {
// Try to locate the argument directly.
SourceLocation Loc = Attr.getLoc();
if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0))
Loc = Attr.getArgAsExpr(0)->getBeginLoc();
Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
return;
}
// Verify that the identifier is a valid decl in the C decl namespace.
LookupResult Result(SemaRef, DeclarationName(IdentLoc->getIdentifierInfo()),
SourceLocation(),
Sema::LookupNameKind::LookupOrdinaryName);
if (!SemaRef.LookupName(Result, SemaRef.TUScope) ||
!Result.getAsSingle<VarDecl>()) {
Diag(IdentLoc->getLoc(), diag::err_nserrordomain_invalid_decl)
<< 1 << IdentLoc->getIdentifierInfo();
return;
}
D->addAttr(::new (getASTContext()) NSErrorDomainAttr(
getASTContext(), Attr, IdentLoc->getIdentifierInfo()));
}
void SemaObjC::handleBridgeAttr(Decl *D, const ParsedAttr &AL) {
IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
if (!Parm) {
Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
return;
}
// Typedefs only allow objc_bridge(id) and have some additional checking.
if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
if (!Parm->getIdentifierInfo()->isStr("id")) {
Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
return;
}
// Only allow 'cv void *'.
QualType T = TD->getUnderlyingType();
if (!T->isVoidPointerType()) {
Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
return;
}
}
D->addAttr(::new (getASTContext()) ObjCBridgeAttr(getASTContext(), AL,
Parm->getIdentifierInfo()));
}
void SemaObjC::handleBridgeMutableAttr(Decl *D, const ParsedAttr &AL) {
IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
if (!Parm) {
Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
return;
}
D->addAttr(::new (getASTContext()) ObjCBridgeMutableAttr(
getASTContext(), AL, Parm->getIdentifierInfo()));
}
void SemaObjC::handleBridgeRelatedAttr(Decl *D, const ParsedAttr &AL) {
IdentifierInfo *RelatedClass =
AL.isArgIdent(0) ? AL.getArgAsIdent(0)->getIdentifierInfo() : nullptr;
if (!RelatedClass) {
Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
return;
}
IdentifierInfo *ClassMethod =
AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->getIdentifierInfo() : nullptr;
IdentifierInfo *InstanceMethod =
AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->getIdentifierInfo() : nullptr;
D->addAttr(::new (getASTContext()) ObjCBridgeRelatedAttr(
getASTContext(), AL, RelatedClass, ClassMethod, InstanceMethod));
}
void SemaObjC::handleDesignatedInitializer(Decl *D, const ParsedAttr &AL) {
DeclContext *Ctx = D->getDeclContext();
// This attribute can only be applied to methods in interfaces or class
// extensions.
if (!isa<ObjCInterfaceDecl>(Ctx) &&
!(isa<ObjCCategoryDecl>(Ctx) &&
cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
return;
}
ObjCInterfaceDecl *IFace;
if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
IFace = CatDecl->getClassInterface();
else
IFace = cast<ObjCInterfaceDecl>(Ctx);
if (!IFace)
return;
IFace->setHasDesignatedInitializers();
D->addAttr(::new (getASTContext())
ObjCDesignatedInitializerAttr(getASTContext(), AL));
}
void SemaObjC::handleRuntimeName(Decl *D, const ParsedAttr &AL) {
StringRef MetaDataName;
if (!SemaRef.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
return;
D->addAttr(::new (getASTContext())
ObjCRuntimeNameAttr(getASTContext(), AL, MetaDataName));
}
// When a user wants to use objc_boxable with a union or struct
// but they don't have access to the declaration (legacy/third-party code)
// then they can 'enable' this feature with a typedef:
// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
void SemaObjC::handleBoxable(Decl *D, const ParsedAttr &AL) {
bool notify = false;
auto *RD = dyn_cast<RecordDecl>(D);
if (RD && RD->getDefinition()) {
RD = RD->getDefinition();
notify = true;
}
if (RD) {
ObjCBoxableAttr *BoxableAttr =
::new (getASTContext()) ObjCBoxableAttr(getASTContext(), AL);
RD->addAttr(BoxableAttr);
if (notify) {
// we need to notify ASTReader/ASTWriter about
// modification of existing declaration
if (ASTMutationListener *L = SemaRef.getASTMutationListener())
L->AddedAttributeToRecord(BoxableAttr, RD);
}
}
}
void SemaObjC::handleOwnershipAttr(Decl *D, const ParsedAttr &AL) {
if (hasDeclarator(D))
return;
Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
<< AL.getRange() << AL << AL.isRegularKeywordAttribute()
<< ExpectedVariable;
}
void SemaObjC::handlePreciseLifetimeAttr(Decl *D, const ParsedAttr &AL) {
const auto *VD = cast<ValueDecl>(D);
QualType QT = VD->getType();
if (!QT->isDependentType() && !QT->isObjCLifetimeType()) {
Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) << QT;
return;
}
Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
// If we have no lifetime yet, check the lifetime we're presumably
// going to infer.
if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
Lifetime = QT->getObjCARCImplicitLifetime();
switch (Lifetime) {
case Qualifiers::OCL_None:
assert(QT->isDependentType() &&
"didn't infer lifetime for non-dependent type?");
break;
case Qualifiers::OCL_Weak: // meaningful
case Qualifiers::OCL_Strong: // meaningful
break;
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Autoreleasing:
Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
<< (Lifetime == Qualifiers::OCL_Autoreleasing);
break;
}
D->addAttr(::new (getASTContext())
ObjCPreciseLifetimeAttr(getASTContext(), AL));
}
static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
bool DiagnoseFailure) {
QualType Ty = VD->getType();
if (!Ty->isObjCRetainableType()) {
if (DiagnoseFailure) {
S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
<< 0;
}
return false;
}
Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
// SemaObjC::inferObjCARCLifetime must run after processing decl attributes
// (because __block lowers to an attribute), so if the lifetime hasn't been
// explicitly specified, infer it locally now.
if (LifetimeQual == Qualifiers::OCL_None)
LifetimeQual = Ty->getObjCARCImplicitLifetime();
// The attributes only really makes sense for __strong variables; ignore any
// attempts to annotate a parameter with any other lifetime qualifier.
if (LifetimeQual != Qualifiers::OCL_Strong) {
if (DiagnoseFailure) {
S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
<< 1;
}
return false;
}
// Tampering with the type of a VarDecl here is a bit of a hack, but we need
// to ensure that the variable is 'const' so that we can error on
// modification, which can otherwise over-release.
VD->setType(Ty.withConst());
VD->setARCPseudoStrong(true);
return true;
}
void SemaObjC::handleExternallyRetainedAttr(Decl *D, const ParsedAttr &AL) {
if (auto *VD = dyn_cast<VarDecl>(D)) {
assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
if (!VD->hasLocalStorage()) {
Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained) << 0;
return;
}
if (!tryMakeVariablePseudoStrong(SemaRef, VD, /*DiagnoseFailure=*/true))
return;
handleSimpleAttribute<ObjCExternallyRetainedAttr>(*this, D, AL);
return;
}
// If D is a function-like declaration (method, block, or function), then we
// make every parameter psuedo-strong.
unsigned NumParams =
hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
for (unsigned I = 0; I != NumParams; ++I) {
auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
QualType Ty = PVD->getType();
// If a user wrote a parameter with __strong explicitly, then assume they
// want "real" strong semantics for that parameter. This works because if
// the parameter was written with __strong, then the strong qualifier will
// be non-local.
if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
Qualifiers::OCL_Strong)
continue;
tryMakeVariablePseudoStrong(SemaRef, PVD, /*DiagnoseFailure=*/false);
}
handleSimpleAttribute<ObjCExternallyRetainedAttr>(*this, D, AL);
}
bool SemaObjC::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
Sema::FormatStringInfo FSI;
if ((SemaRef.GetFormatStringType(Format) == FormatStringType::NSString) &&
SemaRef.getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
false, true, &FSI)) {
Idx = FSI.FormatIdx;
return true;
}
return false;
}
/// Diagnose use of %s directive in an NSString which is being passed
/// as formatting string to formatting method.
void SemaObjC::DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl,
Expr **Args,
unsigned NumArgs) {
unsigned Idx = 0;
bool Format = false;
ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Idx = 2;
Format = true;
} else
for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
if (GetFormatNSStringIdx(I, Idx)) {
Format = true;
break;
}
}
if (!Format || NumArgs <= Idx)
return;
const Expr *FormatExpr = Args[Idx];
if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
FormatExpr = CSCE->getSubExpr();
const StringLiteral *FormatString;
if (const ObjCStringLiteral *OSL =
dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
FormatString = OSL->getString();
else
FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
if (!FormatString)
return;
if (SemaRef.FormatStringHasSArg(FormatString)) {
Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
<< "%s" << 1 << 1;
Diag(FDecl->getLocation(), diag::note_entity_declared_at)
<< FDecl->getDeclName();
}
}
bool SemaObjC::isSignedCharBool(QualType Ty) {
return Ty->isSpecificBuiltinType(BuiltinType::SChar) && getLangOpts().ObjC &&
NSAPIObj->isObjCBOOLType(Ty);
}
void SemaObjC::adornBoolConversionDiagWithTernaryFixit(
const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
const Expr *Ignored = SourceExpr->IgnoreImplicit();
if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
Ignored = OVE->getSourceExpr();
bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
isa<BinaryOperator>(Ignored) ||
isa<CXXOperatorCallExpr>(Ignored);
SourceLocation EndLoc = SemaRef.getLocForEndOfToken(SourceExpr->getEndLoc());
if (NeedsParens)
Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
<< FixItHint::CreateInsertion(EndLoc, ")");
Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
}
/// Check a single element within a collection literal against the
/// target element type.
static void checkCollectionLiteralElement(Sema &S, QualType TargetElementType,
Expr *Element, unsigned ElementKind) {
// Skip a bitcast to 'id' or qualified 'id'.
if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
if (ICE->getCastKind() == CK_BitCast &&
ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
Element = ICE->getSubExpr();
}
QualType ElementType = Element->getType();
ExprResult ElementResult(Element);
if (ElementType->getAs<ObjCObjectPointerType>() &&
!S.IsAssignConvertCompatible(S.CheckSingleAssignmentConstraints(
TargetElementType, ElementResult, false, false))) {
S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
<< ElementType << ElementKind << TargetElementType
<< Element->getSourceRange();
}
if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
S.ObjC().checkArrayLiteral(TargetElementType, ArrayLiteral);
else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
S.ObjC().checkDictionaryLiteral(TargetElementType, DictionaryLiteral);
}
/// Check an Objective-C array literal being converted to the given
/// target type.
void SemaObjC::checkArrayLiteral(QualType TargetType,
ObjCArrayLiteral *ArrayLiteral) {
if (!NSArrayDecl)
return;
const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
if (!TargetObjCPtr)
return;
if (TargetObjCPtr->isUnspecialized() ||
TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() !=
NSArrayDecl->getCanonicalDecl())
return;
auto TypeArgs = TargetObjCPtr->getTypeArgs();
if (TypeArgs.size() != 1)
return;
QualType TargetElementType = TypeArgs[0];
for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
checkCollectionLiteralElement(SemaRef, TargetElementType,
ArrayLiteral->getElement(I), 0);
}
}
void SemaObjC::checkDictionaryLiteral(
QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral) {
if (!NSDictionaryDecl)
return;
const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
if (!TargetObjCPtr)
return;
if (TargetObjCPtr->isUnspecialized() ||
TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() !=
NSDictionaryDecl->getCanonicalDecl())
return;
auto TypeArgs = TargetObjCPtr->getTypeArgs();
if (TypeArgs.size() != 2)
return;
QualType TargetKeyType = TypeArgs[0];
QualType TargetObjectType = TypeArgs[1];
for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
auto Element = DictionaryLiteral->getKeyValueElement(I);
checkCollectionLiteralElement(SemaRef, TargetKeyType, Element.Key, 1);
checkCollectionLiteralElement(SemaRef, TargetObjectType, Element.Value, 2);
}
}
} // namespace clang
|