1//===----- SemaObjC.cpp ---- Semantic Analysis for Objective-C ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements semantic analysis for Objective-C.
10///
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/SemaObjC.h"
14#include "clang/AST/ASTMutationListener.h"
15#include "clang/AST/EvaluatedExprVisitor.h"
16#include "clang/AST/StmtObjC.h"
17#include "clang/Basic/DiagnosticSema.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Sema/Attr.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/ParsedAttr.h"
22#include "clang/Sema/ScopeInfo.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/TemplateDeduction.h"
25#include "llvm/Support/ConvertUTF.h"
26
27namespace clang {
28
29SemaObjC::SemaObjC(Sema &S)
30 : SemaBase(S), NSNumberDecl(nullptr), NSValueDecl(nullptr),
31 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
32 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
33 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
34 DictionaryWithObjectsMethod(nullptr) {}
35
36StmtResult SemaObjC::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
37 Stmt *First, Expr *collection,
38 SourceLocation RParenLoc) {
39 ASTContext &Context = getASTContext();
40 SemaRef.setFunctionHasBranchProtectedScope();
41
42 ExprResult CollectionExprResult =
43 CheckObjCForCollectionOperand(forLoc: ForLoc, collection);
44
45 if (First) {
46 QualType FirstType;
47 if (DeclStmt *DS = dyn_cast<DeclStmt>(Val: First)) {
48 if (!DS->isSingleDecl())
49 return StmtError(Diag((*DS->decl_begin())->getLocation(),
50 diag::err_toomany_element_decls));
51
52 VarDecl *D = dyn_cast<VarDecl>(Val: DS->getSingleDecl());
53 if (!D || D->isInvalidDecl())
54 return StmtError();
55
56 FirstType = D->getType();
57 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
58 // declare identifiers for objects having storage class 'auto' or
59 // 'register'.
60 if (!D->hasLocalStorage())
61 return StmtError(
62 Diag(D->getLocation(), diag::err_non_local_variable_decl_in_for));
63
64 // If the type contained 'auto', deduce the 'auto' to 'id'.
65 if (FirstType->getContainedAutoType()) {
66 SourceLocation Loc = D->getLocation();
67 OpaqueValueExpr OpaqueId(Loc, Context.getObjCIdType(), VK_PRValue);
68 Expr *DeducedInit = &OpaqueId;
69 sema::TemplateDeductionInfo Info(Loc);
70 FirstType = QualType();
71 TemplateDeductionResult Result = SemaRef.DeduceAutoType(
72 AutoTypeLoc: D->getTypeSourceInfo()->getTypeLoc(), Initializer: DeducedInit, Result&: FirstType, Info);
73 if (Result != TemplateDeductionResult::Success &&
74 Result != TemplateDeductionResult::AlreadyDiagnosed)
75 SemaRef.DiagnoseAutoDeductionFailure(VDecl: D, Init: DeducedInit);
76 if (FirstType.isNull()) {
77 D->setInvalidDecl();
78 return StmtError();
79 }
80
81 D->setType(FirstType);
82
83 if (!SemaRef.inTemplateInstantiation()) {
84 SourceLocation Loc =
85 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
86 Diag(Loc, diag::warn_auto_var_is_id) << D->getDeclName();
87 }
88 }
89
90 } else {
91 Expr *FirstE = cast<Expr>(Val: First);
92 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
93 return StmtError(
94 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
95 << First->getSourceRange());
96
97 FirstType = static_cast<Expr *>(First)->getType();
98 if (FirstType.isConstQualified())
99 Diag(ForLoc, diag::err_selector_element_const_type)
100 << FirstType << First->getSourceRange();
101 }
102 if (!FirstType->isDependentType() &&
103 !FirstType->isObjCObjectPointerType() &&
104 !FirstType->isBlockPointerType())
105 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
106 << FirstType << First->getSourceRange());
107 }
108
109 if (CollectionExprResult.isInvalid())
110 return StmtError();
111
112 CollectionExprResult = SemaRef.ActOnFinishFullExpr(Expr: CollectionExprResult.get(),
113 /*DiscardedValue*/ false);
114 if (CollectionExprResult.isInvalid())
115 return StmtError();
116
117 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
118 nullptr, ForLoc, RParenLoc);
119}
120
121ExprResult SemaObjC::CheckObjCForCollectionOperand(SourceLocation forLoc,
122 Expr *collection) {
123 ASTContext &Context = getASTContext();
124 if (!collection)
125 return ExprError();
126
127 ExprResult result = SemaRef.CorrectDelayedTyposInExpr(E: collection);
128 if (!result.isUsable())
129 return ExprError();
130 collection = result.get();
131
132 // Bail out early if we've got a type-dependent expression.
133 if (collection->isTypeDependent())
134 return collection;
135
136 // Perform normal l-value conversion.
137 result = SemaRef.DefaultFunctionArrayLvalueConversion(E: collection);
138 if (result.isInvalid())
139 return ExprError();
140 collection = result.get();
141
142 // The operand needs to have object-pointer type.
143 // TODO: should we do a contextual conversion?
144 const ObjCObjectPointerType *pointerType =
145 collection->getType()->getAs<ObjCObjectPointerType>();
146 if (!pointerType)
147 return Diag(forLoc, diag::err_collection_expr_type)
148 << collection->getType() << collection->getSourceRange();
149
150 // Check that the operand provides
151 // - countByEnumeratingWithState:objects:count:
152 const ObjCObjectType *objectType = pointerType->getObjectType();
153 ObjCInterfaceDecl *iface = objectType->getInterface();
154
155 // If we have a forward-declared type, we can't do this check.
156 // Under ARC, it is an error not to have a forward-declared class.
157 if (iface &&
158 (getLangOpts().ObjCAutoRefCount
159 ? SemaRef.RequireCompleteType(forLoc, QualType(objectType, 0),
160 diag::err_arc_collection_forward,
161 collection)
162 : !SemaRef.isCompleteType(forLoc, QualType(objectType, 0)))) {
163 // Otherwise, if we have any useful type information, check that
164 // the type declares the appropriate method.
165 } else if (iface || !objectType->qual_empty()) {
166 const IdentifierInfo *selectorIdents[] = {
167 &Context.Idents.get(Name: "countByEnumeratingWithState"),
168 &Context.Idents.get(Name: "objects"), &Context.Idents.get(Name: "count")};
169 Selector selector = Context.Selectors.getSelector(NumArgs: 3, IIV: &selectorIdents[0]);
170
171 ObjCMethodDecl *method = nullptr;
172
173 // If there's an interface, look in both the public and private APIs.
174 if (iface) {
175 method = iface->lookupInstanceMethod(Sel: selector);
176 if (!method)
177 method = iface->lookupPrivateMethod(Sel: selector);
178 }
179
180 // Also check protocol qualifiers.
181 if (!method)
182 method = LookupMethodInQualifiedType(Sel: selector, OPT: pointerType,
183 /*instance*/ IsInstance: true);
184
185 // If we didn't find it anywhere, give up.
186 if (!method) {
187 Diag(forLoc, diag::warn_collection_expr_type)
188 << collection->getType() << selector << collection->getSourceRange();
189 }
190
191 // TODO: check for an incompatible signature?
192 }
193
194 // Wrap up any cleanups in the expression.
195 return collection;
196}
197
198StmtResult SemaObjC::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
199 if (!S || !B)
200 return StmtError();
201 ObjCForCollectionStmt *ForStmt = cast<ObjCForCollectionStmt>(Val: S);
202
203 ForStmt->setBody(B);
204 return S;
205}
206
207StmtResult SemaObjC::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
208 SourceLocation RParen, Decl *Parm,
209 Stmt *Body) {
210 ASTContext &Context = getASTContext();
211 VarDecl *Var = cast_or_null<VarDecl>(Val: Parm);
212 if (Var && Var->isInvalidDecl())
213 return StmtError();
214
215 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
216}
217
218StmtResult SemaObjC::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
219 ASTContext &Context = getASTContext();
220 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
221}
222
223StmtResult SemaObjC::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
224 MultiStmtArg CatchStmts,
225 Stmt *Finally) {
226 ASTContext &Context = getASTContext();
227 if (!getLangOpts().ObjCExceptions)
228 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
229
230 // Objective-C try is incompatible with SEH __try.
231 sema::FunctionScopeInfo *FSI = SemaRef.getCurFunction();
232 if (FSI->FirstSEHTryLoc.isValid()) {
233 Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1;
234 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
235 }
236
237 FSI->setHasObjCTry(AtLoc);
238 unsigned NumCatchStmts = CatchStmts.size();
239 return ObjCAtTryStmt::Create(Context, atTryLoc: AtLoc, atTryStmt: Try, CatchStmts: CatchStmts.data(),
240 NumCatchStmts, atFinallyStmt: Finally);
241}
242
243StmtResult SemaObjC::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
244 ASTContext &Context = getASTContext();
245 if (Throw) {
246 ExprResult Result = SemaRef.DefaultLvalueConversion(E: Throw);
247 if (Result.isInvalid())
248 return StmtError();
249
250 Result =
251 SemaRef.ActOnFinishFullExpr(Expr: Result.get(), /*DiscardedValue*/ false);
252 if (Result.isInvalid())
253 return StmtError();
254 Throw = Result.get();
255
256 QualType ThrowType = Throw->getType();
257 // Make sure the expression type is an ObjC pointer or "void *".
258 if (!ThrowType->isDependentType() &&
259 !ThrowType->isObjCObjectPointerType()) {
260 const PointerType *PT = ThrowType->getAs<PointerType>();
261 if (!PT || !PT->getPointeeType()->isVoidType())
262 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
263 << Throw->getType() << Throw->getSourceRange());
264 }
265 }
266
267 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
268}
269
270StmtResult SemaObjC::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
271 Scope *CurScope) {
272 if (!getLangOpts().ObjCExceptions)
273 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
274
275 if (!Throw) {
276 // @throw without an expression designates a rethrow (which must occur
277 // in the context of an @catch clause).
278 Scope *AtCatchParent = CurScope;
279 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
280 AtCatchParent = AtCatchParent->getParent();
281 if (!AtCatchParent)
282 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
283 }
284 return BuildObjCAtThrowStmt(AtLoc, Throw);
285}
286
287ExprResult SemaObjC::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
288 Expr *operand) {
289 ExprResult result = SemaRef.DefaultLvalueConversion(E: operand);
290 if (result.isInvalid())
291 return ExprError();
292 operand = result.get();
293
294 // Make sure the expression type is an ObjC pointer or "void *".
295 QualType type = operand->getType();
296 if (!type->isDependentType() && !type->isObjCObjectPointerType()) {
297 const PointerType *pointerType = type->getAs<PointerType>();
298 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
299 if (getLangOpts().CPlusPlus) {
300 if (SemaRef.RequireCompleteType(atLoc, type,
301 diag::err_incomplete_receiver_type))
302 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
303 << type << operand->getSourceRange();
304
305 ExprResult result =
306 SemaRef.PerformContextuallyConvertToObjCPointer(From: operand);
307 if (result.isInvalid())
308 return ExprError();
309 if (!result.isUsable())
310 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
311 << type << operand->getSourceRange();
312
313 operand = result.get();
314 } else {
315 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
316 << type << operand->getSourceRange();
317 }
318 }
319 }
320
321 // The operand to @synchronized is a full-expression.
322 return SemaRef.ActOnFinishFullExpr(Expr: operand, /*DiscardedValue*/ false);
323}
324
325StmtResult SemaObjC::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
326 Expr *SyncExpr,
327 Stmt *SyncBody) {
328 ASTContext &Context = getASTContext();
329 // We can't jump into or indirect-jump out of a @synchronized block.
330 SemaRef.setFunctionHasBranchProtectedScope();
331 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
332}
333
334StmtResult SemaObjC::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc,
335 Stmt *Body) {
336 ASTContext &Context = getASTContext();
337 SemaRef.setFunctionHasBranchProtectedScope();
338 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
339}
340
341TypeResult SemaObjC::actOnObjCProtocolQualifierType(
342 SourceLocation lAngleLoc, ArrayRef<Decl *> protocols,
343 ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc) {
344 ASTContext &Context = getASTContext();
345 // Form id<protocol-list>.
346 QualType Result = Context.getObjCObjectType(
347 Context.ObjCBuiltinIdTy, {},
348 llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
349 protocols.size()),
350 false);
351 Result = Context.getObjCObjectPointerType(OIT: Result);
352
353 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(T: Result);
354 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
355
356 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
357 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
358
359 auto ObjCObjectTL =
360 ObjCObjectPointerTL.getPointeeLoc().castAs<ObjCObjectTypeLoc>();
361 ObjCObjectTL.setHasBaseTypeAsWritten(false);
362 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
363
364 // No type arguments.
365 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
366 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
367
368 // Fill in protocol qualifiers.
369 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
370 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
371 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
372 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
373
374 // We're done. Return the completed type to the parser.
375 return SemaRef.CreateParsedType(T: Result, TInfo: ResultTInfo);
376}
377
378TypeResult SemaObjC::actOnObjCTypeArgsAndProtocolQualifiers(
379 Scope *S, SourceLocation Loc, ParsedType BaseType,
380 SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs,
381 SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc,
382 ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs,
383 SourceLocation ProtocolRAngleLoc) {
384 ASTContext &Context = getASTContext();
385 TypeSourceInfo *BaseTypeInfo = nullptr;
386 QualType T = SemaRef.GetTypeFromParser(Ty: BaseType, TInfo: &BaseTypeInfo);
387 if (T.isNull())
388 return true;
389
390 // Handle missing type-source info.
391 if (!BaseTypeInfo)
392 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
393
394 // Extract type arguments.
395 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
396 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
397 TypeSourceInfo *TypeArgInfo = nullptr;
398 QualType TypeArg = SemaRef.GetTypeFromParser(Ty: TypeArgs[i], TInfo: &TypeArgInfo);
399 if (TypeArg.isNull()) {
400 ActualTypeArgInfos.clear();
401 break;
402 }
403
404 assert(TypeArgInfo && "No type source info?");
405 ActualTypeArgInfos.push_back(Elt: TypeArgInfo);
406 }
407
408 // Build the object type.
409 QualType Result = BuildObjCObjectType(
410 BaseType: T, Loc: BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
411 TypeArgsLAngleLoc, TypeArgs: ActualTypeArgInfos, TypeArgsRAngleLoc,
412 ProtocolLAngleLoc,
413 Protocols: llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
414 Protocols.size()),
415 ProtocolLocs, ProtocolRAngleLoc,
416 /*FailOnError=*/false,
417 /*Rebuilding=*/false);
418
419 if (Result == T)
420 return BaseType;
421
422 // Create source information for this type.
423 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(T: Result);
424 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
425
426 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
427 // object pointer type. Fill in source information for it.
428 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
429 // The '*' is implicit.
430 ObjCObjectPointerTL.setStarLoc(SourceLocation());
431 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
432 }
433
434 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
435 // Protocol qualifier information.
436 if (OTPTL.getNumProtocols() > 0) {
437 assert(OTPTL.getNumProtocols() == Protocols.size());
438 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
439 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
440 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
441 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
442 }
443
444 // We're done. Return the completed type to the parser.
445 return SemaRef.CreateParsedType(T: Result, TInfo: ResultTInfo);
446 }
447
448 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
449
450 // Type argument information.
451 if (ObjCObjectTL.getNumTypeArgs() > 0) {
452 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
453 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
454 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
455 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
456 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
457 } else {
458 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
459 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
460 }
461
462 // Protocol qualifier information.
463 if (ObjCObjectTL.getNumProtocols() > 0) {
464 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
465 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
466 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
467 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
468 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
469 } else {
470 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
471 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
472 }
473
474 // Base type.
475 ObjCObjectTL.setHasBaseTypeAsWritten(true);
476 if (ObjCObjectTL.getType() == T)
477 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
478 else
479 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
480
481 // We're done. Return the completed type to the parser.
482 return SemaRef.CreateParsedType(T: Result, TInfo: ResultTInfo);
483}
484
485QualType SemaObjC::BuildObjCTypeParamType(
486 const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc,
487 ArrayRef<ObjCProtocolDecl *> Protocols,
488 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
489 bool FailOnError) {
490 ASTContext &Context = getASTContext();
491 QualType Result = QualType(Decl->getTypeForDecl(), 0);
492 if (!Protocols.empty()) {
493 bool HasError;
494 Result = Context.applyObjCProtocolQualifiers(type: Result, protocols: Protocols, hasError&: HasError);
495 if (HasError) {
496 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
497 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
498 if (FailOnError)
499 Result = QualType();
500 }
501 if (FailOnError && Result.isNull())
502 return QualType();
503 }
504
505 return Result;
506}
507
508/// Apply Objective-C type arguments to the given type.
509static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
510 ArrayRef<TypeSourceInfo *> typeArgs,
511 SourceRange typeArgsRange, bool failOnError,
512 bool rebuilding) {
513 // We can only apply type arguments to an Objective-C class type.
514 const auto *objcObjectType = type->getAs<ObjCObjectType>();
515 if (!objcObjectType || !objcObjectType->getInterface()) {
516 S.Diag(loc, diag::err_objc_type_args_non_class) << type << typeArgsRange;
517
518 if (failOnError)
519 return QualType();
520 return type;
521 }
522
523 // The class type must be parameterized.
524 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
525 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
526 if (!typeParams) {
527 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
528 << objcClass->getDeclName() << FixItHint::CreateRemoval(typeArgsRange);
529
530 if (failOnError)
531 return QualType();
532
533 return type;
534 }
535
536 // The type must not already be specialized.
537 if (objcObjectType->isSpecialized()) {
538 S.Diag(loc, diag::err_objc_type_args_specialized_class)
539 << type << FixItHint::CreateRemoval(typeArgsRange);
540
541 if (failOnError)
542 return QualType();
543
544 return type;
545 }
546
547 // Check the type arguments.
548 SmallVector<QualType, 4> finalTypeArgs;
549 unsigned numTypeParams = typeParams->size();
550 bool anyPackExpansions = false;
551 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
552 TypeSourceInfo *typeArgInfo = typeArgs[i];
553 QualType typeArg = typeArgInfo->getType();
554
555 // Type arguments cannot have explicit qualifiers or nullability.
556 // We ignore indirect sources of these, e.g. behind typedefs or
557 // template arguments.
558 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
559 bool diagnosed = false;
560 SourceRange rangeToRemove;
561 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
562 rangeToRemove = attr.getLocalSourceRange();
563 if (attr.getTypePtr()->getImmediateNullability()) {
564 typeArg = attr.getTypePtr()->getModifiedType();
565 S.Diag(attr.getBeginLoc(),
566 diag::err_objc_type_arg_explicit_nullability)
567 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
568 diagnosed = true;
569 }
570 }
571
572 // When rebuilding, qualifiers might have gotten here through a
573 // final substitution.
574 if (!rebuilding && !diagnosed) {
575 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
576 << typeArg << typeArg.getQualifiers().getAsString()
577 << FixItHint::CreateRemoval(rangeToRemove);
578 }
579 }
580
581 // Remove qualifiers even if they're non-local.
582 typeArg = typeArg.getUnqualifiedType();
583
584 finalTypeArgs.push_back(Elt: typeArg);
585
586 if (typeArg->getAs<PackExpansionType>())
587 anyPackExpansions = true;
588
589 // Find the corresponding type parameter, if there is one.
590 ObjCTypeParamDecl *typeParam = nullptr;
591 if (!anyPackExpansions) {
592 if (i < numTypeParams) {
593 typeParam = typeParams->begin()[i];
594 } else {
595 // Too many arguments.
596 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
597 << false << objcClass->getDeclName() << (unsigned)typeArgs.size()
598 << numTypeParams;
599 S.Diag(objcClass->getLocation(), diag::note_previous_decl) << objcClass;
600
601 if (failOnError)
602 return QualType();
603
604 return type;
605 }
606 }
607
608 // Objective-C object pointer types must be substitutable for the bounds.
609 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
610 // If we don't have a type parameter to match against, assume
611 // everything is fine. There was a prior pack expansion that
612 // means we won't be able to match anything.
613 if (!typeParam) {
614 assert(anyPackExpansions && "Too many arguments?");
615 continue;
616 }
617
618 // Retrieve the bound.
619 QualType bound = typeParam->getUnderlyingType();
620 const auto *boundObjC = bound->castAs<ObjCObjectPointerType>();
621
622 // Determine whether the type argument is substitutable for the bound.
623 if (typeArgObjC->isObjCIdType()) {
624 // When the type argument is 'id', the only acceptable type
625 // parameter bound is 'id'.
626 if (boundObjC->isObjCIdType())
627 continue;
628 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
629 // Otherwise, we follow the assignability rules.
630 continue;
631 }
632
633 // Diagnose the mismatch.
634 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
635 diag::err_objc_type_arg_does_not_match_bound)
636 << typeArg << bound << typeParam->getDeclName();
637 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
638 << typeParam->getDeclName();
639
640 if (failOnError)
641 return QualType();
642
643 return type;
644 }
645
646 // Block pointer types are permitted for unqualified 'id' bounds.
647 if (typeArg->isBlockPointerType()) {
648 // If we don't have a type parameter to match against, assume
649 // everything is fine. There was a prior pack expansion that
650 // means we won't be able to match anything.
651 if (!typeParam) {
652 assert(anyPackExpansions && "Too many arguments?");
653 continue;
654 }
655
656 // Retrieve the bound.
657 QualType bound = typeParam->getUnderlyingType();
658 if (bound->isBlockCompatibleObjCPointerType(ctx&: S.Context))
659 continue;
660
661 // Diagnose the mismatch.
662 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
663 diag::err_objc_type_arg_does_not_match_bound)
664 << typeArg << bound << typeParam->getDeclName();
665 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
666 << typeParam->getDeclName();
667
668 if (failOnError)
669 return QualType();
670
671 return type;
672 }
673
674 // Types that have __attribute__((NSObject)) are permitted.
675 if (typeArg->isObjCNSObjectType()) {
676 continue;
677 }
678
679 // Dependent types will be checked at instantiation time.
680 if (typeArg->isDependentType()) {
681 continue;
682 }
683
684 // Diagnose non-id-compatible type arguments.
685 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
686 diag::err_objc_type_arg_not_id_compatible)
687 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
688
689 if (failOnError)
690 return QualType();
691
692 return type;
693 }
694
695 // Make sure we didn't have the wrong number of arguments.
696 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
697 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
698 << (typeArgs.size() < typeParams->size()) << objcClass->getDeclName()
699 << (unsigned)finalTypeArgs.size() << (unsigned)numTypeParams;
700 S.Diag(objcClass->getLocation(), diag::note_previous_decl) << objcClass;
701
702 if (failOnError)
703 return QualType();
704
705 return type;
706 }
707
708 // Success. Form the specialized type.
709 return S.Context.getObjCObjectType(Base: type, typeArgs: finalTypeArgs, protocols: {}, isKindOf: false);
710}
711
712QualType SemaObjC::BuildObjCObjectType(
713 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
714 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
715 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
716 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
717 bool FailOnError, bool Rebuilding) {
718 ASTContext &Context = getASTContext();
719 QualType Result = BaseType;
720 if (!TypeArgs.empty()) {
721 Result =
722 applyObjCTypeArgs(S&: SemaRef, loc: Loc, type: Result, typeArgs: TypeArgs,
723 typeArgsRange: SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
724 failOnError: FailOnError, rebuilding: Rebuilding);
725 if (FailOnError && Result.isNull())
726 return QualType();
727 }
728
729 if (!Protocols.empty()) {
730 bool HasError;
731 Result = Context.applyObjCProtocolQualifiers(type: Result, protocols: Protocols, hasError&: HasError);
732 if (HasError) {
733 Diag(Loc, diag::err_invalid_protocol_qualifiers)
734 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
735 if (FailOnError)
736 Result = QualType();
737 }
738 if (FailOnError && Result.isNull())
739 return QualType();
740 }
741
742 return Result;
743}
744
745ParsedType SemaObjC::ActOnObjCInstanceType(SourceLocation Loc) {
746 ASTContext &Context = getASTContext();
747 QualType T = Context.getObjCInstanceType();
748 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
749 return SemaRef.CreateParsedType(T, TInfo);
750}
751
752//===--- CHECK: Objective-C retain cycles ----------------------------------//
753
754namespace {
755
756struct RetainCycleOwner {
757 VarDecl *Variable = nullptr;
758 SourceRange Range;
759 SourceLocation Loc;
760 bool Indirect = false;
761
762 RetainCycleOwner() = default;
763
764 void setLocsFrom(Expr *e) {
765 Loc = e->getExprLoc();
766 Range = e->getSourceRange();
767 }
768};
769
770} // namespace
771
772/// Consider whether capturing the given variable can possibly lead to
773/// a retain cycle.
774static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
775 // In ARC, it's captured strongly iff the variable has __strong
776 // lifetime. In MRR, it's captured strongly if the variable is
777 // __block and has an appropriate type.
778 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
779 return false;
780
781 owner.Variable = var;
782 if (ref)
783 owner.setLocsFrom(ref);
784 return true;
785}
786
787static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
788 while (true) {
789 e = e->IgnoreParens();
790 if (CastExpr *cast = dyn_cast<CastExpr>(Val: e)) {
791 switch (cast->getCastKind()) {
792 case CK_BitCast:
793 case CK_LValueBitCast:
794 case CK_LValueToRValue:
795 case CK_ARCReclaimReturnedObject:
796 e = cast->getSubExpr();
797 continue;
798
799 default:
800 return false;
801 }
802 }
803
804 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(Val: e)) {
805 ObjCIvarDecl *ivar = ref->getDecl();
806 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
807 return false;
808
809 // Try to find a retain cycle in the base.
810 if (!findRetainCycleOwner(S, e: ref->getBase(), owner))
811 return false;
812
813 if (ref->isFreeIvar())
814 owner.setLocsFrom(ref);
815 owner.Indirect = true;
816 return true;
817 }
818
819 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(Val: e)) {
820 VarDecl *var = dyn_cast<VarDecl>(Val: ref->getDecl());
821 if (!var)
822 return false;
823 return considerVariable(var, ref, owner);
824 }
825
826 if (MemberExpr *member = dyn_cast<MemberExpr>(Val: e)) {
827 if (member->isArrow())
828 return false;
829
830 // Don't count this as an indirect ownership.
831 e = member->getBase();
832 continue;
833 }
834
835 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(Val: e)) {
836 // Only pay attention to pseudo-objects on property references.
837 ObjCPropertyRefExpr *pre = dyn_cast<ObjCPropertyRefExpr>(
838 Val: pseudo->getSyntacticForm()->IgnoreParens());
839 if (!pre)
840 return false;
841 if (pre->isImplicitProperty())
842 return false;
843 ObjCPropertyDecl *property = pre->getExplicitProperty();
844 if (!property->isRetaining() &&
845 !(property->getPropertyIvarDecl() &&
846 property->getPropertyIvarDecl()->getType().getObjCLifetime() ==
847 Qualifiers::OCL_Strong))
848 return false;
849
850 owner.Indirect = true;
851 if (pre->isSuperReceiver()) {
852 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
853 if (!owner.Variable)
854 return false;
855 owner.Loc = pre->getLocation();
856 owner.Range = pre->getSourceRange();
857 return true;
858 }
859 e = const_cast<Expr *>(
860 cast<OpaqueValueExpr>(Val: pre->getBase())->getSourceExpr());
861 continue;
862 }
863
864 // Array ivars?
865
866 return false;
867 }
868}
869
870namespace {
871
872struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
873 VarDecl *Variable;
874 Expr *Capturer = nullptr;
875 bool VarWillBeReased = false;
876
877 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
878 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), Variable(variable) {}
879
880 void VisitDeclRefExpr(DeclRefExpr *ref) {
881 if (ref->getDecl() == Variable && !Capturer)
882 Capturer = ref;
883 }
884
885 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
886 if (Capturer)
887 return;
888 Visit(ref->getBase());
889 if (Capturer && ref->isFreeIvar())
890 Capturer = ref;
891 }
892
893 void VisitBlockExpr(BlockExpr *block) {
894 // Look inside nested blocks
895 if (block->getBlockDecl()->capturesVariable(var: Variable))
896 Visit(S: block->getBlockDecl()->getBody());
897 }
898
899 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
900 if (Capturer)
901 return;
902 if (OVE->getSourceExpr())
903 Visit(OVE->getSourceExpr());
904 }
905
906 void VisitBinaryOperator(BinaryOperator *BinOp) {
907 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
908 return;
909 Expr *LHS = BinOp->getLHS();
910 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(Val: LHS)) {
911 if (DRE->getDecl() != Variable)
912 return;
913 if (Expr *RHS = BinOp->getRHS()) {
914 RHS = RHS->IgnoreParenCasts();
915 std::optional<llvm::APSInt> Value;
916 VarWillBeReased =
917 (RHS && (Value = RHS->getIntegerConstantExpr(Ctx: Context)) &&
918 *Value == 0);
919 }
920 }
921 }
922};
923
924} // namespace
925
926/// Check whether the given argument is a block which captures a
927/// variable.
928static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
929 assert(owner.Variable && owner.Loc.isValid());
930
931 e = e->IgnoreParenCasts();
932
933 // Look through [^{...} copy] and Block_copy(^{...}).
934 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Val: e)) {
935 Selector Cmd = ME->getSelector();
936 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(argIndex: 0) == "copy") {
937 e = ME->getInstanceReceiver();
938 if (!e)
939 return nullptr;
940 e = e->IgnoreParenCasts();
941 }
942 } else if (CallExpr *CE = dyn_cast<CallExpr>(Val: e)) {
943 if (CE->getNumArgs() == 1) {
944 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: CE->getCalleeDecl());
945 if (Fn) {
946 const IdentifierInfo *FnI = Fn->getIdentifier();
947 if (FnI && FnI->isStr(Str: "_Block_copy")) {
948 e = CE->getArg(Arg: 0)->IgnoreParenCasts();
949 }
950 }
951 }
952 }
953
954 BlockExpr *block = dyn_cast<BlockExpr>(Val: e);
955 if (!block || !block->getBlockDecl()->capturesVariable(var: owner.Variable))
956 return nullptr;
957
958 FindCaptureVisitor visitor(S.Context, owner.Variable);
959 visitor.Visit(S: block->getBlockDecl()->getBody());
960 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
961}
962
963static void diagnoseRetainCycle(Sema &S, Expr *capturer,
964 RetainCycleOwner &owner) {
965 assert(capturer);
966 assert(owner.Variable && owner.Loc.isValid());
967
968 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
969 << owner.Variable << capturer->getSourceRange();
970 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
971 << owner.Indirect << owner.Range;
972}
973
974/// Check for a keyword selector that starts with the word 'add' or
975/// 'set'.
976static bool isSetterLikeSelector(Selector sel) {
977 if (sel.isUnarySelector())
978 return false;
979
980 StringRef str = sel.getNameForSlot(argIndex: 0);
981 str = str.ltrim(Char: '_');
982 if (str.starts_with(Prefix: "set"))
983 str = str.substr(Start: 3);
984 else if (str.starts_with(Prefix: "add")) {
985 // Specially allow 'addOperationWithBlock:'.
986 if (sel.getNumArgs() == 1 && str.starts_with(Prefix: "addOperationWithBlock"))
987 return false;
988 str = str.substr(Start: 3);
989 } else
990 return false;
991
992 if (str.empty())
993 return true;
994 return !isLowercase(c: str.front());
995}
996
997static std::optional<int>
998GetNSMutableArrayArgumentIndex(SemaObjC &S, ObjCMessageExpr *Message) {
999 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
1000 InterfaceDecl: Message->getReceiverInterface(), NSClassKind: NSAPI::ClassId_NSMutableArray);
1001 if (!IsMutableArray) {
1002 return std::nullopt;
1003 }
1004
1005 Selector Sel = Message->getSelector();
1006
1007 std::optional<NSAPI::NSArrayMethodKind> MKOpt =
1008 S.NSAPIObj->getNSArrayMethodKind(Sel);
1009 if (!MKOpt) {
1010 return std::nullopt;
1011 }
1012
1013 NSAPI::NSArrayMethodKind MK = *MKOpt;
1014
1015 switch (MK) {
1016 case NSAPI::NSMutableArr_addObject:
1017 case NSAPI::NSMutableArr_insertObjectAtIndex:
1018 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
1019 return 0;
1020 case NSAPI::NSMutableArr_replaceObjectAtIndex:
1021 return 1;
1022
1023 default:
1024 return std::nullopt;
1025 }
1026
1027 return std::nullopt;
1028}
1029
1030static std::optional<int>
1031GetNSMutableDictionaryArgumentIndex(SemaObjC &S, ObjCMessageExpr *Message) {
1032 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
1033 InterfaceDecl: Message->getReceiverInterface(), NSClassKind: NSAPI::ClassId_NSMutableDictionary);
1034 if (!IsMutableDictionary) {
1035 return std::nullopt;
1036 }
1037
1038 Selector Sel = Message->getSelector();
1039
1040 std::optional<NSAPI::NSDictionaryMethodKind> MKOpt =
1041 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
1042 if (!MKOpt) {
1043 return std::nullopt;
1044 }
1045
1046 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
1047
1048 switch (MK) {
1049 case NSAPI::NSMutableDict_setObjectForKey:
1050 case NSAPI::NSMutableDict_setValueForKey:
1051 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
1052 return 0;
1053
1054 default:
1055 return std::nullopt;
1056 }
1057
1058 return std::nullopt;
1059}
1060
1061static std::optional<int> GetNSSetArgumentIndex(SemaObjC &S,
1062 ObjCMessageExpr *Message) {
1063 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
1064 InterfaceDecl: Message->getReceiverInterface(), NSClassKind: NSAPI::ClassId_NSMutableSet);
1065
1066 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
1067 InterfaceDecl: Message->getReceiverInterface(), NSClassKind: NSAPI::ClassId_NSMutableOrderedSet);
1068 if (!IsMutableSet && !IsMutableOrderedSet) {
1069 return std::nullopt;
1070 }
1071
1072 Selector Sel = Message->getSelector();
1073
1074 std::optional<NSAPI::NSSetMethodKind> MKOpt =
1075 S.NSAPIObj->getNSSetMethodKind(Sel);
1076 if (!MKOpt) {
1077 return std::nullopt;
1078 }
1079
1080 NSAPI::NSSetMethodKind MK = *MKOpt;
1081
1082 switch (MK) {
1083 case NSAPI::NSMutableSet_addObject:
1084 case NSAPI::NSOrderedSet_setObjectAtIndex:
1085 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
1086 case NSAPI::NSOrderedSet_insertObjectAtIndex:
1087 return 0;
1088 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
1089 return 1;
1090 }
1091
1092 return std::nullopt;
1093}
1094
1095void SemaObjC::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
1096 if (!Message->isInstanceMessage()) {
1097 return;
1098 }
1099
1100 std::optional<int> ArgOpt;
1101
1102 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(S&: *this, Message)) &&
1103 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(S&: *this, Message)) &&
1104 !(ArgOpt = GetNSSetArgumentIndex(S&: *this, Message))) {
1105 return;
1106 }
1107
1108 int ArgIndex = *ArgOpt;
1109
1110 Expr *Arg = Message->getArg(Arg: ArgIndex)->IgnoreImpCasts();
1111 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Val: Arg)) {
1112 Arg = OE->getSourceExpr()->IgnoreImpCasts();
1113 }
1114
1115 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1116 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Val: Arg)) {
1117 if (ArgRE->isObjCSelfExpr()) {
1118 Diag(Message->getSourceRange().getBegin(),
1119 diag::warn_objc_circular_container)
1120 << ArgRE->getDecl() << StringRef("'super'");
1121 }
1122 }
1123 } else {
1124 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
1125
1126 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Val: Receiver)) {
1127 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
1128 }
1129
1130 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Val: Receiver)) {
1131 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Val: Arg)) {
1132 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
1133 ValueDecl *Decl = ReceiverRE->getDecl();
1134 Diag(Message->getSourceRange().getBegin(),
1135 diag::warn_objc_circular_container)
1136 << Decl << Decl;
1137 if (!ArgRE->isObjCSelfExpr()) {
1138 Diag(Decl->getLocation(),
1139 diag::note_objc_circular_container_declared_here)
1140 << Decl;
1141 }
1142 }
1143 }
1144 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Val: Receiver)) {
1145 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Val: Arg)) {
1146 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
1147 ObjCIvarDecl *Decl = IvarRE->getDecl();
1148 Diag(Message->getSourceRange().getBegin(),
1149 diag::warn_objc_circular_container)
1150 << Decl << Decl;
1151 Diag(Decl->getLocation(),
1152 diag::note_objc_circular_container_declared_here)
1153 << Decl;
1154 }
1155 }
1156 }
1157 }
1158}
1159
1160/// Check a message send to see if it's likely to cause a retain cycle.
1161void SemaObjC::checkRetainCycles(ObjCMessageExpr *msg) {
1162 // Only check instance methods whose selector looks like a setter.
1163 if (!msg->isInstanceMessage() || !isSetterLikeSelector(sel: msg->getSelector()))
1164 return;
1165
1166 // Try to find a variable that the receiver is strongly owned by.
1167 RetainCycleOwner owner;
1168 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
1169 if (!findRetainCycleOwner(S&: SemaRef, e: msg->getInstanceReceiver(), owner))
1170 return;
1171 } else {
1172 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
1173 owner.Variable = SemaRef.getCurMethodDecl()->getSelfDecl();
1174 owner.Loc = msg->getSuperLoc();
1175 owner.Range = msg->getSuperLoc();
1176 }
1177
1178 // Check whether the receiver is captured by any of the arguments.
1179 const ObjCMethodDecl *MD = msg->getMethodDecl();
1180 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
1181 if (Expr *capturer = findCapturingExpr(S&: SemaRef, e: msg->getArg(Arg: i), owner)) {
1182 // noescape blocks should not be retained by the method.
1183 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
1184 continue;
1185 return diagnoseRetainCycle(S&: SemaRef, capturer, owner);
1186 }
1187 }
1188}
1189
1190/// Check a property assign to see if it's likely to cause a retain cycle.
1191void SemaObjC::checkRetainCycles(Expr *receiver, Expr *argument) {
1192 RetainCycleOwner owner;
1193 if (!findRetainCycleOwner(S&: SemaRef, e: receiver, owner))
1194 return;
1195
1196 if (Expr *capturer = findCapturingExpr(S&: SemaRef, e: argument, owner))
1197 diagnoseRetainCycle(S&: SemaRef, capturer, owner);
1198}
1199
1200void SemaObjC::checkRetainCycles(VarDecl *Var, Expr *Init) {
1201 RetainCycleOwner Owner;
1202 if (!considerVariable(var: Var, /*DeclRefExpr=*/ref: nullptr, owner&: Owner))
1203 return;
1204
1205 // Because we don't have an expression for the variable, we have to set the
1206 // location explicitly here.
1207 Owner.Loc = Var->getLocation();
1208 Owner.Range = Var->getSourceRange();
1209
1210 if (Expr *Capturer = findCapturingExpr(S&: SemaRef, e: Init, owner&: Owner))
1211 diagnoseRetainCycle(S&: SemaRef, capturer: Capturer, owner&: Owner);
1212}
1213
1214/// CheckObjCString - Checks that the argument to the builtin
1215/// CFString constructor is correct
1216/// Note: It might also make sense to do the UTF-16 conversion here (would
1217/// simplify the backend).
1218bool SemaObjC::CheckObjCString(Expr *Arg) {
1219 Arg = Arg->IgnoreParenCasts();
1220 StringLiteral *Literal = dyn_cast<StringLiteral>(Val: Arg);
1221
1222 if (!Literal || !Literal->isOrdinary()) {
1223 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
1224 << Arg->getSourceRange();
1225 return true;
1226 }
1227
1228 if (Literal->containsNonAsciiOrNull()) {
1229 StringRef String = Literal->getString();
1230 unsigned NumBytes = String.size();
1231 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
1232 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
1233 llvm::UTF16 *ToPtr = &ToBuf[0];
1234
1235 llvm::ConversionResult Result =
1236 llvm::ConvertUTF8toUTF16(sourceStart: &FromPtr, sourceEnd: FromPtr + NumBytes, targetStart: &ToPtr,
1237 targetEnd: ToPtr + NumBytes, flags: llvm::strictConversion);
1238 // Check for conversion failure.
1239 if (Result != llvm::conversionOK)
1240 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
1241 << Arg->getSourceRange();
1242 }
1243 return false;
1244}
1245
1246bool SemaObjC::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1247 ArrayRef<const Expr *> Args) {
1248 VariadicCallType CallType = Method->isVariadic()
1249 ? VariadicCallType::Method
1250 : VariadicCallType::DoesNotApply;
1251
1252 SemaRef.checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
1253 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1254 CallType);
1255
1256 SemaRef.CheckTCBEnforcement(lbrac, Method);
1257
1258 return false;
1259}
1260
1261const DeclContext *SemaObjC::getCurObjCLexicalContext() const {
1262 const DeclContext *DC = SemaRef.getCurLexicalContext();
1263 // A category implicitly has the attribute of the interface.
1264 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(Val: DC))
1265 DC = CatD->getClassInterface();
1266 return DC;
1267}
1268
1269/// Retrieve the identifier "NSError".
1270IdentifierInfo *SemaObjC::getNSErrorIdent() {
1271 if (!Ident_NSError)
1272 Ident_NSError = SemaRef.PP.getIdentifierInfo(Name: "NSError");
1273
1274 return Ident_NSError;
1275}
1276
1277void SemaObjC::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
1278 assert(
1279 IDecl->getLexicalParent() == SemaRef.CurContext &&
1280 "The next DeclContext should be lexically contained in the current one.");
1281 SemaRef.CurContext = IDecl;
1282}
1283
1284void SemaObjC::ActOnObjCContainerFinishDefinition() {
1285 // Exit this scope of this interface definition.
1286 SemaRef.PopDeclContext();
1287}
1288
1289void SemaObjC::ActOnObjCTemporaryExitContainerContext(
1290 ObjCContainerDecl *ObjCCtx) {
1291 assert(ObjCCtx == SemaRef.CurContext && "Mismatch of container contexts");
1292 SemaRef.OriginalLexicalContext = ObjCCtx;
1293 ActOnObjCContainerFinishDefinition();
1294}
1295
1296void SemaObjC::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
1297 ActOnObjCContainerStartDefinition(IDecl: ObjCCtx);
1298 SemaRef.OriginalLexicalContext = nullptr;
1299}
1300
1301/// Find the protocol with the given name, if any.
1302ObjCProtocolDecl *SemaObjC::LookupProtocol(IdentifierInfo *II,
1303 SourceLocation IdLoc,
1304 RedeclarationKind Redecl) {
1305 Decl *D = SemaRef.LookupSingleName(S: SemaRef.TUScope, Name: II, Loc: IdLoc,
1306 NameKind: Sema::LookupObjCProtocolName, Redecl);
1307 return cast_or_null<ObjCProtocolDecl>(Val: D);
1308}
1309
1310/// Determine whether this is an Objective-C writeback conversion,
1311/// used for parameter passing when performing automatic reference counting.
1312///
1313/// \param FromType The type we're converting form.
1314///
1315/// \param ToType The type we're converting to.
1316///
1317/// \param ConvertedType The type that will be produced after applying
1318/// this conversion.
1319bool SemaObjC::isObjCWritebackConversion(QualType FromType, QualType ToType,
1320 QualType &ConvertedType) {
1321 ASTContext &Context = getASTContext();
1322 if (!getLangOpts().ObjCAutoRefCount ||
1323 Context.hasSameUnqualifiedType(T1: FromType, T2: ToType))
1324 return false;
1325
1326 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1327 QualType ToPointee;
1328 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1329 ToPointee = ToPointer->getPointeeType();
1330 else
1331 return false;
1332
1333 Qualifiers ToQuals = ToPointee.getQualifiers();
1334 if (!ToPointee->isObjCLifetimeType() ||
1335 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1336 !ToQuals.withoutObjCLifetime().empty())
1337 return false;
1338
1339 // Argument must be a pointer to __strong to __weak.
1340 QualType FromPointee;
1341 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1342 FromPointee = FromPointer->getPointeeType();
1343 else
1344 return false;
1345
1346 Qualifiers FromQuals = FromPointee.getQualifiers();
1347 if (!FromPointee->isObjCLifetimeType() ||
1348 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1349 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1350 return false;
1351
1352 // Make sure that we have compatible qualifiers.
1353 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1354 if (!ToQuals.compatiblyIncludes(other: FromQuals, Ctx: getASTContext()))
1355 return false;
1356
1357 // Remove qualifiers from the pointee type we're converting from; they
1358 // aren't used in the compatibility check belong, and we'll be adding back
1359 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1360 FromPointee = FromPointee.getUnqualifiedType();
1361
1362 // The unqualified form of the pointee types must be compatible.
1363 ToPointee = ToPointee.getUnqualifiedType();
1364 bool IncompatibleObjC;
1365 if (Context.typesAreCompatible(T1: FromPointee, T2: ToPointee))
1366 FromPointee = ToPointee;
1367 else if (!SemaRef.isObjCPointerConversion(FromType: FromPointee, ToType: ToPointee, ConvertedType&: FromPointee,
1368 IncompatibleObjC))
1369 return false;
1370
1371 /// Construct the type we're converting to, which is a pointer to
1372 /// __autoreleasing pointee.
1373 FromPointee = Context.getQualifiedType(T: FromPointee, Qs: FromQuals);
1374 ConvertedType = Context.getPointerType(T: FromPointee);
1375 return true;
1376}
1377
1378/// CheckSubscriptingKind - This routine decide what type
1379/// of indexing represented by "FromE" is being done.
1380SemaObjC::ObjCSubscriptKind SemaObjC::CheckSubscriptingKind(Expr *FromE) {
1381 // If the expression already has integral or enumeration type, we're golden.
1382 QualType T = FromE->getType();
1383 if (T->isIntegralOrEnumerationType())
1384 return SemaObjC::OS_Array;
1385
1386 // If we don't have a class type in C++, there's no way we can get an
1387 // expression of integral or enumeration type.
1388 const RecordType *RecordTy = T->getAs<RecordType>();
1389 if (!RecordTy && (T->isObjCObjectPointerType() || T->isVoidPointerType()))
1390 // All other scalar cases are assumed to be dictionary indexing which
1391 // caller handles, with diagnostics if needed.
1392 return SemaObjC::OS_Dictionary;
1393 if (!getLangOpts().CPlusPlus || !RecordTy || RecordTy->isIncompleteType()) {
1394 // No indexing can be done. Issue diagnostics and quit.
1395 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1396 if (isa<StringLiteral>(IndexExpr))
1397 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1398 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1399 else
1400 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion) << T;
1401 return SemaObjC::OS_Error;
1402 }
1403
1404 // We must have a complete class type.
1405 if (SemaRef.RequireCompleteType(FromE->getExprLoc(), T,
1406 diag::err_objc_index_incomplete_class_type,
1407 FromE))
1408 return SemaObjC::OS_Error;
1409
1410 // Look for a conversion to an integral, enumeration type, or
1411 // objective-C pointer type.
1412 int NoIntegrals = 0, NoObjCIdPointers = 0;
1413 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1414
1415 for (NamedDecl *D : cast<CXXRecordDecl>(Val: RecordTy->getDecl())
1416 ->getVisibleConversionFunctions()) {
1417 if (CXXConversionDecl *Conversion =
1418 dyn_cast<CXXConversionDecl>(Val: D->getUnderlyingDecl())) {
1419 QualType CT = Conversion->getConversionType().getNonReferenceType();
1420 if (CT->isIntegralOrEnumerationType()) {
1421 ++NoIntegrals;
1422 ConversionDecls.push_back(Elt: Conversion);
1423 } else if (CT->isObjCIdType() || CT->isBlockPointerType()) {
1424 ++NoObjCIdPointers;
1425 ConversionDecls.push_back(Elt: Conversion);
1426 }
1427 }
1428 }
1429 if (NoIntegrals == 1 && NoObjCIdPointers == 0)
1430 return SemaObjC::OS_Array;
1431 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1432 return SemaObjC::OS_Dictionary;
1433 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1434 // No conversion function was found. Issue diagnostic and return.
1435 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1436 << FromE->getType();
1437 return SemaObjC::OS_Error;
1438 }
1439 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1440 << FromE->getType();
1441 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1442 Diag(ConversionDecls[i]->getLocation(),
1443 diag::note_conv_function_declared_at);
1444
1445 return SemaObjC::OS_Error;
1446}
1447
1448void SemaObjC::AddCFAuditedAttribute(Decl *D) {
1449 ASTContext &Context = getASTContext();
1450 auto IdLoc = SemaRef.PP.getPragmaARCCFCodeAuditedInfo();
1451 if (!IdLoc.getLoc().isValid())
1452 return;
1453
1454 // Don't add a redundant or conflicting attribute.
1455 if (D->hasAttr<CFAuditedTransferAttr>() ||
1456 D->hasAttr<CFUnknownTransferAttr>())
1457 return;
1458
1459 AttributeCommonInfo Info(IdLoc.getIdentifierInfo(),
1460 SourceRange(IdLoc.getLoc()),
1461 AttributeCommonInfo::Form::Pragma());
1462 D->addAttr(CFAuditedTransferAttr::CreateImplicit(Context, Info));
1463}
1464
1465bool SemaObjC::isCFError(RecordDecl *RD) {
1466 // If we already know about CFError, test it directly.
1467 if (CFError)
1468 return CFError == RD;
1469
1470 // Check whether this is CFError, which we identify based on its bridge to
1471 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
1472 // declared with "objc_bridge_mutable", so look for either one of the two
1473 // attributes.
1474 if (RD->getTagKind() == TagTypeKind::Struct) {
1475 IdentifierInfo *bridgedType = nullptr;
1476 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
1477 bridgedType = bridgeAttr->getBridgedType();
1478 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
1479 bridgedType = bridgeAttr->getBridgedType();
1480
1481 if (bridgedType == getNSErrorIdent()) {
1482 CFError = RD;
1483 return true;
1484 }
1485 }
1486
1487 return false;
1488}
1489
1490bool SemaObjC::isNSStringType(QualType T, bool AllowNSAttributedString) {
1491 const auto *PT = T->getAs<ObjCObjectPointerType>();
1492 if (!PT)
1493 return false;
1494
1495 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
1496 if (!Cls)
1497 return false;
1498
1499 IdentifierInfo *ClsName = Cls->getIdentifier();
1500
1501 if (AllowNSAttributedString &&
1502 ClsName == &getASTContext().Idents.get("NSAttributedString"))
1503 return true;
1504 // FIXME: Should we walk the chain of classes?
1505 return ClsName == &getASTContext().Idents.get("NSString") ||
1506 ClsName == &getASTContext().Idents.get("NSMutableString");
1507}
1508
1509bool SemaObjC::isCFStringType(QualType T) {
1510 const auto *PT = T->getAs<PointerType>();
1511 if (!PT)
1512 return false;
1513
1514 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
1515 if (!RT)
1516 return false;
1517
1518 const RecordDecl *RD = RT->getDecl();
1519 if (RD->getTagKind() != TagTypeKind::Struct)
1520 return false;
1521
1522 return RD->getIdentifier() == &getASTContext().Idents.get("__CFString");
1523}
1524
1525static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1526 // The IBOutlet/IBOutletCollection attributes only apply to instance
1527 // variables or properties of Objective-C classes. The outlet must also
1528 // have an object reference type.
1529 if (const auto *VD = dyn_cast<ObjCIvarDecl>(Val: D)) {
1530 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1531 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1532 << AL << VD->getType() << 0;
1533 return false;
1534 }
1535 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(Val: D)) {
1536 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1537 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1538 << AL << PD->getType() << 1;
1539 return false;
1540 }
1541 } else {
1542 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1543 return false;
1544 }
1545
1546 return true;
1547}
1548
1549void SemaObjC::handleIBOutlet(Decl *D, const ParsedAttr &AL) {
1550 if (!checkIBOutletCommon(S&: SemaRef, D, AL))
1551 return;
1552
1553 D->addAttr(::new (getASTContext()) IBOutletAttr(getASTContext(), AL));
1554}
1555
1556void SemaObjC::handleIBOutletCollection(Decl *D, const ParsedAttr &AL) {
1557
1558 ASTContext &Context = getASTContext();
1559 // The iboutletcollection attribute can have zero or one arguments.
1560 if (AL.getNumArgs() > 1) {
1561 Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1562 return;
1563 }
1564
1565 if (!checkIBOutletCommon(S&: SemaRef, D, AL))
1566 return;
1567
1568 ParsedType PT;
1569
1570 if (AL.hasParsedType())
1571 PT = AL.getTypeArg();
1572 else {
1573 PT = SemaRef.getTypeName(
1574 II: Context.Idents.get(Name: "NSObject"), NameLoc: AL.getLoc(),
1575 S: SemaRef.getScopeForContext(Ctx: D->getDeclContext()->getParent()));
1576 if (!PT) {
1577 Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1578 return;
1579 }
1580 }
1581
1582 TypeSourceInfo *QTLoc = nullptr;
1583 QualType QT = SemaRef.GetTypeFromParser(Ty: PT, TInfo: &QTLoc);
1584 if (!QTLoc)
1585 QTLoc = Context.getTrivialTypeSourceInfo(T: QT, Loc: AL.getLoc());
1586
1587 // Diagnose use of non-object type in iboutletcollection attribute.
1588 // FIXME. Gnu attribute extension ignores use of builtin types in
1589 // attributes. So, __attribute__((iboutletcollection(char))) will be
1590 // treated as __attribute__((iboutletcollection())).
1591 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1592 Diag(AL.getLoc(), QT->isBuiltinType()
1593 ? diag::err_iboutletcollection_builtintype
1594 : diag::err_iboutletcollection_type)
1595 << QT;
1596 return;
1597 }
1598
1599 D->addAttr(::new (Context) IBOutletCollectionAttr(Context, AL, QTLoc));
1600}
1601
1602void SemaObjC::handleSuppresProtocolAttr(Decl *D, const ParsedAttr &AL) {
1603 if (!cast<ObjCProtocolDecl>(Val: D)->isThisDeclarationADefinition()) {
1604 Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1605 << AL << AL.getRange();
1606 return;
1607 }
1608
1609 D->addAttr(::new (getASTContext())
1610 ObjCExplicitProtocolImplAttr(getASTContext(), AL));
1611}
1612
1613void SemaObjC::handleDirectAttr(Decl *D, const ParsedAttr &AL) {
1614 // objc_direct cannot be set on methods declared in the context of a protocol
1615 if (isa<ObjCProtocolDecl>(Val: D->getDeclContext())) {
1616 Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
1617 return;
1618 }
1619
1620 if (getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
1621 handleSimpleAttribute<ObjCDirectAttr>(*this, D, AL);
1622 } else {
1623 Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
1624 }
1625}
1626
1627void SemaObjC::handleDirectMembersAttr(Decl *D, const ParsedAttr &AL) {
1628 if (getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
1629 handleSimpleAttribute<ObjCDirectMembersAttr>(*this, D, AL);
1630 } else {
1631 Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
1632 }
1633}
1634
1635void SemaObjC::handleMethodFamilyAttr(Decl *D, const ParsedAttr &AL) {
1636 const auto *M = cast<ObjCMethodDecl>(Val: D);
1637 if (!AL.isArgIdent(Arg: 0)) {
1638 Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1639 << AL << 1 << AANT_ArgumentIdentifier;
1640 return;
1641 }
1642
1643 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
1644 ObjCMethodFamilyAttr::FamilyKind F;
1645 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(
1646 IL->getIdentifierInfo()->getName(), F)) {
1647 Diag(IL->getLoc(), diag::warn_attribute_type_not_supported)
1648 << AL << IL->getIdentifierInfo();
1649 return;
1650 }
1651
1652 if (F == ObjCMethodFamilyAttr::OMF_init &&
1653 !M->getReturnType()->isObjCObjectPointerType()) {
1654 Diag(M->getLocation(), diag::err_init_method_bad_return_type)
1655 << M->getReturnType();
1656 // Ignore the attribute.
1657 return;
1658 }
1659
1660 D->addAttr(new (getASTContext())
1661 ObjCMethodFamilyAttr(getASTContext(), AL, F));
1662}
1663
1664void SemaObjC::handleNSObject(Decl *D, const ParsedAttr &AL) {
1665 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
1666 QualType T = TD->getUnderlyingType();
1667 if (!T->isCARCBridgableType()) {
1668 Diag(TD->getLocation(), diag::err_nsobject_attribute);
1669 return;
1670 }
1671 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(Val: D)) {
1672 QualType T = PD->getType();
1673 if (!T->isCARCBridgableType()) {
1674 Diag(PD->getLocation(), diag::err_nsobject_attribute);
1675 return;
1676 }
1677 } else {
1678 // It is okay to include this attribute on properties, e.g.:
1679 //
1680 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
1681 //
1682 // In this case it follows tradition and suppresses an error in the above
1683 // case.
1684 Diag(D->getLocation(), diag::warn_nsobject_attribute);
1685 }
1686 D->addAttr(::new (getASTContext()) ObjCNSObjectAttr(getASTContext(), AL));
1687}
1688
1689void SemaObjC::handleIndependentClass(Decl *D, const ParsedAttr &AL) {
1690 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
1691 QualType T = TD->getUnderlyingType();
1692 if (!T->isObjCObjectPointerType()) {
1693 Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
1694 return;
1695 }
1696 } else {
1697 Diag(D->getLocation(), diag::warn_independentclass_attribute);
1698 return;
1699 }
1700 D->addAttr(::new (getASTContext())
1701 ObjCIndependentClassAttr(getASTContext(), AL));
1702}
1703
1704void SemaObjC::handleBlocksAttr(Decl *D, const ParsedAttr &AL) {
1705 if (!AL.isArgIdent(Arg: 0)) {
1706 Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1707 << AL << 1 << AANT_ArgumentIdentifier;
1708 return;
1709 }
1710
1711 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
1712 BlocksAttr::BlockType type;
1713 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
1714 Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
1715 return;
1716 }
1717
1718 D->addAttr(::new (getASTContext()) BlocksAttr(getASTContext(), AL, type));
1719}
1720
1721static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
1722 return QT->isDependentType() || QT->isObjCRetainableType();
1723}
1724
1725static bool isValidSubjectOfNSAttribute(QualType QT) {
1726 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
1727 QT->isObjCNSObjectType();
1728}
1729
1730static bool isValidSubjectOfCFAttribute(QualType QT) {
1731 return QT->isDependentType() || QT->isPointerType() ||
1732 isValidSubjectOfNSAttribute(QT);
1733}
1734
1735static bool isValidSubjectOfOSAttribute(QualType QT) {
1736 if (QT->isDependentType())
1737 return true;
1738 QualType PT = QT->getPointeeType();
1739 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
1740}
1741
1742void SemaObjC::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
1743 Sema::RetainOwnershipKind K,
1744 bool IsTemplateInstantiation) {
1745 ValueDecl *VD = cast<ValueDecl>(Val: D);
1746 switch (K) {
1747 case Sema::RetainOwnershipKind::OS:
1748 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
1749 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
1750 diag::warn_ns_attribute_wrong_parameter_type,
1751 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
1752 return;
1753 case Sema::RetainOwnershipKind::NS:
1754 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
1755 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
1756
1757 // These attributes are normally just advisory, but in ARC, ns_consumed
1758 // is significant. Allow non-dependent code to contain inappropriate
1759 // attributes even in ARC, but require template instantiations to be
1760 // set up correctly.
1761 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
1762 ? diag::err_ns_attribute_wrong_parameter_type
1763 : diag::warn_ns_attribute_wrong_parameter_type),
1764 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
1765 return;
1766 case Sema::RetainOwnershipKind::CF:
1767 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
1768 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
1769 diag::warn_ns_attribute_wrong_parameter_type,
1770 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
1771 return;
1772 }
1773}
1774
1775Sema::RetainOwnershipKind
1776SemaObjC::parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
1777 switch (AL.getKind()) {
1778 case ParsedAttr::AT_CFConsumed:
1779 case ParsedAttr::AT_CFReturnsRetained:
1780 case ParsedAttr::AT_CFReturnsNotRetained:
1781 return Sema::RetainOwnershipKind::CF;
1782 case ParsedAttr::AT_OSConsumesThis:
1783 case ParsedAttr::AT_OSConsumed:
1784 case ParsedAttr::AT_OSReturnsRetained:
1785 case ParsedAttr::AT_OSReturnsNotRetained:
1786 case ParsedAttr::AT_OSReturnsRetainedOnZero:
1787 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
1788 return Sema::RetainOwnershipKind::OS;
1789 case ParsedAttr::AT_NSConsumesSelf:
1790 case ParsedAttr::AT_NSConsumed:
1791 case ParsedAttr::AT_NSReturnsRetained:
1792 case ParsedAttr::AT_NSReturnsNotRetained:
1793 case ParsedAttr::AT_NSReturnsAutoreleased:
1794 return Sema::RetainOwnershipKind::NS;
1795 default:
1796 llvm_unreachable("Wrong argument supplied");
1797 }
1798}
1799
1800bool SemaObjC::checkNSReturnsRetainedReturnType(SourceLocation Loc,
1801 QualType QT) {
1802 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
1803 return false;
1804
1805 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
1806 << "'ns_returns_retained'" << 0 << 0;
1807 return true;
1808}
1809
1810/// \return whether the parameter is a pointer to OSObject pointer.
1811bool SemaObjC::isValidOSObjectOutParameter(const Decl *D) {
1812 const auto *PVD = dyn_cast<ParmVarDecl>(Val: D);
1813 if (!PVD)
1814 return false;
1815 QualType QT = PVD->getType();
1816 QualType PT = QT->getPointeeType();
1817 return !PT.isNull() && isValidSubjectOfOSAttribute(QT: PT);
1818}
1819
1820void SemaObjC::handleXReturnsXRetainedAttr(Decl *D, const ParsedAttr &AL) {
1821 QualType ReturnType;
1822 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
1823
1824 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
1825 ReturnType = MD->getReturnType();
1826 } else if (getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
1827 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
1828 return; // ignore: was handled as a type attribute
1829 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(Val: D)) {
1830 ReturnType = PD->getType();
1831 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1832 ReturnType = FD->getReturnType();
1833 } else if (const auto *Param = dyn_cast<ParmVarDecl>(Val: D)) {
1834 // Attributes on parameters are used for out-parameters,
1835 // passed as pointers-to-pointers.
1836 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
1837 ? /*pointer-to-CF-pointer*/ 2
1838 : /*pointer-to-OSObject-pointer*/ 3;
1839 ReturnType = Param->getType()->getPointeeType();
1840 if (ReturnType.isNull()) {
1841 Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
1842 << AL << DiagID << AL.getRange();
1843 return;
1844 }
1845 } else if (AL.isUsedAsTypeAttr()) {
1846 return;
1847 } else {
1848 AttributeDeclKind ExpectedDeclKind;
1849 switch (AL.getKind()) {
1850 default:
1851 llvm_unreachable("invalid ownership attribute");
1852 case ParsedAttr::AT_NSReturnsRetained:
1853 case ParsedAttr::AT_NSReturnsAutoreleased:
1854 case ParsedAttr::AT_NSReturnsNotRetained:
1855 ExpectedDeclKind = ExpectedFunctionOrMethod;
1856 break;
1857
1858 case ParsedAttr::AT_OSReturnsRetained:
1859 case ParsedAttr::AT_OSReturnsNotRetained:
1860 case ParsedAttr::AT_CFReturnsRetained:
1861 case ParsedAttr::AT_CFReturnsNotRetained:
1862 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
1863 break;
1864 }
1865 Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
1866 << AL.getRange() << AL << AL.isRegularKeywordAttribute()
1867 << ExpectedDeclKind;
1868 return;
1869 }
1870
1871 bool TypeOK;
1872 bool Cf;
1873 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
1874 switch (AL.getKind()) {
1875 default:
1876 llvm_unreachable("invalid ownership attribute");
1877 case ParsedAttr::AT_NSReturnsRetained:
1878 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(QT: ReturnType);
1879 Cf = false;
1880 break;
1881
1882 case ParsedAttr::AT_NSReturnsAutoreleased:
1883 case ParsedAttr::AT_NSReturnsNotRetained:
1884 TypeOK = isValidSubjectOfNSAttribute(QT: ReturnType);
1885 Cf = false;
1886 break;
1887
1888 case ParsedAttr::AT_CFReturnsRetained:
1889 case ParsedAttr::AT_CFReturnsNotRetained:
1890 TypeOK = isValidSubjectOfCFAttribute(QT: ReturnType);
1891 Cf = true;
1892 break;
1893
1894 case ParsedAttr::AT_OSReturnsRetained:
1895 case ParsedAttr::AT_OSReturnsNotRetained:
1896 TypeOK = isValidSubjectOfOSAttribute(QT: ReturnType);
1897 Cf = true;
1898 ParmDiagID = 3; // Pointer-to-OSObject-pointer
1899 break;
1900 }
1901
1902 if (!TypeOK) {
1903 if (AL.isUsedAsTypeAttr())
1904 return;
1905
1906 if (isa<ParmVarDecl>(Val: D)) {
1907 Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
1908 << AL << ParmDiagID << AL.getRange();
1909 } else {
1910 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
1911 enum : unsigned { Function, Method, Property } SubjectKind = Function;
1912 if (isa<ObjCMethodDecl>(Val: D))
1913 SubjectKind = Method;
1914 else if (isa<ObjCPropertyDecl>(Val: D))
1915 SubjectKind = Property;
1916 Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
1917 << AL << SubjectKind << Cf << AL.getRange();
1918 }
1919 return;
1920 }
1921
1922 switch (AL.getKind()) {
1923 default:
1924 llvm_unreachable("invalid ownership attribute");
1925 case ParsedAttr::AT_NSReturnsAutoreleased:
1926 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(*this, D, AL);
1927 return;
1928 case ParsedAttr::AT_CFReturnsNotRetained:
1929 handleSimpleAttribute<CFReturnsNotRetainedAttr>(*this, D, AL);
1930 return;
1931 case ParsedAttr::AT_NSReturnsNotRetained:
1932 handleSimpleAttribute<NSReturnsNotRetainedAttr>(*this, D, AL);
1933 return;
1934 case ParsedAttr::AT_CFReturnsRetained:
1935 handleSimpleAttribute<CFReturnsRetainedAttr>(*this, D, AL);
1936 return;
1937 case ParsedAttr::AT_NSReturnsRetained:
1938 handleSimpleAttribute<NSReturnsRetainedAttr>(*this, D, AL);
1939 return;
1940 case ParsedAttr::AT_OSReturnsRetained:
1941 handleSimpleAttribute<OSReturnsRetainedAttr>(*this, D, AL);
1942 return;
1943 case ParsedAttr::AT_OSReturnsNotRetained:
1944 handleSimpleAttribute<OSReturnsNotRetainedAttr>(*this, D, AL);
1945 return;
1946 };
1947}
1948
1949void SemaObjC::handleReturnsInnerPointerAttr(Decl *D, const ParsedAttr &Attrs) {
1950 const int EP_ObjCMethod = 1;
1951 const int EP_ObjCProperty = 2;
1952
1953 SourceLocation loc = Attrs.getLoc();
1954 QualType resultType;
1955 if (isa<ObjCMethodDecl>(Val: D))
1956 resultType = cast<ObjCMethodDecl>(Val: D)->getReturnType();
1957 else
1958 resultType = cast<ObjCPropertyDecl>(Val: D)->getType();
1959
1960 if (!resultType->isReferenceType() &&
1961 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
1962 Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
1963 << SourceRange(loc) << Attrs
1964 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
1965 << /*non-retainable pointer*/ 2;
1966
1967 // Drop the attribute.
1968 return;
1969 }
1970
1971 D->addAttr(::new (getASTContext())
1972 ObjCReturnsInnerPointerAttr(getASTContext(), Attrs));
1973}
1974
1975void SemaObjC::handleRequiresSuperAttr(Decl *D, const ParsedAttr &Attrs) {
1976 const auto *Method = cast<ObjCMethodDecl>(Val: D);
1977
1978 const DeclContext *DC = Method->getDeclContext();
1979 if (const auto *PDecl = dyn_cast_if_present<ObjCProtocolDecl>(DC)) {
1980 Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol)
1981 << Attrs << 0;
1982 Diag(PDecl->getLocation(), diag::note_protocol_decl);
1983 return;
1984 }
1985 if (Method->getMethodFamily() == OMF_dealloc) {
1986 Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol)
1987 << Attrs << 1;
1988 return;
1989 }
1990
1991 D->addAttr(::new (getASTContext())
1992 ObjCRequiresSuperAttr(getASTContext(), Attrs));
1993}
1994
1995void SemaObjC::handleNSErrorDomain(Decl *D, const ParsedAttr &Attr) {
1996 if (!isa<TagDecl>(Val: D)) {
1997 Diag(D->getBeginLoc(), diag::err_nserrordomain_invalid_decl) << 0;
1998 return;
1999 }
2000
2001 IdentifierLoc *IdentLoc =
2002 Attr.isArgIdent(Arg: 0) ? Attr.getArgAsIdent(Arg: 0) : nullptr;
2003 if (!IdentLoc || !IdentLoc->getIdentifierInfo()) {
2004 // Try to locate the argument directly.
2005 SourceLocation Loc = Attr.getLoc();
2006 if (Attr.isArgExpr(Arg: 0) && Attr.getArgAsExpr(Arg: 0))
2007 Loc = Attr.getArgAsExpr(Arg: 0)->getBeginLoc();
2008
2009 Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
2010 return;
2011 }
2012
2013 // Verify that the identifier is a valid decl in the C decl namespace.
2014 LookupResult Result(SemaRef, DeclarationName(IdentLoc->getIdentifierInfo()),
2015 SourceLocation(),
2016 Sema::LookupNameKind::LookupOrdinaryName);
2017 if (!SemaRef.LookupName(R&: Result, S: SemaRef.TUScope) ||
2018 !Result.getAsSingle<VarDecl>()) {
2019 Diag(IdentLoc->getLoc(), diag::err_nserrordomain_invalid_decl)
2020 << 1 << IdentLoc->getIdentifierInfo();
2021 return;
2022 }
2023
2024 D->addAttr(::new (getASTContext()) NSErrorDomainAttr(
2025 getASTContext(), Attr, IdentLoc->getIdentifierInfo()));
2026}
2027
2028void SemaObjC::handleBridgeAttr(Decl *D, const ParsedAttr &AL) {
2029 IdentifierLoc *Parm = AL.isArgIdent(Arg: 0) ? AL.getArgAsIdent(Arg: 0) : nullptr;
2030
2031 if (!Parm) {
2032 Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
2033 return;
2034 }
2035
2036 // Typedefs only allow objc_bridge(id) and have some additional checking.
2037 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
2038 if (!Parm->getIdentifierInfo()->isStr(Str: "id")) {
2039 Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
2040 return;
2041 }
2042
2043 // Only allow 'cv void *'.
2044 QualType T = TD->getUnderlyingType();
2045 if (!T->isVoidPointerType()) {
2046 Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
2047 return;
2048 }
2049 }
2050
2051 D->addAttr(::new (getASTContext()) ObjCBridgeAttr(getASTContext(), AL,
2052 Parm->getIdentifierInfo()));
2053}
2054
2055void SemaObjC::handleBridgeMutableAttr(Decl *D, const ParsedAttr &AL) {
2056 IdentifierLoc *Parm = AL.isArgIdent(Arg: 0) ? AL.getArgAsIdent(Arg: 0) : nullptr;
2057
2058 if (!Parm) {
2059 Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
2060 return;
2061 }
2062
2063 D->addAttr(::new (getASTContext()) ObjCBridgeMutableAttr(
2064 getASTContext(), AL, Parm->getIdentifierInfo()));
2065}
2066
2067void SemaObjC::handleBridgeRelatedAttr(Decl *D, const ParsedAttr &AL) {
2068 IdentifierInfo *RelatedClass =
2069 AL.isArgIdent(Arg: 0) ? AL.getArgAsIdent(Arg: 0)->getIdentifierInfo() : nullptr;
2070 if (!RelatedClass) {
2071 Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
2072 return;
2073 }
2074 IdentifierInfo *ClassMethod =
2075 AL.getArgAsIdent(Arg: 1) ? AL.getArgAsIdent(Arg: 1)->getIdentifierInfo() : nullptr;
2076 IdentifierInfo *InstanceMethod =
2077 AL.getArgAsIdent(Arg: 2) ? AL.getArgAsIdent(Arg: 2)->getIdentifierInfo() : nullptr;
2078 D->addAttr(::new (getASTContext()) ObjCBridgeRelatedAttr(
2079 getASTContext(), AL, RelatedClass, ClassMethod, InstanceMethod));
2080}
2081
2082void SemaObjC::handleDesignatedInitializer(Decl *D, const ParsedAttr &AL) {
2083 DeclContext *Ctx = D->getDeclContext();
2084
2085 // This attribute can only be applied to methods in interfaces or class
2086 // extensions.
2087 if (!isa<ObjCInterfaceDecl>(Val: Ctx) &&
2088 !(isa<ObjCCategoryDecl>(Val: Ctx) &&
2089 cast<ObjCCategoryDecl>(Val: Ctx)->IsClassExtension())) {
2090 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
2091 return;
2092 }
2093
2094 ObjCInterfaceDecl *IFace;
2095 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Val: Ctx))
2096 IFace = CatDecl->getClassInterface();
2097 else
2098 IFace = cast<ObjCInterfaceDecl>(Val: Ctx);
2099
2100 if (!IFace)
2101 return;
2102
2103 IFace->setHasDesignatedInitializers();
2104 D->addAttr(::new (getASTContext())
2105 ObjCDesignatedInitializerAttr(getASTContext(), AL));
2106}
2107
2108void SemaObjC::handleRuntimeName(Decl *D, const ParsedAttr &AL) {
2109 StringRef MetaDataName;
2110 if (!SemaRef.checkStringLiteralArgumentAttr(Attr: AL, ArgNum: 0, Str&: MetaDataName))
2111 return;
2112 D->addAttr(::new (getASTContext())
2113 ObjCRuntimeNameAttr(getASTContext(), AL, MetaDataName));
2114}
2115
2116// When a user wants to use objc_boxable with a union or struct
2117// but they don't have access to the declaration (legacy/third-party code)
2118// then they can 'enable' this feature with a typedef:
2119// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
2120void SemaObjC::handleBoxable(Decl *D, const ParsedAttr &AL) {
2121 bool notify = false;
2122
2123 auto *RD = dyn_cast<RecordDecl>(Val: D);
2124 if (RD && RD->getDefinition()) {
2125 RD = RD->getDefinition();
2126 notify = true;
2127 }
2128
2129 if (RD) {
2130 ObjCBoxableAttr *BoxableAttr =
2131 ::new (getASTContext()) ObjCBoxableAttr(getASTContext(), AL);
2132 RD->addAttr(A: BoxableAttr);
2133 if (notify) {
2134 // we need to notify ASTReader/ASTWriter about
2135 // modification of existing declaration
2136 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
2137 L->AddedAttributeToRecord(Attr: BoxableAttr, Record: RD);
2138 }
2139 }
2140}
2141
2142void SemaObjC::handleOwnershipAttr(Decl *D, const ParsedAttr &AL) {
2143 if (hasDeclarator(D))
2144 return;
2145
2146 Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
2147 << AL.getRange() << AL << AL.isRegularKeywordAttribute()
2148 << ExpectedVariable;
2149}
2150
2151void SemaObjC::handlePreciseLifetimeAttr(Decl *D, const ParsedAttr &AL) {
2152 const auto *VD = cast<ValueDecl>(Val: D);
2153 QualType QT = VD->getType();
2154
2155 if (!QT->isDependentType() && !QT->isObjCLifetimeType()) {
2156 Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) << QT;
2157 return;
2158 }
2159
2160 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
2161
2162 // If we have no lifetime yet, check the lifetime we're presumably
2163 // going to infer.
2164 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
2165 Lifetime = QT->getObjCARCImplicitLifetime();
2166
2167 switch (Lifetime) {
2168 case Qualifiers::OCL_None:
2169 assert(QT->isDependentType() &&
2170 "didn't infer lifetime for non-dependent type?");
2171 break;
2172
2173 case Qualifiers::OCL_Weak: // meaningful
2174 case Qualifiers::OCL_Strong: // meaningful
2175 break;
2176
2177 case Qualifiers::OCL_ExplicitNone:
2178 case Qualifiers::OCL_Autoreleasing:
2179 Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
2180 << (Lifetime == Qualifiers::OCL_Autoreleasing);
2181 break;
2182 }
2183
2184 D->addAttr(::new (getASTContext())
2185 ObjCPreciseLifetimeAttr(getASTContext(), AL));
2186}
2187
2188static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
2189 bool DiagnoseFailure) {
2190 QualType Ty = VD->getType();
2191 if (!Ty->isObjCRetainableType()) {
2192 if (DiagnoseFailure) {
2193 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
2194 << 0;
2195 }
2196 return false;
2197 }
2198
2199 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
2200
2201 // SemaObjC::inferObjCARCLifetime must run after processing decl attributes
2202 // (because __block lowers to an attribute), so if the lifetime hasn't been
2203 // explicitly specified, infer it locally now.
2204 if (LifetimeQual == Qualifiers::OCL_None)
2205 LifetimeQual = Ty->getObjCARCImplicitLifetime();
2206
2207 // The attributes only really makes sense for __strong variables; ignore any
2208 // attempts to annotate a parameter with any other lifetime qualifier.
2209 if (LifetimeQual != Qualifiers::OCL_Strong) {
2210 if (DiagnoseFailure) {
2211 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
2212 << 1;
2213 }
2214 return false;
2215 }
2216
2217 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
2218 // to ensure that the variable is 'const' so that we can error on
2219 // modification, which can otherwise over-release.
2220 VD->setType(Ty.withConst());
2221 VD->setARCPseudoStrong(true);
2222 return true;
2223}
2224
2225void SemaObjC::handleExternallyRetainedAttr(Decl *D, const ParsedAttr &AL) {
2226 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
2227 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
2228 if (!VD->hasLocalStorage()) {
2229 Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained) << 0;
2230 return;
2231 }
2232
2233 if (!tryMakeVariablePseudoStrong(S&: SemaRef, VD, /*DiagnoseFailure=*/true))
2234 return;
2235
2236 handleSimpleAttribute<ObjCExternallyRetainedAttr>(*this, D, AL);
2237 return;
2238 }
2239
2240 // If D is a function-like declaration (method, block, or function), then we
2241 // make every parameter psuedo-strong.
2242 unsigned NumParams =
2243 hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
2244 for (unsigned I = 0; I != NumParams; ++I) {
2245 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, Idx: I));
2246 QualType Ty = PVD->getType();
2247
2248 // If a user wrote a parameter with __strong explicitly, then assume they
2249 // want "real" strong semantics for that parameter. This works because if
2250 // the parameter was written with __strong, then the strong qualifier will
2251 // be non-local.
2252 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
2253 Qualifiers::OCL_Strong)
2254 continue;
2255
2256 tryMakeVariablePseudoStrong(SemaRef, PVD, /*DiagnoseFailure=*/false);
2257 }
2258 handleSimpleAttribute<ObjCExternallyRetainedAttr>(*this, D, AL);
2259}
2260
2261bool SemaObjC::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2262 Sema::FormatStringInfo FSI;
2263 if ((SemaRef.GetFormatStringType(FormatFlavor: Format) == FormatStringType::NSString) &&
2264 SemaRef.getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
2265 false, true, &FSI)) {
2266 Idx = FSI.FormatIdx;
2267 return true;
2268 }
2269 return false;
2270}
2271
2272/// Diagnose use of %s directive in an NSString which is being passed
2273/// as formatting string to formatting method.
2274void SemaObjC::DiagnoseCStringFormatDirectiveInCFAPI(const NamedDecl *FDecl,
2275 Expr **Args,
2276 unsigned NumArgs) {
2277 unsigned Idx = 0;
2278 bool Format = false;
2279 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2280 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2281 Idx = 2;
2282 Format = true;
2283 } else
2284 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2285 if (GetFormatNSStringIdx(I, Idx)) {
2286 Format = true;
2287 break;
2288 }
2289 }
2290 if (!Format || NumArgs <= Idx)
2291 return;
2292 const Expr *FormatExpr = Args[Idx];
2293 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(Val: FormatExpr))
2294 FormatExpr = CSCE->getSubExpr();
2295 const StringLiteral *FormatString;
2296 if (const ObjCStringLiteral *OSL =
2297 dyn_cast<ObjCStringLiteral>(Val: FormatExpr->IgnoreParenImpCasts()))
2298 FormatString = OSL->getString();
2299 else
2300 FormatString = dyn_cast<StringLiteral>(Val: FormatExpr->IgnoreParenImpCasts());
2301 if (!FormatString)
2302 return;
2303 if (SemaRef.FormatStringHasSArg(FExpr: FormatString)) {
2304 Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2305 << "%s" << 1 << 1;
2306 Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2307 << FDecl->getDeclName();
2308 }
2309}
2310
2311bool SemaObjC::isSignedCharBool(QualType Ty) {
2312 return Ty->isSpecificBuiltinType(K: BuiltinType::SChar) && getLangOpts().ObjC &&
2313 NSAPIObj->isObjCBOOLType(T: Ty);
2314}
2315
2316void SemaObjC::adornBoolConversionDiagWithTernaryFixit(
2317 const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
2318 const Expr *Ignored = SourceExpr->IgnoreImplicit();
2319 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: Ignored))
2320 Ignored = OVE->getSourceExpr();
2321 bool NeedsParens = isa<AbstractConditionalOperator>(Val: Ignored) ||
2322 isa<BinaryOperator>(Val: Ignored) ||
2323 isa<CXXOperatorCallExpr>(Val: Ignored);
2324 SourceLocation EndLoc = SemaRef.getLocForEndOfToken(Loc: SourceExpr->getEndLoc());
2325 if (NeedsParens)
2326 Builder << FixItHint::CreateInsertion(InsertionLoc: SourceExpr->getBeginLoc(), Code: "(")
2327 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
2328 Builder << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: " ? YES : NO");
2329}
2330
2331/// Check a single element within a collection literal against the
2332/// target element type.
2333static void checkCollectionLiteralElement(Sema &S, QualType TargetElementType,
2334 Expr *Element, unsigned ElementKind) {
2335 // Skip a bitcast to 'id' or qualified 'id'.
2336 if (auto ICE = dyn_cast<ImplicitCastExpr>(Val: Element)) {
2337 if (ICE->getCastKind() == CK_BitCast &&
2338 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
2339 Element = ICE->getSubExpr();
2340 }
2341
2342 QualType ElementType = Element->getType();
2343 ExprResult ElementResult(Element);
2344 if (ElementType->getAs<ObjCObjectPointerType>() &&
2345 !S.IsAssignConvertCompatible(ConvTy: S.CheckSingleAssignmentConstraints(
2346 LHSType: TargetElementType, RHS&: ElementResult, Diagnose: false, DiagnoseCFAudited: false))) {
2347 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
2348 << ElementType << ElementKind << TargetElementType
2349 << Element->getSourceRange();
2350 }
2351
2352 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: Element))
2353 S.ObjC().checkArrayLiteral(TargetType: TargetElementType, ArrayLiteral);
2354 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: Element))
2355 S.ObjC().checkDictionaryLiteral(TargetType: TargetElementType, DictionaryLiteral);
2356}
2357
2358/// Check an Objective-C array literal being converted to the given
2359/// target type.
2360void SemaObjC::checkArrayLiteral(QualType TargetType,
2361 ObjCArrayLiteral *ArrayLiteral) {
2362 if (!NSArrayDecl)
2363 return;
2364
2365 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
2366 if (!TargetObjCPtr)
2367 return;
2368
2369 if (TargetObjCPtr->isUnspecialized() ||
2370 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() !=
2371 NSArrayDecl->getCanonicalDecl())
2372 return;
2373
2374 auto TypeArgs = TargetObjCPtr->getTypeArgs();
2375 if (TypeArgs.size() != 1)
2376 return;
2377
2378 QualType TargetElementType = TypeArgs[0];
2379 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
2380 checkCollectionLiteralElement(S&: SemaRef, TargetElementType,
2381 Element: ArrayLiteral->getElement(Index: I), ElementKind: 0);
2382 }
2383}
2384
2385void SemaObjC::checkDictionaryLiteral(
2386 QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral) {
2387 if (!NSDictionaryDecl)
2388 return;
2389
2390 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
2391 if (!TargetObjCPtr)
2392 return;
2393
2394 if (TargetObjCPtr->isUnspecialized() ||
2395 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() !=
2396 NSDictionaryDecl->getCanonicalDecl())
2397 return;
2398
2399 auto TypeArgs = TargetObjCPtr->getTypeArgs();
2400 if (TypeArgs.size() != 2)
2401 return;
2402
2403 QualType TargetKeyType = TypeArgs[0];
2404 QualType TargetObjectType = TypeArgs[1];
2405 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
2406 auto Element = DictionaryLiteral->getKeyValueElement(Index: I);
2407 checkCollectionLiteralElement(S&: SemaRef, TargetElementType: TargetKeyType, Element: Element.Key, ElementKind: 1);
2408 checkCollectionLiteralElement(S&: SemaRef, TargetElementType: TargetObjectType, Element: Element.Value, ElementKind: 2);
2409 }
2410}
2411
2412} // namespace clang
2413

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/Sema/SemaObjC.cpp