1//===--- SemaAPINotes.cpp - API Notes Handling ----------------------------===//
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//
9// This file implements the mapping from API notes to declaration attributes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/APINotes/APINotesReader.h"
15#include "clang/APINotes/Types.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Lex/Lexer.h"
23#include "clang/Sema/SemaObjC.h"
24#include "clang/Sema/SemaSwift.h"
25#include <stack>
26
27using namespace clang;
28
29namespace {
30enum class IsActive_t : bool { Inactive, Active };
31enum class IsSubstitution_t : bool { Original, Replacement };
32
33struct VersionedInfoMetadata {
34 /// An empty version refers to unversioned metadata.
35 VersionTuple Version;
36 unsigned IsActive : 1;
37 unsigned IsReplacement : 1;
38
39 VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
40 IsSubstitution_t Replacement)
41 : Version(Version), IsActive(Active == IsActive_t::Active),
42 IsReplacement(Replacement == IsSubstitution_t::Replacement) {}
43};
44} // end anonymous namespace
45
46/// Determine whether this is a multi-level pointer type.
47static bool isIndirectPointerType(QualType Type) {
48 QualType Pointee = Type->getPointeeType();
49 if (Pointee.isNull())
50 return false;
51
52 return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
53 Pointee->isMemberPointerType();
54}
55
56static void applyAPINotesType(Sema &S, Decl *decl, StringRef typeString,
57 VersionedInfoMetadata metadata) {
58 if (typeString.empty())
59
60 return;
61
62 // Version-independent APINotes add "type" annotations
63 // with a versioned attribute for the client to select and apply.
64 if (S.captureSwiftVersionIndependentAPINotes()) {
65 auto *typeAttr = SwiftTypeAttr::CreateImplicit(Ctx&: S.Context, TypeString: typeString);
66 auto *versioned = SwiftVersionedAdditionAttr::CreateImplicit(
67 Ctx&: S.Context, Version: metadata.Version, AdditionalAttr: typeAttr, IsReplacedByActive: metadata.IsReplacement);
68 decl->addAttr(A: versioned);
69 } else {
70 if (!metadata.IsActive)
71 return;
72 S.ApplyAPINotesType(D: decl, TypeString: typeString);
73 }
74}
75
76/// Apply nullability to the given declaration.
77static void applyNullability(Sema &S, Decl *decl, NullabilityKind nullability,
78 VersionedInfoMetadata metadata) {
79 // Version-independent APINotes add "nullability" annotations
80 // with a versioned attribute for the client to select and apply.
81 if (S.captureSwiftVersionIndependentAPINotes()) {
82 SwiftNullabilityAttr::Kind attrNullabilityKind;
83 switch (nullability) {
84 case NullabilityKind::NonNull:
85 attrNullabilityKind = SwiftNullabilityAttr::Kind::NonNull;
86 break;
87 case NullabilityKind::Nullable:
88 attrNullabilityKind = SwiftNullabilityAttr::Kind::Nullable;
89 break;
90 case NullabilityKind::Unspecified:
91 attrNullabilityKind = SwiftNullabilityAttr::Kind::Unspecified;
92 break;
93 case NullabilityKind::NullableResult:
94 attrNullabilityKind = SwiftNullabilityAttr::Kind::NullableResult;
95 break;
96 }
97 auto *nullabilityAttr =
98 SwiftNullabilityAttr::CreateImplicit(Ctx&: S.Context, Kind: attrNullabilityKind);
99 auto *versioned = SwiftVersionedAdditionAttr::CreateImplicit(
100 Ctx&: S.Context, Version: metadata.Version, AdditionalAttr: nullabilityAttr, IsReplacedByActive: metadata.IsReplacement);
101 decl->addAttr(A: versioned);
102 return;
103 } else {
104 if (!metadata.IsActive)
105 return;
106
107 S.ApplyNullability(D: decl, Nullability: nullability);
108 }
109}
110
111/// Copy a string into ASTContext-allocated memory.
112static StringRef ASTAllocateString(ASTContext &Ctx, StringRef String) {
113 void *mem = Ctx.Allocate(Size: String.size(), Align: alignof(char *));
114 memcpy(dest: mem, src: String.data(), n: String.size());
115 return StringRef(static_cast<char *>(mem), String.size());
116}
117
118static AttributeCommonInfo getPlaceholderAttrInfo() {
119 return AttributeCommonInfo(SourceRange(),
120 AttributeCommonInfo::UnknownAttribute,
121 {AttributeCommonInfo::AS_GNU,
122 /*Spelling*/ 0, /*IsAlignas*/ false,
123 /*IsRegularKeywordAttribute*/ false});
124}
125
126namespace {
127template <typename A> struct AttrKindFor {};
128
129#define ATTR(X) \
130 template <> struct AttrKindFor<X##Attr> { \
131 static const attr::Kind value = attr::X; \
132 };
133#include "clang/Basic/AttrList.inc"
134
135/// Handle an attribute introduced by API notes.
136///
137/// \param IsAddition Whether we should add a new attribute
138/// (otherwise, we might remove an existing attribute).
139/// \param CreateAttr Create the new attribute to be added.
140template <typename A>
141void handleAPINotedAttribute(
142 Sema &S, Decl *D, bool IsAddition, VersionedInfoMetadata Metadata,
143 llvm::function_ref<A *()> CreateAttr,
144 llvm::function_ref<Decl::attr_iterator(const Decl *)> GetExistingAttr) {
145 if (Metadata.IsActive) {
146 auto Existing = GetExistingAttr(D);
147 if (Existing != D->attr_end()) {
148 // Remove the existing attribute, and treat it as a superseded
149 // non-versioned attribute.
150 auto *Versioned = SwiftVersionedAdditionAttr::CreateImplicit(
151 Ctx&: S.Context, Version: Metadata.Version, AdditionalAttr: *Existing, /*IsReplacedByActive*/ true);
152
153 D->getAttrs().erase(CI: Existing);
154 D->addAttr(A: Versioned);
155 }
156
157 // If we're supposed to add a new attribute, do so.
158 if (IsAddition) {
159 if (auto Attr = CreateAttr())
160 D->addAttr(A: Attr);
161 }
162
163 return;
164 }
165 if (IsAddition) {
166 if (auto Attr = CreateAttr()) {
167 auto *Versioned = SwiftVersionedAdditionAttr::CreateImplicit(
168 S.Context, Metadata.Version, Attr,
169 /*IsReplacedByActive*/ Metadata.IsReplacement);
170 D->addAttr(A: Versioned);
171 }
172 } else {
173 // FIXME: This isn't preserving enough information for things like
174 // availability, where we're trying to remove a /specific/ kind of
175 // attribute.
176 auto *Versioned = SwiftVersionedRemovalAttr::CreateImplicit(
177 S.Context, Metadata.Version, AttrKindFor<A>::value,
178 /*IsReplacedByActive*/ Metadata.IsReplacement);
179 D->addAttr(A: Versioned);
180 }
181}
182
183template <typename A>
184void handleAPINotedAttribute(Sema &S, Decl *D, bool ShouldAddAttribute,
185 VersionedInfoMetadata Metadata,
186 llvm::function_ref<A *()> CreateAttr) {
187 handleAPINotedAttribute<A>(
188 S, D, ShouldAddAttribute, Metadata, CreateAttr, [](const Decl *D) {
189 return llvm::find_if(D->attrs(),
190 [](const Attr *Next) { return isa<A>(Next); });
191 });
192}
193} // namespace
194
195template <typename A>
196static void handleAPINotedRetainCountAttribute(Sema &S, Decl *D,
197 bool ShouldAddAttribute,
198 VersionedInfoMetadata Metadata) {
199 // The template argument has a default to make the "removal" case more
200 // concise; it doesn't matter /which/ attribute is being removed.
201 handleAPINotedAttribute<A>(
202 S, D, ShouldAddAttribute, Metadata,
203 [&] { return new (S.Context) A(S.Context, getPlaceholderAttrInfo()); },
204 [](const Decl *D) -> Decl::attr_iterator {
205 return llvm::find_if(D->attrs(), [](const Attr *Next) -> bool {
206 return isa<CFReturnsRetainedAttr>(Val: Next) ||
207 isa<CFReturnsNotRetainedAttr>(Val: Next) ||
208 isa<NSReturnsRetainedAttr>(Val: Next) ||
209 isa<NSReturnsNotRetainedAttr>(Val: Next) ||
210 isa<CFAuditedTransferAttr>(Val: Next);
211 });
212 });
213}
214
215static void handleAPINotedRetainCountConvention(
216 Sema &S, Decl *D, VersionedInfoMetadata Metadata,
217 std::optional<api_notes::RetainCountConventionKind> Convention) {
218 if (!Convention)
219 return;
220 switch (*Convention) {
221 case api_notes::RetainCountConventionKind::None:
222 if (isa<FunctionDecl>(Val: D)) {
223 handleAPINotedRetainCountAttribute<CFUnknownTransferAttr>(
224 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
225 } else {
226 handleAPINotedRetainCountAttribute<CFReturnsRetainedAttr>(
227 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: false, Metadata);
228 }
229 break;
230 case api_notes::RetainCountConventionKind::CFReturnsRetained:
231 handleAPINotedRetainCountAttribute<CFReturnsRetainedAttr>(
232 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
233 break;
234 case api_notes::RetainCountConventionKind::CFReturnsNotRetained:
235 handleAPINotedRetainCountAttribute<CFReturnsNotRetainedAttr>(
236 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
237 break;
238 case api_notes::RetainCountConventionKind::NSReturnsRetained:
239 handleAPINotedRetainCountAttribute<NSReturnsRetainedAttr>(
240 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
241 break;
242 case api_notes::RetainCountConventionKind::NSReturnsNotRetained:
243 handleAPINotedRetainCountAttribute<NSReturnsNotRetainedAttr>(
244 S, D, /*shouldAddAttribute*/ ShouldAddAttribute: true, Metadata);
245 break;
246 }
247}
248
249static void ProcessAPINotes(Sema &S, Decl *D,
250 const api_notes::CommonEntityInfo &Info,
251 VersionedInfoMetadata Metadata) {
252 // Availability
253 if (Info.Unavailable) {
254 handleAPINotedAttribute<UnavailableAttr>(S, D, ShouldAddAttribute: true, Metadata, CreateAttr: [&] {
255 return new (S.Context)
256 UnavailableAttr(S.Context, getPlaceholderAttrInfo(),
257 ASTAllocateString(Ctx&: S.Context, String: Info.UnavailableMsg));
258 });
259 }
260
261 if (Info.UnavailableInSwift) {
262 handleAPINotedAttribute<AvailabilityAttr>(
263 S, D, IsAddition: true, Metadata,
264 CreateAttr: [&] {
265 return new (S.Context) AvailabilityAttr(
266 S.Context, getPlaceholderAttrInfo(),
267 &S.Context.Idents.get(Name: "swift"), VersionTuple(), VersionTuple(),
268 VersionTuple(),
269 /*Unavailable=*/true,
270 ASTAllocateString(Ctx&: S.Context, String: Info.UnavailableMsg),
271 /*Strict=*/false,
272 /*Replacement=*/StringRef(),
273 /*Priority=*/Sema::AP_Explicit,
274 /*Environment=*/nullptr);
275 },
276 GetExistingAttr: [](const Decl *D) {
277 return llvm::find_if(Range: D->attrs(), P: [](const Attr *next) -> bool {
278 if (const auto *AA = dyn_cast<AvailabilityAttr>(Val: next))
279 if (const auto *II = AA->getPlatform())
280 return II->isStr(Str: "swift");
281 return false;
282 });
283 });
284 }
285
286 // swift_private
287 if (auto SwiftPrivate = Info.isSwiftPrivate()) {
288 handleAPINotedAttribute<SwiftPrivateAttr>(
289 S, D, ShouldAddAttribute: *SwiftPrivate, Metadata, CreateAttr: [&] {
290 return new (S.Context)
291 SwiftPrivateAttr(S.Context, getPlaceholderAttrInfo());
292 });
293 }
294
295 // swift_safety
296 if (auto SafetyKind = Info.getSwiftSafety()) {
297 bool Addition = *SafetyKind != api_notes::SwiftSafetyKind::Unspecified;
298 handleAPINotedAttribute<SwiftAttrAttr>(
299 S, D, IsAddition: Addition, Metadata,
300 CreateAttr: [&] {
301 return SwiftAttrAttr::Create(
302 Ctx&: S.Context, Attribute: *SafetyKind == api_notes::SwiftSafetyKind::Safe
303 ? "safe"
304 : "unsafe");
305 },
306 GetExistingAttr: [](const Decl *D) {
307 return llvm::find_if(Range: D->attrs(), P: [](const Attr *attr) {
308 if (const auto *swiftAttr = dyn_cast<SwiftAttrAttr>(Val: attr)) {
309 if (swiftAttr->getAttribute() == "safe" ||
310 swiftAttr->getAttribute() == "unsafe")
311 return true;
312 }
313 return false;
314 });
315 });
316 }
317
318 // swift_name
319 if (!Info.SwiftName.empty()) {
320 handleAPINotedAttribute<SwiftNameAttr>(
321 S, D, ShouldAddAttribute: true, Metadata, CreateAttr: [&]() -> SwiftNameAttr * {
322 AttributeFactory AF{};
323 AttributePool AP{AF};
324 auto &C = S.getASTContext();
325 ParsedAttr *SNA = AP.create(
326 attrName: &C.Idents.get(Name: "swift_name"), attrRange: SourceRange(), scope: AttributeScopeInfo(),
327 Param1: nullptr, Param2: nullptr, Param3: nullptr, form: ParsedAttr::Form::GNU());
328
329 if (!S.Swift().DiagnoseName(D, Name: Info.SwiftName, Loc: D->getLocation(), AL: *SNA,
330 /*IsAsync=*/false))
331 return nullptr;
332
333 return new (S.Context)
334 SwiftNameAttr(S.Context, getPlaceholderAttrInfo(),
335 ASTAllocateString(Ctx&: S.Context, String: Info.SwiftName));
336 });
337 }
338}
339
340static void ProcessAPINotes(Sema &S, Decl *D,
341 const api_notes::CommonTypeInfo &Info,
342 VersionedInfoMetadata Metadata) {
343 // swift_bridge
344 if (auto SwiftBridge = Info.getSwiftBridge()) {
345 handleAPINotedAttribute<SwiftBridgeAttr>(
346 S, D, ShouldAddAttribute: !SwiftBridge->empty(), Metadata, CreateAttr: [&] {
347 return new (S.Context)
348 SwiftBridgeAttr(S.Context, getPlaceholderAttrInfo(),
349 ASTAllocateString(Ctx&: S.Context, String: *SwiftBridge));
350 });
351 }
352
353 // ns_error_domain
354 if (auto NSErrorDomain = Info.getNSErrorDomain()) {
355 handleAPINotedAttribute<NSErrorDomainAttr>(
356 S, D, ShouldAddAttribute: !NSErrorDomain->empty(), Metadata, CreateAttr: [&] {
357 return new (S.Context)
358 NSErrorDomainAttr(S.Context, getPlaceholderAttrInfo(),
359 &S.Context.Idents.get(Name: *NSErrorDomain));
360 });
361 }
362
363 if (auto ConformsTo = Info.getSwiftConformance())
364 D->addAttr(
365 A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "conforms_to:" + ConformsTo.value()));
366
367 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
368 Metadata);
369}
370
371/// Check that the replacement type provided by API notes is reasonable.
372///
373/// This is a very weak form of ABI check.
374static bool checkAPINotesReplacementType(Sema &S, SourceLocation Loc,
375 QualType OrigType,
376 QualType ReplacementType) {
377 if (S.Context.getTypeSize(T: OrigType) !=
378 S.Context.getTypeSize(T: ReplacementType)) {
379 S.Diag(Loc, DiagID: diag::err_incompatible_replacement_type)
380 << ReplacementType << OrigType;
381 return true;
382 }
383
384 return false;
385}
386
387void Sema::ApplyAPINotesType(Decl *D, StringRef TypeString) {
388 if (!TypeString.empty() && ParseTypeFromStringCallback) {
389 auto ParsedType = ParseTypeFromStringCallback(TypeString, "<API Notes>",
390 D->getLocation());
391 if (ParsedType.isUsable()) {
392 QualType Type = Sema::GetTypeFromParser(Ty: ParsedType.get());
393 auto TypeInfo = Context.getTrivialTypeSourceInfo(T: Type, Loc: D->getLocation());
394 if (auto Var = dyn_cast<VarDecl>(Val: D)) {
395 // Make adjustments to parameter types.
396 if (isa<ParmVarDecl>(Val: Var)) {
397 Type = ObjC().AdjustParameterTypeForObjCAutoRefCount(
398 T: Type, NameLoc: D->getLocation(), TSInfo: TypeInfo);
399 Type = Context.getAdjustedParameterType(T: Type);
400 }
401
402 if (!checkAPINotesReplacementType(S&: *this, Loc: Var->getLocation(),
403 OrigType: Var->getType(), ReplacementType: Type)) {
404 Var->setType(Type);
405 Var->setTypeSourceInfo(TypeInfo);
406 }
407 } else if (auto property = dyn_cast<ObjCPropertyDecl>(Val: D)) {
408 if (!checkAPINotesReplacementType(S&: *this, Loc: property->getLocation(),
409 OrigType: property->getType(), ReplacementType: Type)) {
410 property->setType(T: Type, TSI: TypeInfo);
411 }
412 } else if (auto field = dyn_cast<FieldDecl>(Val: D)) {
413 if (!checkAPINotesReplacementType(S&: *this, Loc: field->getLocation(),
414 OrigType: field->getType(), ReplacementType: Type)) {
415 field->setType(Type);
416 field->setTypeSourceInfo(TypeInfo);
417 }
418 } else {
419 llvm_unreachable("API notes allowed a type on an unknown declaration");
420 }
421 }
422 }
423}
424
425void Sema::ApplyNullability(Decl *D, NullabilityKind Nullability) {
426 auto GetModified =
427 [&](class Decl *D, QualType QT,
428 NullabilityKind Nullability) -> std::optional<QualType> {
429 QualType Original = QT;
430 CheckImplicitNullabilityTypeSpecifier(Type&: QT, Nullability, DiagLoc: D->getLocation(),
431 AllowArrayTypes: isa<ParmVarDecl>(Val: D),
432 /*OverrideExisting=*/true);
433 return (QT.getTypePtr() != Original.getTypePtr()) ? std::optional(QT)
434 : std::nullopt;
435 };
436
437 if (auto Function = dyn_cast<FunctionDecl>(Val: D)) {
438 if (auto Modified =
439 GetModified(D, Function->getReturnType(), Nullability)) {
440 const FunctionType *FnType = Function->getType()->castAs<FunctionType>();
441 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(Val: FnType))
442 Function->setType(Context.getFunctionType(
443 ResultTy: *Modified, Args: proto->getParamTypes(), EPI: proto->getExtProtoInfo()));
444 else
445 Function->setType(
446 Context.getFunctionNoProtoType(ResultTy: *Modified, Info: FnType->getExtInfo()));
447 }
448 } else if (auto Method = dyn_cast<ObjCMethodDecl>(Val: D)) {
449 if (auto Modified = GetModified(D, Method->getReturnType(), Nullability)) {
450 Method->setReturnType(*Modified);
451
452 // Make it a context-sensitive keyword if we can.
453 if (!isIndirectPointerType(Type: *Modified))
454 Method->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
455 Method->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
456 }
457 } else if (auto Value = dyn_cast<ValueDecl>(Val: D)) {
458 if (auto Modified = GetModified(D, Value->getType(), Nullability)) {
459 Value->setType(*Modified);
460
461 // Make it a context-sensitive keyword if we can.
462 if (auto Parm = dyn_cast<ParmVarDecl>(Val: D)) {
463 if (Parm->isObjCMethodParameter() && !isIndirectPointerType(Type: *Modified))
464 Parm->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
465 Parm->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
466 }
467 }
468 } else if (auto Property = dyn_cast<ObjCPropertyDecl>(Val: D)) {
469 if (auto Modified = GetModified(D, Property->getType(), Nullability)) {
470 Property->setType(T: *Modified, TSI: Property->getTypeSourceInfo());
471
472 // Make it a property attribute if we can.
473 if (!isIndirectPointerType(Type: *Modified))
474 Property->setPropertyAttributes(
475 ObjCPropertyAttribute::kind_null_resettable);
476 }
477 }
478}
479
480/// Process API notes for a variable or property.
481static void ProcessAPINotes(Sema &S, Decl *D,
482 const api_notes::VariableInfo &Info,
483 VersionedInfoMetadata Metadata) {
484 // Type override.
485 applyAPINotesType(S, decl: D, typeString: Info.getType(), metadata: Metadata);
486
487 // Nullability.
488 if (auto Nullability = Info.getNullability())
489 applyNullability(S, decl: D, nullability: *Nullability, metadata: Metadata);
490
491 // Handle common entity information.
492 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
493 Metadata);
494}
495
496/// Process API notes for a parameter.
497static void ProcessAPINotes(Sema &S, ParmVarDecl *D,
498 const api_notes::ParamInfo &Info,
499 VersionedInfoMetadata Metadata) {
500 // noescape
501 if (auto NoEscape = Info.isNoEscape())
502 handleAPINotedAttribute<NoEscapeAttr>(S, D, ShouldAddAttribute: *NoEscape, Metadata, CreateAttr: [&] {
503 return new (S.Context) NoEscapeAttr(S.Context, getPlaceholderAttrInfo());
504 });
505
506 if (auto Lifetimebound = Info.isLifetimebound())
507 handleAPINotedAttribute<LifetimeBoundAttr>(
508 S, D, ShouldAddAttribute: *Lifetimebound, Metadata, CreateAttr: [&] {
509 return new (S.Context)
510 LifetimeBoundAttr(S.Context, getPlaceholderAttrInfo());
511 });
512
513 // Retain count convention
514 handleAPINotedRetainCountConvention(S, D, Metadata,
515 Convention: Info.getRetainCountConvention());
516
517 // Handle common entity information.
518 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
519 Metadata);
520}
521
522/// Process API notes for a global variable.
523static void ProcessAPINotes(Sema &S, VarDecl *D,
524 const api_notes::GlobalVariableInfo &Info,
525 VersionedInfoMetadata metadata) {
526 // Handle common entity information.
527 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
528 Metadata: metadata);
529}
530
531/// Process API notes for a C field.
532static void ProcessAPINotes(Sema &S, FieldDecl *D,
533 const api_notes::FieldInfo &Info,
534 VersionedInfoMetadata metadata) {
535 // Handle common entity information.
536 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
537 Metadata: metadata);
538}
539
540/// Process API notes for an Objective-C property.
541static void ProcessAPINotes(Sema &S, ObjCPropertyDecl *D,
542 const api_notes::ObjCPropertyInfo &Info,
543 VersionedInfoMetadata Metadata) {
544 // Handle common entity information.
545 ProcessAPINotes(S, D, Info: static_cast<const api_notes::VariableInfo &>(Info),
546 Metadata);
547
548 if (auto AsAccessors = Info.getSwiftImportAsAccessors()) {
549 handleAPINotedAttribute<SwiftImportPropertyAsAccessorsAttr>(
550 S, D, ShouldAddAttribute: *AsAccessors, Metadata, CreateAttr: [&] {
551 return new (S.Context) SwiftImportPropertyAsAccessorsAttr(
552 S.Context, getPlaceholderAttrInfo());
553 });
554 }
555}
556
557namespace {
558typedef llvm::PointerUnion<FunctionDecl *, ObjCMethodDecl *> FunctionOrMethod;
559}
560
561/// Process API notes for a function or method.
562static void ProcessAPINotes(Sema &S, FunctionOrMethod AnyFunc,
563 const api_notes::FunctionInfo &Info,
564 VersionedInfoMetadata Metadata) {
565 // Find the declaration itself.
566 FunctionDecl *FD = dyn_cast<FunctionDecl *>(Val&: AnyFunc);
567 Decl *D = FD;
568 ObjCMethodDecl *MD = nullptr;
569 if (!D) {
570 MD = cast<ObjCMethodDecl *>(Val&: AnyFunc);
571 D = MD;
572 }
573
574 assert((FD || MD) && "Expecting Function or ObjCMethod");
575
576 // Nullability of return type.
577 if (Info.NullabilityAudited)
578 applyNullability(S, decl: D, nullability: Info.getReturnTypeInfo(), metadata: Metadata);
579
580 // Parameters.
581 unsigned NumParams = FD ? FD->getNumParams() : MD->param_size();
582
583 bool AnyTypeChanged = false;
584 for (unsigned I = 0; I != NumParams; ++I) {
585 ParmVarDecl *Param = FD ? FD->getParamDecl(i: I) : MD->param_begin()[I];
586 QualType ParamTypeBefore = Param->getType();
587
588 if (I < Info.Params.size())
589 ProcessAPINotes(S, D: Param, Info: Info.Params[I], Metadata);
590
591 // Nullability.
592 if (Info.NullabilityAudited)
593 applyNullability(S, decl: Param, nullability: Info.getParamTypeInfo(index: I), metadata: Metadata);
594
595 if (ParamTypeBefore.getAsOpaquePtr() != Param->getType().getAsOpaquePtr())
596 AnyTypeChanged = true;
597 }
598
599 // returns_(un)retained
600 if (!Info.SwiftReturnOwnership.empty())
601 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context,
602 Attribute: "returns_" + Info.SwiftReturnOwnership));
603
604 // Result type override.
605 QualType OverriddenResultType;
606 if (Metadata.IsActive && !Info.ResultType.empty() &&
607 S.ParseTypeFromStringCallback) {
608 auto ParsedType = S.ParseTypeFromStringCallback(
609 Info.ResultType, "<API Notes>", D->getLocation());
610 if (ParsedType.isUsable()) {
611 QualType ResultType = Sema::GetTypeFromParser(Ty: ParsedType.get());
612
613 if (MD) {
614 if (!checkAPINotesReplacementType(S, Loc: D->getLocation(),
615 OrigType: MD->getReturnType(), ReplacementType: ResultType)) {
616 auto ResultTypeInfo =
617 S.Context.getTrivialTypeSourceInfo(T: ResultType, Loc: D->getLocation());
618 MD->setReturnType(ResultType);
619 MD->setReturnTypeSourceInfo(ResultTypeInfo);
620 }
621 } else if (!checkAPINotesReplacementType(
622 S, Loc: FD->getLocation(), OrigType: FD->getReturnType(), ReplacementType: ResultType)) {
623 OverriddenResultType = ResultType;
624 AnyTypeChanged = true;
625 }
626 }
627 }
628
629 // If the result type or any of the parameter types changed for a function
630 // declaration, we have to rebuild the type.
631 if (FD && AnyTypeChanged) {
632 if (const auto *fnProtoType = FD->getType()->getAs<FunctionProtoType>()) {
633 if (OverriddenResultType.isNull())
634 OverriddenResultType = fnProtoType->getReturnType();
635
636 SmallVector<QualType, 4> ParamTypes;
637 for (auto Param : FD->parameters())
638 ParamTypes.push_back(Elt: Param->getType());
639
640 FD->setType(S.Context.getFunctionType(ResultTy: OverriddenResultType, Args: ParamTypes,
641 EPI: fnProtoType->getExtProtoInfo()));
642 } else if (!OverriddenResultType.isNull()) {
643 const auto *FnNoProtoType = FD->getType()->castAs<FunctionNoProtoType>();
644 FD->setType(S.Context.getFunctionNoProtoType(
645 ResultTy: OverriddenResultType, Info: FnNoProtoType->getExtInfo()));
646 }
647 }
648
649 // Retain count convention
650 handleAPINotedRetainCountConvention(S, D, Metadata,
651 Convention: Info.getRetainCountConvention());
652
653 // Handle common entity information.
654 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
655 Metadata);
656}
657
658/// Process API notes for a C++ method.
659static void ProcessAPINotes(Sema &S, CXXMethodDecl *Method,
660 const api_notes::CXXMethodInfo &Info,
661 VersionedInfoMetadata Metadata) {
662 if (Info.This && Info.This->isLifetimebound() &&
663 !lifetimes::implicitObjectParamIsLifetimeBound(FD: Method)) {
664 auto MethodType = Method->getType();
665 auto *attr = ::new (S.Context)
666 LifetimeBoundAttr(S.Context, getPlaceholderAttrInfo());
667 QualType AttributedType =
668 S.Context.getAttributedType(attr, modifiedType: MethodType, equivalentType: MethodType);
669 TypeLocBuilder TLB;
670 TLB.pushFullCopy(L: Method->getTypeSourceInfo()->getTypeLoc());
671 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(T: AttributedType);
672 TyLoc.setAttr(attr);
673 Method->setType(AttributedType);
674 Method->setTypeSourceInfo(TLB.getTypeSourceInfo(Context&: S.Context, T: AttributedType));
675 }
676
677 ProcessAPINotes(S, AnyFunc: (FunctionOrMethod)Method, Info, Metadata);
678}
679
680/// Process API notes for a global function.
681static void ProcessAPINotes(Sema &S, FunctionDecl *D,
682 const api_notes::GlobalFunctionInfo &Info,
683 VersionedInfoMetadata Metadata) {
684 // Handle common function information.
685 ProcessAPINotes(S, AnyFunc: FunctionOrMethod(D),
686 Info: static_cast<const api_notes::FunctionInfo &>(Info), Metadata);
687}
688
689/// Process API notes for an enumerator.
690static void ProcessAPINotes(Sema &S, EnumConstantDecl *D,
691 const api_notes::EnumConstantInfo &Info,
692 VersionedInfoMetadata Metadata) {
693 // Handle common information.
694 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonEntityInfo &>(Info),
695 Metadata);
696}
697
698/// Process API notes for an Objective-C method.
699static void ProcessAPINotes(Sema &S, ObjCMethodDecl *D,
700 const api_notes::ObjCMethodInfo &Info,
701 VersionedInfoMetadata Metadata) {
702 // Designated initializers.
703 if (Info.DesignatedInit) {
704 handleAPINotedAttribute<ObjCDesignatedInitializerAttr>(
705 S, D, ShouldAddAttribute: true, Metadata, CreateAttr: [&] {
706 if (ObjCInterfaceDecl *IFace = D->getClassInterface())
707 IFace->setHasDesignatedInitializers();
708
709 return new (S.Context) ObjCDesignatedInitializerAttr(
710 S.Context, getPlaceholderAttrInfo());
711 });
712 }
713
714 // Handle common function information.
715 ProcessAPINotes(S, AnyFunc: FunctionOrMethod(D),
716 Info: static_cast<const api_notes::FunctionInfo &>(Info), Metadata);
717}
718
719/// Process API notes for a tag.
720static void ProcessAPINotes(Sema &S, TagDecl *D, const api_notes::TagInfo &Info,
721 VersionedInfoMetadata Metadata) {
722 if (auto ImportAs = Info.SwiftImportAs)
723 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "import_" + ImportAs.value()));
724
725 if (auto RetainOp = Info.SwiftRetainOp)
726 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "retain:" + RetainOp.value()));
727
728 if (auto ReleaseOp = Info.SwiftReleaseOp)
729 D->addAttr(
730 A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "release:" + ReleaseOp.value()));
731 if (auto DestroyOp = Info.SwiftDestroyOp)
732 D->addAttr(
733 A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "destroy:" + DestroyOp.value()));
734 if (auto DefaultOwnership = Info.SwiftDefaultOwnership)
735 D->addAttr(A: SwiftAttrAttr::Create(
736 Ctx&: S.Context, Attribute: "returned_as_" + DefaultOwnership.value() + "_by_default"));
737
738 if (auto Copyable = Info.isSwiftCopyable()) {
739 if (!*Copyable)
740 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context, Attribute: "~Copyable"));
741 }
742
743 if (auto Escapable = Info.isSwiftEscapable()) {
744 D->addAttr(A: SwiftAttrAttr::Create(Ctx&: S.Context,
745 Attribute: *Escapable ? "Escapable" : "~Escapable"));
746 }
747
748 if (auto Extensibility = Info.EnumExtensibility) {
749 using api_notes::EnumExtensibilityKind;
750 bool ShouldAddAttribute = (*Extensibility != EnumExtensibilityKind::None);
751 handleAPINotedAttribute<EnumExtensibilityAttr>(
752 S, D, ShouldAddAttribute, Metadata, CreateAttr: [&] {
753 EnumExtensibilityAttr::Kind kind;
754 switch (*Extensibility) {
755 case EnumExtensibilityKind::None:
756 llvm_unreachable("remove only");
757 case EnumExtensibilityKind::Open:
758 kind = EnumExtensibilityAttr::Open;
759 break;
760 case EnumExtensibilityKind::Closed:
761 kind = EnumExtensibilityAttr::Closed;
762 break;
763 }
764 return new (S.Context)
765 EnumExtensibilityAttr(S.Context, getPlaceholderAttrInfo(), kind);
766 });
767 }
768
769 if (auto FlagEnum = Info.isFlagEnum()) {
770 handleAPINotedAttribute<FlagEnumAttr>(S, D, ShouldAddAttribute: *FlagEnum, Metadata, CreateAttr: [&] {
771 return new (S.Context) FlagEnumAttr(S.Context, getPlaceholderAttrInfo());
772 });
773 }
774
775 // Handle common type information.
776 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonTypeInfo &>(Info),
777 Metadata);
778}
779
780/// Process API notes for a typedef.
781static void ProcessAPINotes(Sema &S, TypedefNameDecl *D,
782 const api_notes::TypedefInfo &Info,
783 VersionedInfoMetadata Metadata) {
784 // swift_wrapper
785 using SwiftWrapperKind = api_notes::SwiftNewTypeKind;
786
787 if (auto SwiftWrapper = Info.SwiftWrapper) {
788 handleAPINotedAttribute<SwiftNewTypeAttr>(
789 S, D, ShouldAddAttribute: *SwiftWrapper != SwiftWrapperKind::None, Metadata, CreateAttr: [&] {
790 SwiftNewTypeAttr::NewtypeKind Kind;
791 switch (*SwiftWrapper) {
792 case SwiftWrapperKind::None:
793 llvm_unreachable("Shouldn't build an attribute");
794
795 case SwiftWrapperKind::Struct:
796 Kind = SwiftNewTypeAttr::NK_Struct;
797 break;
798
799 case SwiftWrapperKind::Enum:
800 Kind = SwiftNewTypeAttr::NK_Enum;
801 break;
802 }
803 AttributeCommonInfo SyntaxInfo{
804 SourceRange(),
805 AttributeCommonInfo::AT_SwiftNewType,
806 {AttributeCommonInfo::AS_GNU, SwiftNewTypeAttr::GNU_swift_wrapper,
807 /*IsAlignas*/ false, /*IsRegularKeywordAttribute*/ false}};
808 return new (S.Context) SwiftNewTypeAttr(S.Context, SyntaxInfo, Kind);
809 });
810 }
811
812 // Handle common type information.
813 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonTypeInfo &>(Info),
814 Metadata);
815}
816
817/// Process API notes for an Objective-C class or protocol.
818static void ProcessAPINotes(Sema &S, ObjCContainerDecl *D,
819 const api_notes::ContextInfo &Info,
820 VersionedInfoMetadata Metadata) {
821 // Handle common type information.
822 ProcessAPINotes(S, D, Info: static_cast<const api_notes::CommonTypeInfo &>(Info),
823 Metadata);
824}
825
826/// Process API notes for an Objective-C class.
827static void ProcessAPINotes(Sema &S, ObjCInterfaceDecl *D,
828 const api_notes::ContextInfo &Info,
829 VersionedInfoMetadata Metadata) {
830 if (auto AsNonGeneric = Info.getSwiftImportAsNonGeneric()) {
831 handleAPINotedAttribute<SwiftImportAsNonGenericAttr>(
832 S, D, ShouldAddAttribute: *AsNonGeneric, Metadata, CreateAttr: [&] {
833 return new (S.Context)
834 SwiftImportAsNonGenericAttr(S.Context, getPlaceholderAttrInfo());
835 });
836 }
837
838 if (auto ObjcMembers = Info.getSwiftObjCMembers()) {
839 handleAPINotedAttribute<SwiftObjCMembersAttr>(
840 S, D, ShouldAddAttribute: *ObjcMembers, Metadata, CreateAttr: [&] {
841 return new (S.Context)
842 SwiftObjCMembersAttr(S.Context, getPlaceholderAttrInfo());
843 });
844 }
845
846 // Handle information common to Objective-C classes and protocols.
847 ProcessAPINotes(S, D: static_cast<clang::ObjCContainerDecl *>(D), Info,
848 Metadata);
849}
850
851/// If we're applying API notes with an active, non-default version, and the
852/// versioned API notes have a SwiftName but the declaration normally wouldn't
853/// have one, add a removal attribute to make it clear that the new SwiftName
854/// attribute only applies to the active version of \p D, not to all versions.
855///
856/// This must be run \em before processing API notes for \p D, because otherwise
857/// any existing SwiftName attribute will have been packaged up in a
858/// SwiftVersionedAdditionAttr.
859template <typename SpecificInfo>
860static void maybeAttachUnversionedSwiftName(
861 Sema &S, Decl *D,
862 const api_notes::APINotesReader::VersionedInfo<SpecificInfo> Info) {
863 if (D->hasAttr<SwiftNameAttr>())
864 return;
865 if (!Info.getSelected())
866 return;
867
868 // Is the active slice versioned, and does it set a Swift name?
869 VersionTuple SelectedVersion;
870 SpecificInfo SelectedInfoSlice;
871 std::tie(SelectedVersion, SelectedInfoSlice) = Info[*Info.getSelected()];
872 if (SelectedVersion.empty())
873 return;
874 if (SelectedInfoSlice.SwiftName.empty())
875 return;
876
877 // Does the unversioned slice /not/ set a Swift name?
878 for (const auto &VersionAndInfoSlice : Info) {
879 if (!VersionAndInfoSlice.first.empty())
880 continue;
881 if (!VersionAndInfoSlice.second.SwiftName.empty())
882 return;
883 }
884
885 // Then explicitly call that out with a removal attribute.
886 VersionedInfoMetadata DummyFutureMetadata(
887 SelectedVersion, IsActive_t::Inactive, IsSubstitution_t::Replacement);
888 handleAPINotedAttribute<SwiftNameAttr>(
889 S, D, /*add*/ false, DummyFutureMetadata, []() -> SwiftNameAttr * {
890 llvm_unreachable("should not try to add an attribute here");
891 });
892}
893
894/// Processes all versions of versioned API notes.
895///
896/// Just dispatches to the various ProcessAPINotes functions in this file.
897template <typename SpecificDecl, typename SpecificInfo>
898static void ProcessVersionedAPINotes(
899 Sema &S, SpecificDecl *D,
900 const api_notes::APINotesReader::VersionedInfo<SpecificInfo> Info) {
901
902 if (!S.captureSwiftVersionIndependentAPINotes())
903 maybeAttachUnversionedSwiftName(S, D, Info);
904
905 unsigned Selected = Info.getSelected().value_or(Info.size());
906
907 VersionTuple Version;
908 SpecificInfo InfoSlice;
909 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
910 std::tie(Version, InfoSlice) = Info[i];
911 auto Active = (i == Selected) ? IsActive_t::Active : IsActive_t::Inactive;
912 auto Replacement = IsSubstitution_t::Original;
913
914 // When collection all APINotes as version-independent,
915 // capture all as inactive and defer to the client select the
916 // right one.
917 if (S.captureSwiftVersionIndependentAPINotes()) {
918 Active = IsActive_t::Inactive;
919 Replacement = IsSubstitution_t::Original;
920 } else if (Active == IsActive_t::Inactive && Version.empty()) {
921 Replacement = IsSubstitution_t::Replacement;
922 Version = Info[Selected].first;
923 }
924
925 ProcessAPINotes(S, D, InfoSlice,
926 VersionedInfoMetadata(Version, Active, Replacement));
927 }
928}
929
930static std::optional<api_notes::Context>
931UnwindNamespaceContext(DeclContext *DC, api_notes::APINotesManager &APINotes) {
932 if (auto NamespaceContext = dyn_cast<NamespaceDecl>(Val: DC)) {
933 for (auto Reader : APINotes.findAPINotes(Loc: NamespaceContext->getLocation())) {
934 // Retrieve the context ID for the parent namespace of the decl.
935 std::stack<NamespaceDecl *> NamespaceStack;
936 {
937 for (auto CurrentNamespace = NamespaceContext; CurrentNamespace;
938 CurrentNamespace =
939 dyn_cast<NamespaceDecl>(Val: CurrentNamespace->getParent())) {
940 if (!CurrentNamespace->isInlineNamespace())
941 NamespaceStack.push(x: CurrentNamespace);
942 }
943 }
944 std::optional<api_notes::ContextID> NamespaceID;
945 while (!NamespaceStack.empty()) {
946 auto CurrentNamespace = NamespaceStack.top();
947 NamespaceStack.pop();
948 NamespaceID =
949 Reader->lookupNamespaceID(Name: CurrentNamespace->getName(), ParentNamespaceID: NamespaceID);
950 if (!NamespaceID)
951 return std::nullopt;
952 }
953 if (NamespaceID)
954 return api_notes::Context(*NamespaceID,
955 api_notes::ContextKind::Namespace);
956 }
957 }
958 return std::nullopt;
959}
960
961static std::optional<api_notes::Context>
962UnwindTagContext(TagDecl *DC, api_notes::APINotesManager &APINotes) {
963 assert(DC && "tag context must not be null");
964 for (auto Reader : APINotes.findAPINotes(Loc: DC->getLocation())) {
965 // Retrieve the context ID for the parent tag of the decl.
966 std::stack<TagDecl *> TagStack;
967 {
968 for (auto CurrentTag = DC; CurrentTag;
969 CurrentTag = dyn_cast<TagDecl>(Val: CurrentTag->getParent()))
970 TagStack.push(x: CurrentTag);
971 }
972 assert(!TagStack.empty());
973 std::optional<api_notes::Context> Ctx =
974 UnwindNamespaceContext(DC: TagStack.top()->getDeclContext(), APINotes);
975 while (!TagStack.empty()) {
976 auto CurrentTag = TagStack.top();
977 TagStack.pop();
978 auto CtxID = Reader->lookupTagID(Name: CurrentTag->getName(), ParentCtx: Ctx);
979 if (!CtxID)
980 return std::nullopt;
981 Ctx = api_notes::Context(*CtxID, api_notes::ContextKind::Tag);
982 }
983 return Ctx;
984 }
985 return std::nullopt;
986}
987
988/// Process API notes that are associated with this declaration, mapping them
989/// to attributes as appropriate.
990void Sema::ProcessAPINotes(Decl *D) {
991 if (!D)
992 return;
993
994 auto *DC = D->getDeclContext();
995 // Globals.
996 if (DC->isFileContext() || DC->isNamespace() ||
997 DC->getDeclKind() == Decl::LinkageSpec) {
998 std::optional<api_notes::Context> APINotesContext =
999 UnwindNamespaceContext(DC, APINotes);
1000 // Global variables.
1001 if (auto VD = dyn_cast<VarDecl>(Val: D)) {
1002 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1003 auto Info =
1004 Reader->lookupGlobalVariable(Name: VD->getName(), Ctx: APINotesContext);
1005 ProcessVersionedAPINotes(S&: *this, D: VD, Info);
1006 }
1007
1008 return;
1009 }
1010
1011 // Global functions.
1012 if (auto FD = dyn_cast<FunctionDecl>(Val: D)) {
1013 if (FD->getDeclName().isIdentifier()) {
1014 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1015 auto Info =
1016 Reader->lookupGlobalFunction(Name: FD->getName(), Ctx: APINotesContext);
1017 ProcessVersionedAPINotes(S&: *this, D: FD, Info);
1018 }
1019 }
1020
1021 return;
1022 }
1023
1024 // Objective-C classes.
1025 if (auto Class = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
1026 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1027 auto Info = Reader->lookupObjCClassInfo(Name: Class->getName());
1028 ProcessVersionedAPINotes(S&: *this, D: Class, Info);
1029 }
1030
1031 return;
1032 }
1033
1034 // Objective-C protocols.
1035 if (auto Protocol = dyn_cast<ObjCProtocolDecl>(Val: D)) {
1036 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1037 auto Info = Reader->lookupObjCProtocolInfo(Name: Protocol->getName());
1038 ProcessVersionedAPINotes(S&: *this, D: Protocol, Info);
1039 }
1040
1041 return;
1042 }
1043
1044 // Tags
1045 if (auto Tag = dyn_cast<TagDecl>(Val: D)) {
1046 // Determine the name of the entity to search for. If this is an
1047 // anonymous tag that gets its linked name from a typedef, look for the
1048 // typedef name. This allows tag-specific information to be added
1049 // to the declaration.
1050 std::string LookupName;
1051 if (auto typedefName = Tag->getTypedefNameForAnonDecl())
1052 LookupName = typedefName->getName().str();
1053 else
1054 LookupName = Tag->getName().str();
1055
1056 // Use the source location to discern if this Tag is an OPTIONS macro.
1057 // For now we would like to limit this trick of looking up the APINote tag
1058 // using the EnumDecl's QualType in the case where the enum is anonymous.
1059 // This is only being used to support APINotes lookup for C++
1060 // NS/CF_OPTIONS when C++-Interop is enabled.
1061 std::string MacroName =
1062 LookupName.empty() && Tag->getOuterLocStart().isMacroID()
1063 ? clang::Lexer::getImmediateMacroName(
1064 Loc: Tag->getOuterLocStart(),
1065 SM: Tag->getASTContext().getSourceManager(), LangOpts)
1066 .str()
1067 : "";
1068
1069 if (LookupName.empty() && isa<clang::EnumDecl>(Val: Tag) &&
1070 (MacroName == "CF_OPTIONS" || MacroName == "NS_OPTIONS" ||
1071 MacroName == "OBJC_OPTIONS" || MacroName == "SWIFT_OPTIONS")) {
1072
1073 clang::QualType T = llvm::cast<clang::EnumDecl>(Val: Tag)->getIntegerType();
1074 LookupName = clang::QualType::getAsString(
1075 split: T.split(), Policy: getASTContext().getPrintingPolicy());
1076 }
1077
1078 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1079 if (auto ParentTag = dyn_cast<TagDecl>(Val: Tag->getDeclContext()))
1080 APINotesContext = UnwindTagContext(DC: ParentTag, APINotes);
1081 auto Info = Reader->lookupTag(Name: LookupName, Ctx: APINotesContext);
1082 ProcessVersionedAPINotes(S&: *this, D: Tag, Info);
1083 }
1084
1085 return;
1086 }
1087
1088 // Typedefs
1089 if (auto Typedef = dyn_cast<TypedefNameDecl>(Val: D)) {
1090 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1091 auto Info = Reader->lookupTypedef(Name: Typedef->getName(), Ctx: APINotesContext);
1092 ProcessVersionedAPINotes(S&: *this, D: Typedef, Info);
1093 }
1094
1095 return;
1096 }
1097 }
1098
1099 // Enumerators.
1100 if (DC->getRedeclContext()->isFileContext() ||
1101 DC->getRedeclContext()->isExternCContext()) {
1102 if (auto EnumConstant = dyn_cast<EnumConstantDecl>(Val: D)) {
1103 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1104 auto Info = Reader->lookupEnumConstant(Name: EnumConstant->getName());
1105 ProcessVersionedAPINotes(S&: *this, D: EnumConstant, Info);
1106 }
1107
1108 return;
1109 }
1110 }
1111
1112 if (auto ObjCContainer = dyn_cast<ObjCContainerDecl>(Val: DC)) {
1113 // Location function that looks up an Objective-C context.
1114 auto GetContext = [&](api_notes::APINotesReader *Reader)
1115 -> std::optional<api_notes::ContextID> {
1116 if (auto Protocol = dyn_cast<ObjCProtocolDecl>(Val: ObjCContainer)) {
1117 if (auto Found = Reader->lookupObjCProtocolID(Name: Protocol->getName()))
1118 return *Found;
1119
1120 return std::nullopt;
1121 }
1122
1123 if (auto Impl = dyn_cast<ObjCCategoryImplDecl>(Val: ObjCContainer)) {
1124 if (auto Cat = Impl->getCategoryDecl())
1125 ObjCContainer = Cat->getClassInterface();
1126 else
1127 return std::nullopt;
1128 }
1129
1130 if (auto Category = dyn_cast<ObjCCategoryDecl>(Val: ObjCContainer)) {
1131 if (Category->getClassInterface())
1132 ObjCContainer = Category->getClassInterface();
1133 else
1134 return std::nullopt;
1135 }
1136
1137 if (auto Impl = dyn_cast<ObjCImplDecl>(Val: ObjCContainer)) {
1138 if (Impl->getClassInterface())
1139 ObjCContainer = Impl->getClassInterface();
1140 else
1141 return std::nullopt;
1142 }
1143
1144 if (auto Class = dyn_cast<ObjCInterfaceDecl>(Val: ObjCContainer)) {
1145 if (auto Found = Reader->lookupObjCClassID(Name: Class->getName()))
1146 return *Found;
1147
1148 return std::nullopt;
1149 }
1150
1151 return std::nullopt;
1152 };
1153
1154 // Objective-C methods.
1155 if (auto Method = dyn_cast<ObjCMethodDecl>(Val: D)) {
1156 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1157 if (auto Context = GetContext(Reader)) {
1158 // Map the selector.
1159 Selector Sel = Method->getSelector();
1160 SmallVector<StringRef, 2> SelPieces;
1161 if (Sel.isUnarySelector()) {
1162 SelPieces.push_back(Elt: Sel.getNameForSlot(argIndex: 0));
1163 } else {
1164 for (unsigned i = 0, n = Sel.getNumArgs(); i != n; ++i)
1165 SelPieces.push_back(Elt: Sel.getNameForSlot(argIndex: i));
1166 }
1167
1168 api_notes::ObjCSelectorRef SelectorRef;
1169 SelectorRef.NumArgs = Sel.getNumArgs();
1170 SelectorRef.Identifiers = SelPieces;
1171
1172 auto Info = Reader->lookupObjCMethod(CtxID: *Context, Selector: SelectorRef,
1173 IsInstanceMethod: Method->isInstanceMethod());
1174 ProcessVersionedAPINotes(S&: *this, D: Method, Info);
1175 }
1176 }
1177 }
1178
1179 // Objective-C properties.
1180 if (auto Property = dyn_cast<ObjCPropertyDecl>(Val: D)) {
1181 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1182 if (auto Context = GetContext(Reader)) {
1183 bool isInstanceProperty =
1184 (Property->getPropertyAttributesAsWritten() &
1185 ObjCPropertyAttribute::kind_class) == 0;
1186 auto Info = Reader->lookupObjCProperty(CtxID: *Context, Name: Property->getName(),
1187 IsInstance: isInstanceProperty);
1188 ProcessVersionedAPINotes(S&: *this, D: Property, Info);
1189 }
1190 }
1191
1192 return;
1193 }
1194 }
1195
1196 if (auto TagContext = dyn_cast<TagDecl>(Val: DC)) {
1197 if (auto CXXMethod = dyn_cast<CXXMethodDecl>(Val: D)) {
1198 if (!isa<CXXConstructorDecl>(Val: CXXMethod) &&
1199 !isa<CXXDestructorDecl>(Val: CXXMethod) &&
1200 !isa<CXXConversionDecl>(Val: CXXMethod)) {
1201 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1202 if (auto Context = UnwindTagContext(DC: TagContext, APINotes)) {
1203 std::string MethodName;
1204 if (CXXMethod->isOverloadedOperator())
1205 MethodName =
1206 std::string("operator") +
1207 getOperatorSpelling(Operator: CXXMethod->getOverloadedOperator());
1208 else
1209 MethodName = CXXMethod->getName();
1210
1211 auto Info = Reader->lookupCXXMethod(CtxID: Context->id, Name: MethodName);
1212 ProcessVersionedAPINotes(S&: *this, D: CXXMethod, Info);
1213 }
1214 }
1215 }
1216 }
1217
1218 if (auto Field = dyn_cast<FieldDecl>(Val: D)) {
1219 if (!Field->isUnnamedBitField() && !Field->isAnonymousStructOrUnion()) {
1220 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1221 if (auto Context = UnwindTagContext(DC: TagContext, APINotes)) {
1222 auto Info = Reader->lookupField(CtxID: Context->id, Name: Field->getName());
1223 ProcessVersionedAPINotes(S&: *this, D: Field, Info);
1224 }
1225 }
1226 }
1227 }
1228
1229 if (auto Tag = dyn_cast<TagDecl>(Val: D)) {
1230 for (auto Reader : APINotes.findAPINotes(Loc: D->getLocation())) {
1231 if (auto Context = UnwindTagContext(DC: TagContext, APINotes)) {
1232 auto Info = Reader->lookupTag(Name: Tag->getName(), Ctx: Context);
1233 ProcessVersionedAPINotes(S&: *this, D: Tag, Info);
1234 }
1235 }
1236 }
1237 }
1238}
1239