clang 23.0.0git
SemaAPINotes.cpp
Go to the documentation of this file.
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"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/TypeLoc.h"
22#include "clang/Lex/Lexer.h"
23#include "clang/Sema/SemaObjC.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.
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.
65 auto *typeAttr = SwiftTypeAttr::CreateImplicit(S.Context, typeString);
66 auto *versioned = SwiftVersionedAdditionAttr::CreateImplicit(
67 S.Context, metadata.Version, typeAttr, metadata.IsReplacement);
68 decl->addAttr(versioned);
69 } else {
70 if (!metadata.IsActive)
71 return;
72 S.ApplyAPINotesType(decl, 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.
82 SwiftNullabilityAttr::Kind attrNullabilityKind;
83 switch (nullability) {
85 attrNullabilityKind = SwiftNullabilityAttr::Kind::NonNull;
86 break;
88 attrNullabilityKind = SwiftNullabilityAttr::Kind::Nullable;
89 break;
91 attrNullabilityKind = SwiftNullabilityAttr::Kind::Unspecified;
92 break;
94 attrNullabilityKind = SwiftNullabilityAttr::Kind::NullableResult;
95 break;
96 }
97 auto *nullabilityAttr =
98 SwiftNullabilityAttr::CreateImplicit(S.Context, attrNullabilityKind);
99 auto *versioned = SwiftVersionedAdditionAttr::CreateImplicit(
100 S.Context, metadata.Version, nullabilityAttr, metadata.IsReplacement);
101 decl->addAttr(versioned);
102 return;
103 } else {
104 if (!metadata.IsActive)
105 return;
106
107 S.ApplyNullability(decl, nullability);
108 }
109}
110
111/// Copy a string into ASTContext-allocated memory.
112static StringRef ASTAllocateString(ASTContext &Ctx, StringRef String) {
113 void *mem = Ctx.Allocate(String.size(), alignof(char *));
114 memcpy(mem, String.data(), String.size());
115 return StringRef(static_cast<char *>(mem), String.size());
116}
117
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 S.Context, Metadata.Version, *Existing, /*IsReplacedByActive*/ true);
152
153 D->getAttrs().erase(Existing);
154 D->addAttr(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(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(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(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>
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>(Next) ||
207 isa<CFReturnsNotRetainedAttr>(Next) ||
208 isa<NSReturnsRetainedAttr>(Next) ||
209 isa<NSReturnsNotRetainedAttr>(Next) ||
210 isa<CFAuditedTransferAttr>(Next);
211 });
212 });
213}
214
216 Sema &S, Decl *D, VersionedInfoMetadata Metadata,
217 std::optional<api_notes::RetainCountConventionKind> Convention) {
218 if (!Convention)
219 return;
220 switch (*Convention) {
222 if (isa<FunctionDecl>(D)) {
224 S, D, /*shouldAddAttribute*/ true, Metadata);
225 } else {
227 S, D, /*shouldAddAttribute*/ false, Metadata);
228 }
229 break;
232 S, D, /*shouldAddAttribute*/ true, Metadata);
233 break;
236 S, D, /*shouldAddAttribute*/ true, Metadata);
237 break;
240 S, D, /*shouldAddAttribute*/ true, Metadata);
241 break;
244 S, D, /*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, true, Metadata, [&] {
255 return new (S.Context)
256 UnavailableAttr(S.Context, getPlaceholderAttrInfo(),
258 });
259 }
260
261 if (Info.UnavailableInSwift) {
262 handleAPINotedAttribute<AvailabilityAttr>(
263 S, D, true, Metadata,
264 [&] {
265 return new (S.Context) AvailabilityAttr(
267 &S.Context.Idents.get("swift"), VersionTuple(), VersionTuple(),
268 VersionTuple(),
269 /*Unavailable=*/true,
271 /*Strict=*/false,
272 /*Replacement=*/StringRef(),
273 /*Priority=*/Sema::AP_Explicit,
274 /*Environment=*/nullptr,
275 /*OrigAnyAppleOSVersion=*/VersionTuple());
276 },
277 [](const Decl *D) {
278 return llvm::find_if(D->attrs(), [](const Attr *next) -> bool {
279 if (const auto *AA = dyn_cast<AvailabilityAttr>(next))
280 if (const auto *II = AA->getPlatform())
281 return II->isStr("swift");
282 return false;
283 });
284 });
285 }
286
287 // swift_private
288 if (auto SwiftPrivate = Info.isSwiftPrivate()) {
289 handleAPINotedAttribute<SwiftPrivateAttr>(
290 S, D, *SwiftPrivate, Metadata, [&] {
291 return new (S.Context)
292 SwiftPrivateAttr(S.Context, getPlaceholderAttrInfo());
293 });
294 }
295
296 // swift_safety
297 if (auto SafetyKind = Info.getSwiftSafety()) {
299 handleAPINotedAttribute<SwiftAttrAttr>(
300 S, D, Addition, Metadata,
301 [&] {
302 return SwiftAttrAttr::Create(
304 ? "safe"
305 : "unsafe");
306 },
307 [](const Decl *D) {
308 return llvm::find_if(D->attrs(), [](const Attr *attr) {
309 if (const auto *swiftAttr = dyn_cast<SwiftAttrAttr>(attr)) {
310 if (swiftAttr->getAttribute() == "safe" ||
311 swiftAttr->getAttribute() == "unsafe")
312 return true;
313 }
314 return false;
315 });
316 });
317 }
318
319 // swift_name
320 if (!Info.SwiftName.empty()) {
321 handleAPINotedAttribute<SwiftNameAttr>(
322 S, D, true, Metadata, [&]() -> SwiftNameAttr * {
323 AttributeFactory AF{};
324 AttributePool AP{AF};
325 auto &C = S.getASTContext();
326 ParsedAttr *SNA = AP.create(
327 &C.Idents.get("swift_name"), SourceRange(), AttributeScopeInfo(),
328 nullptr, nullptr, nullptr, ParsedAttr::Form::GNU());
329
330 if (!S.Swift().DiagnoseName(D, Info.SwiftName, D->getLocation(), *SNA,
331 /*IsAsync=*/false))
332 return nullptr;
333
334 return new (S.Context)
335 SwiftNameAttr(S.Context, getPlaceholderAttrInfo(),
336 ASTAllocateString(S.Context, Info.SwiftName));
337 });
338 }
339}
340
341static void ProcessAPINotes(Sema &S, Decl *D,
342 const api_notes::CommonTypeInfo &Info,
343 VersionedInfoMetadata Metadata) {
344 // swift_bridge
345 if (auto SwiftBridge = Info.getSwiftBridge()) {
346 handleAPINotedAttribute<SwiftBridgeAttr>(
347 S, D, !SwiftBridge->empty(), Metadata, [&] {
348 return new (S.Context)
349 SwiftBridgeAttr(S.Context, getPlaceholderAttrInfo(),
350 ASTAllocateString(S.Context, *SwiftBridge));
351 });
352 }
353
354 // ns_error_domain
355 if (auto NSErrorDomain = Info.getNSErrorDomain()) {
356 handleAPINotedAttribute<NSErrorDomainAttr>(
357 S, D, !NSErrorDomain->empty(), Metadata, [&] {
358 return new (S.Context)
359 NSErrorDomainAttr(S.Context, getPlaceholderAttrInfo(),
360 &S.Context.Idents.get(*NSErrorDomain));
361 });
362 }
363
364 if (auto ConformsTo = Info.getSwiftConformance())
365 D->addAttr(
366 SwiftAttrAttr::Create(S.Context, "conforms_to:" + ConformsTo.value()));
367
368 ProcessAPINotes(S, D, static_cast<const api_notes::CommonEntityInfo &>(Info),
369 Metadata);
370}
371
372/// Check that the replacement type provided by API notes is reasonable.
373///
374/// This is a very weak form of ABI check.
376 QualType OrigType,
377 QualType ReplacementType) {
378 if (S.Context.getTypeSize(OrigType) !=
379 S.Context.getTypeSize(ReplacementType)) {
380 S.Diag(Loc, diag::err_incompatible_replacement_type)
381 << ReplacementType << OrigType;
382 return true;
383 }
384
385 return false;
386}
387
388void Sema::ApplyAPINotesType(Decl *D, StringRef TypeString) {
389 if (!TypeString.empty() && ParseTypeFromStringCallback) {
390 auto ParsedType = ParseTypeFromStringCallback(TypeString, "<API Notes>",
391 D->getLocation());
392 if (ParsedType.isUsable()) {
394 auto TypeInfo = Context.getTrivialTypeSourceInfo(Type, D->getLocation());
395 if (auto Var = dyn_cast<VarDecl>(D)) {
396 // Make adjustments to parameter types.
397 if (isa<ParmVarDecl>(Var)) {
399 Type, D->getLocation(), TypeInfo);
400 Type = Context.getAdjustedParameterType(Type);
401 }
402
403 if (!checkAPINotesReplacementType(*this, Var->getLocation(),
404 Var->getType(), Type)) {
405 Var->setType(Type);
406 Var->setTypeSourceInfo(TypeInfo);
407 }
408 } else if (auto property = dyn_cast<ObjCPropertyDecl>(D)) {
409 if (!checkAPINotesReplacementType(*this, property->getLocation(),
410 property->getType(), Type)) {
411 property->setType(Type, TypeInfo);
412 }
413 } else if (auto field = dyn_cast<FieldDecl>(D)) {
414 if (!checkAPINotesReplacementType(*this, field->getLocation(),
415 field->getType(), Type)) {
416 field->setType(Type);
417 field->setTypeSourceInfo(TypeInfo);
418 }
419 } else {
420 llvm_unreachable("API notes allowed a type on an unknown declaration");
421 }
422 }
423 }
424}
425
427 auto GetModified =
428 [&](class Decl *D, QualType QT,
429 NullabilityKind Nullability) -> std::optional<QualType> {
430 QualType Original = QT;
433 /*OverrideExisting=*/true);
434 return (QT.getTypePtr() != Original.getTypePtr()) ? std::optional(QT)
435 : std::nullopt;
436 };
437
438 if (auto Function = dyn_cast<FunctionDecl>(D)) {
439 if (auto Modified =
440 GetModified(D, Function->getReturnType(), Nullability)) {
441 const FunctionType *FnType = Function->getType()->castAs<FunctionType>();
442 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(FnType))
443 Function->setType(Context.getFunctionType(
444 *Modified, proto->getParamTypes(), proto->getExtProtoInfo()));
445 else
446 Function->setType(
447 Context.getFunctionNoProtoType(*Modified, FnType->getExtInfo()));
448 }
449 } else if (auto Method = dyn_cast<ObjCMethodDecl>(D)) {
450 if (auto Modified = GetModified(D, Method->getReturnType(), Nullability)) {
451 Method->setReturnType(*Modified);
452
453 // Make it a context-sensitive keyword if we can.
454 if (!isIndirectPointerType(*Modified))
455 Method->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
456 Method->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
457 }
458 } else if (auto Value = dyn_cast<ValueDecl>(D)) {
459 if (auto Modified = GetModified(D, Value->getType(), Nullability)) {
460 Value->setType(*Modified);
461
462 // Make it a context-sensitive keyword if we can.
463 if (auto Parm = dyn_cast<ParmVarDecl>(D)) {
464 if (Parm->isObjCMethodParameter() && !isIndirectPointerType(*Modified))
465 Parm->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
466 Parm->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
467 }
468 }
469 } else if (auto Property = dyn_cast<ObjCPropertyDecl>(D)) {
470 if (auto Modified = GetModified(D, Property->getType(), Nullability)) {
471 Property->setType(*Modified, Property->getTypeSourceInfo());
472
473 // Make it a property attribute if we can.
474 if (!isIndirectPointerType(*Modified))
475 Property->setPropertyAttributes(
477 }
478 }
479}
480
481/// Process API notes for a variable or property.
482static void ProcessAPINotes(Sema &S, Decl *D,
483 const api_notes::VariableInfo &Info,
484 VersionedInfoMetadata Metadata) {
485 // Type override.
486 applyAPINotesType(S, D, Info.getType(), Metadata);
487
488 // Nullability.
489 if (auto Nullability = Info.getNullability())
490 applyNullability(S, D, *Nullability, Metadata);
491
492 // Handle common entity information.
493 ProcessAPINotes(S, D, static_cast<const api_notes::CommonEntityInfo &>(Info),
494 Metadata);
495}
496
497/// Process API notes for a parameter.
499 const api_notes::ParamInfo &Info,
500 VersionedInfoMetadata Metadata) {
501 // noescape
502 if (auto NoEscape = Info.isNoEscape())
503 handleAPINotedAttribute<NoEscapeAttr>(S, D, *NoEscape, Metadata, [&] {
504 return new (S.Context) NoEscapeAttr(S.Context, getPlaceholderAttrInfo());
505 });
506
507 if (auto Lifetimebound = Info.isLifetimebound())
508 handleAPINotedAttribute<LifetimeBoundAttr>(
509 S, D, *Lifetimebound, Metadata, [&] {
510 return new (S.Context)
511 LifetimeBoundAttr(S.Context, getPlaceholderAttrInfo());
512 });
513
514 // Retain count convention
517
518 // Handle common entity information.
519 ProcessAPINotes(S, D, static_cast<const api_notes::VariableInfo &>(Info),
520 Metadata);
521}
522
523/// Process API notes for a global variable.
524static void ProcessAPINotes(Sema &S, VarDecl *D,
526 VersionedInfoMetadata metadata) {
527 // Handle common entity information.
528 ProcessAPINotes(S, D, static_cast<const api_notes::VariableInfo &>(Info),
529 metadata);
530}
531
532/// Process API notes for a C field.
533static void ProcessAPINotes(Sema &S, FieldDecl *D,
534 const api_notes::FieldInfo &Info,
535 VersionedInfoMetadata metadata) {
536 // Handle common entity information.
537 ProcessAPINotes(S, D, static_cast<const api_notes::VariableInfo &>(Info),
538 metadata);
539}
540
541/// Process API notes for an Objective-C property.
543 const api_notes::ObjCPropertyInfo &Info,
544 VersionedInfoMetadata Metadata) {
545 // Handle common entity information.
546 ProcessAPINotes(S, D, static_cast<const api_notes::VariableInfo &>(Info),
547 Metadata);
548
549 if (auto AsAccessors = Info.getSwiftImportAsAccessors()) {
550 handleAPINotedAttribute<SwiftImportPropertyAsAccessorsAttr>(
551 S, D, *AsAccessors, Metadata, [&] {
552 return new (S.Context) SwiftImportPropertyAsAccessorsAttr(
554 });
555 }
556}
557
558namespace {
559typedef llvm::PointerUnion<FunctionDecl *, ObjCMethodDecl *> FunctionOrMethod;
560}
561
562/// Process API notes for a function or method.
563static void ProcessAPINotes(Sema &S, FunctionOrMethod AnyFunc,
564 const api_notes::FunctionInfo &Info,
565 VersionedInfoMetadata Metadata) {
566 // Find the declaration itself.
567 FunctionDecl *FD = dyn_cast<FunctionDecl *>(AnyFunc);
568 Decl *D = FD;
569 ObjCMethodDecl *MD = nullptr;
570 if (!D) {
571 MD = cast<ObjCMethodDecl *>(AnyFunc);
572 D = MD;
573 }
574
575 assert((FD || MD) && "Expecting Function or ObjCMethod");
576
577 // Nullability of return type.
578 if (Info.NullabilityAudited)
579 applyNullability(S, D, Info.getReturnTypeInfo(), Metadata);
580
581 // Parameters.
582 unsigned NumParams = FD ? FD->getNumParams() : MD->param_size();
583
584 bool AnyTypeChanged = false;
585 for (unsigned I = 0; I != NumParams; ++I) {
586 ParmVarDecl *Param = FD ? FD->getParamDecl(I) : MD->param_begin()[I];
587 QualType ParamTypeBefore = Param->getType();
588
589 if (I < Info.Params.size())
590 ProcessAPINotes(S, Param, Info.Params[I], Metadata);
591
592 // Nullability.
593 if (Info.NullabilityAudited)
594 applyNullability(S, Param, Info.getParamTypeInfo(I), Metadata);
595
596 if (ParamTypeBefore.getAsOpaquePtr() != Param->getType().getAsOpaquePtr())
597 AnyTypeChanged = true;
598 }
599
600 // returns_(un)retained
601 if (!Info.SwiftReturnOwnership.empty())
602 D->addAttr(SwiftAttrAttr::Create(S.Context,
603 "returns_" + Info.SwiftReturnOwnership));
604
605 // Result type override.
606 QualType OverriddenResultType;
607 if (Metadata.IsActive && !Info.ResultType.empty() &&
610 Info.ResultType, "<API Notes>", D->getLocation());
611 if (ParsedType.isUsable()) {
612 QualType ResultType = Sema::GetTypeFromParser(ParsedType.get());
613
614 if (MD) {
616 MD->getReturnType(), ResultType)) {
617 auto ResultTypeInfo =
618 S.Context.getTrivialTypeSourceInfo(ResultType, D->getLocation());
619 MD->setReturnType(ResultType);
620 MD->setReturnTypeSourceInfo(ResultTypeInfo);
621 }
623 S, FD->getLocation(), FD->getReturnType(), ResultType)) {
624 OverriddenResultType = ResultType;
625 AnyTypeChanged = true;
626 }
627 }
628 }
629
630 // If the result type or any of the parameter types changed for a function
631 // declaration, we have to rebuild the type.
632 if (FD && AnyTypeChanged) {
633 if (const auto *fnProtoType = FD->getType()->getAs<FunctionProtoType>()) {
634 if (OverriddenResultType.isNull())
635 OverriddenResultType = fnProtoType->getReturnType();
636
637 SmallVector<QualType, 4> ParamTypes;
638 for (auto Param : FD->parameters())
639 ParamTypes.push_back(Param->getType());
640
641 FD->setType(S.Context.getFunctionType(OverriddenResultType, ParamTypes,
642 fnProtoType->getExtProtoInfo()));
643 } else if (!OverriddenResultType.isNull()) {
644 const auto *FnNoProtoType = FD->getType()->castAs<FunctionNoProtoType>();
646 OverriddenResultType, FnNoProtoType->getExtInfo()));
647 }
648 }
649
650 // Retain count convention
653
654 // Handle common entity information.
655 ProcessAPINotes(S, D, static_cast<const api_notes::CommonEntityInfo &>(Info),
656 Metadata);
657}
658
659/// Process API notes for a C++ method.
660static void ProcessAPINotes(Sema &S, CXXMethodDecl *Method,
661 const api_notes::CXXMethodInfo &Info,
662 VersionedInfoMetadata Metadata) {
663 if (Info.This && Info.This->isLifetimebound() &&
665 auto MethodType = Method->getType();
666 auto *attr = ::new (S.Context)
667 LifetimeBoundAttr(S.Context, getPlaceholderAttrInfo());
668 QualType AttributedType =
669 S.Context.getAttributedType(attr, MethodType, MethodType);
670 TypeLocBuilder TLB;
671 TLB.pushFullCopy(Method->getTypeSourceInfo()->getTypeLoc());
672 AttributedTypeLoc TyLoc = TLB.push<AttributedTypeLoc>(AttributedType);
673 TyLoc.setAttr(attr);
674 Method->setType(AttributedType);
675 Method->setTypeSourceInfo(TLB.getTypeSourceInfo(S.Context, AttributedType));
676 }
677
678 ProcessAPINotes(S, (FunctionOrMethod)Method, Info, Metadata);
679}
680
681/// Process API notes for a global function.
684 VersionedInfoMetadata Metadata) {
685 // Handle common function information.
686 ProcessAPINotes(S, FunctionOrMethod(D),
687 static_cast<const api_notes::FunctionInfo &>(Info), Metadata);
688}
689
690/// Process API notes for an enumerator.
692 const api_notes::EnumConstantInfo &Info,
693 VersionedInfoMetadata Metadata) {
694 // Handle common information.
695 ProcessAPINotes(S, D, static_cast<const api_notes::CommonEntityInfo &>(Info),
696 Metadata);
697}
698
699/// Process API notes for an Objective-C method.
701 const api_notes::ObjCMethodInfo &Info,
702 VersionedInfoMetadata Metadata) {
703 // Designated initializers.
704 if (Info.DesignatedInit) {
705 handleAPINotedAttribute<ObjCDesignatedInitializerAttr>(
706 S, D, true, Metadata, [&] {
707 if (ObjCInterfaceDecl *IFace = D->getClassInterface())
708 IFace->setHasDesignatedInitializers();
709
710 return new (S.Context) ObjCDesignatedInitializerAttr(
712 });
713 }
714
715 // Handle common function information.
716 ProcessAPINotes(S, FunctionOrMethod(D),
717 static_cast<const api_notes::FunctionInfo &>(Info), Metadata);
718}
719
720/// Process API notes for a tag.
721static void ProcessAPINotes(Sema &S, TagDecl *D, const api_notes::TagInfo &Info,
722 VersionedInfoMetadata Metadata) {
723 if (auto ImportAs = Info.SwiftImportAs)
724 D->addAttr(SwiftAttrAttr::Create(S.Context, "import_" + ImportAs.value()));
725
726 if (auto RetainOp = Info.SwiftRetainOp)
727 D->addAttr(SwiftAttrAttr::Create(S.Context, "retain:" + RetainOp.value()));
728
729 if (auto ReleaseOp = Info.SwiftReleaseOp)
730 D->addAttr(
731 SwiftAttrAttr::Create(S.Context, "release:" + ReleaseOp.value()));
732 if (auto DestroyOp = Info.SwiftDestroyOp)
733 D->addAttr(
734 SwiftAttrAttr::Create(S.Context, "destroy:" + DestroyOp.value()));
735 if (auto DefaultOwnership = Info.SwiftDefaultOwnership)
736 D->addAttr(SwiftAttrAttr::Create(
737 S.Context, "returned_as_" + DefaultOwnership.value() + "_by_default"));
738
739 if (auto Copyable = Info.isSwiftCopyable()) {
740 if (!*Copyable)
741 D->addAttr(SwiftAttrAttr::Create(S.Context, "~Copyable"));
742 }
743
744 if (auto Escapable = Info.isSwiftEscapable()) {
745 D->addAttr(SwiftAttrAttr::Create(S.Context,
746 *Escapable ? "Escapable" : "~Escapable"));
747 }
748
749 if (auto Extensibility = Info.EnumExtensibility) {
751 bool ShouldAddAttribute = (*Extensibility != EnumExtensibilityKind::None);
752 handleAPINotedAttribute<EnumExtensibilityAttr>(
753 S, D, ShouldAddAttribute, Metadata, [&] {
754 EnumExtensibilityAttr::Kind kind;
755 switch (*Extensibility) {
756 case EnumExtensibilityKind::None:
757 llvm_unreachable("remove only");
758 case EnumExtensibilityKind::Open:
759 kind = EnumExtensibilityAttr::Open;
760 break;
761 case EnumExtensibilityKind::Closed:
762 kind = EnumExtensibilityAttr::Closed;
763 break;
764 }
765 return new (S.Context)
766 EnumExtensibilityAttr(S.Context, getPlaceholderAttrInfo(), kind);
767 });
768 }
769
770 if (auto FlagEnum = Info.isFlagEnum()) {
771 handleAPINotedAttribute<FlagEnumAttr>(S, D, *FlagEnum, Metadata, [&] {
772 return new (S.Context) FlagEnumAttr(S.Context, getPlaceholderAttrInfo());
773 });
774 }
775
776 // Handle common type information.
777 ProcessAPINotes(S, D, static_cast<const api_notes::CommonTypeInfo &>(Info),
778 Metadata);
779}
780
781/// Process API notes for a typedef.
783 const api_notes::TypedefInfo &Info,
784 VersionedInfoMetadata Metadata) {
785 // swift_wrapper
786 using SwiftWrapperKind = api_notes::SwiftNewTypeKind;
787
788 if (auto SwiftWrapper = Info.SwiftWrapper) {
789 handleAPINotedAttribute<SwiftNewTypeAttr>(
790 S, D, *SwiftWrapper != SwiftWrapperKind::None, Metadata, [&] {
791 SwiftNewTypeAttr::NewtypeKind Kind;
792 switch (*SwiftWrapper) {
793 case SwiftWrapperKind::None:
794 llvm_unreachable("Shouldn't build an attribute");
795
796 case SwiftWrapperKind::Struct:
797 Kind = SwiftNewTypeAttr::NK_Struct;
798 break;
799
800 case SwiftWrapperKind::Enum:
801 Kind = SwiftNewTypeAttr::NK_Enum;
802 break;
803 }
804 AttributeCommonInfo SyntaxInfo{
805 SourceRange(),
806 AttributeCommonInfo::AT_SwiftNewType,
807 {AttributeCommonInfo::AS_GNU, SwiftNewTypeAttr::GNU_swift_wrapper,
808 /*IsAlignas*/ false, /*IsRegularKeywordAttribute*/ false}};
809 return new (S.Context) SwiftNewTypeAttr(S.Context, SyntaxInfo, Kind);
810 });
811 }
812
813 // Handle common type information.
814 ProcessAPINotes(S, D, static_cast<const api_notes::CommonTypeInfo &>(Info),
815 Metadata);
816}
817
818/// Process API notes for an Objective-C class or protocol.
820 const api_notes::ContextInfo &Info,
821 VersionedInfoMetadata Metadata) {
822 // Handle common type information.
823 ProcessAPINotes(S, D, static_cast<const api_notes::CommonTypeInfo &>(Info),
824 Metadata);
825}
826
827/// Process API notes for an Objective-C class.
829 const api_notes::ContextInfo &Info,
830 VersionedInfoMetadata Metadata) {
831 if (auto AsNonGeneric = Info.getSwiftImportAsNonGeneric()) {
832 handleAPINotedAttribute<SwiftImportAsNonGenericAttr>(
833 S, D, *AsNonGeneric, Metadata, [&] {
834 return new (S.Context)
835 SwiftImportAsNonGenericAttr(S.Context, getPlaceholderAttrInfo());
836 });
837 }
838
839 if (auto ObjcMembers = Info.getSwiftObjCMembers()) {
840 handleAPINotedAttribute<SwiftObjCMembersAttr>(
841 S, D, *ObjcMembers, Metadata, [&] {
842 return new (S.Context)
843 SwiftObjCMembersAttr(S.Context, getPlaceholderAttrInfo());
844 });
845 }
846
847 // Handle information common to Objective-C classes and protocols.
848 ProcessAPINotes(S, static_cast<clang::ObjCContainerDecl *>(D), Info,
849 Metadata);
850}
851
852/// If we're applying API notes with an active, non-default version, and the
853/// versioned API notes have a SwiftName but the declaration normally wouldn't
854/// have one, add a removal attribute to make it clear that the new SwiftName
855/// attribute only applies to the active version of \p D, not to all versions.
856///
857/// This must be run \em before processing API notes for \p D, because otherwise
858/// any existing SwiftName attribute will have been packaged up in a
859/// SwiftVersionedAdditionAttr.
860template <typename SpecificInfo>
862 Sema &S, Decl *D,
864 if (D->hasAttr<SwiftNameAttr>())
865 return;
866 if (!Info.getSelected())
867 return;
868
869 // Is the active slice versioned, and does it set a Swift name?
870 VersionTuple SelectedVersion;
871 SpecificInfo SelectedInfoSlice;
872 std::tie(SelectedVersion, SelectedInfoSlice) = Info[*Info.getSelected()];
873 if (SelectedVersion.empty())
874 return;
875 if (SelectedInfoSlice.SwiftName.empty())
876 return;
877
878 // Does the unversioned slice /not/ set a Swift name?
879 for (const auto &VersionAndInfoSlice : Info) {
880 if (!VersionAndInfoSlice.first.empty())
881 continue;
882 if (!VersionAndInfoSlice.second.SwiftName.empty())
883 return;
884 }
885
886 // Then explicitly call that out with a removal attribute.
887 VersionedInfoMetadata DummyFutureMetadata(
888 SelectedVersion, IsActive_t::Inactive, IsSubstitution_t::Replacement);
889 handleAPINotedAttribute<SwiftNameAttr>(
890 S, D, /*add*/ false, DummyFutureMetadata, []() -> SwiftNameAttr * {
891 llvm_unreachable("should not try to add an attribute here");
892 });
893}
894
895/// Processes all versions of versioned API notes.
896///
897/// Just dispatches to the various ProcessAPINotes functions in this file.
898template <typename SpecificDecl, typename SpecificInfo>
900 Sema &S, SpecificDecl *D,
902
905
906 unsigned Selected = Info.getSelected().value_or(Info.size());
907
908 VersionTuple Version;
909 SpecificInfo InfoSlice;
910 for (unsigned i = 0, e = Info.size(); i != e; ++i) {
911 std::tie(Version, InfoSlice) = Info[i];
912 auto Active = (i == Selected) ? IsActive_t::Active : IsActive_t::Inactive;
913 auto Replacement = IsSubstitution_t::Original;
914
915 // When collecting all APINotes as version-independent,
916 // capture all as inactive and defer to the client to select the
917 // right one.
919 Active = IsActive_t::Inactive;
920 Replacement = IsSubstitution_t::Original;
921 } else if (Active == IsActive_t::Inactive && Version.empty()) {
922 Replacement = IsSubstitution_t::Replacement;
923 Version = Info[Selected].first;
924 }
925
926 ProcessAPINotes(S, D, InfoSlice,
927 VersionedInfoMetadata(Version, Active, Replacement));
928 }
929}
930
931static std::optional<api_notes::Context>
933 if (auto NamespaceContext = dyn_cast<NamespaceDecl>(DC)) {
934 for (auto Reader : APINotes.findAPINotes(NamespaceContext->getLocation())) {
935 // Retrieve the context ID for the parent namespace of the decl.
936 std::stack<NamespaceDecl *> NamespaceStack;
937 {
938 for (auto CurrentNamespace = NamespaceContext; CurrentNamespace;
939 CurrentNamespace =
940 dyn_cast<NamespaceDecl>(CurrentNamespace->getParent())) {
941 if (!CurrentNamespace->isInlineNamespace())
942 NamespaceStack.push(CurrentNamespace);
943 }
944 }
945 std::optional<api_notes::ContextID> NamespaceID;
946 while (!NamespaceStack.empty()) {
947 auto CurrentNamespace = NamespaceStack.top();
948 NamespaceStack.pop();
949 NamespaceID =
950 Reader->lookupNamespaceID(CurrentNamespace->getName(), NamespaceID);
951 if (!NamespaceID)
952 return std::nullopt;
953 }
954 if (NamespaceID)
955 return api_notes::Context(*NamespaceID,
957 }
958 }
959 return std::nullopt;
960}
961
962static std::optional<api_notes::Context>
964 assert(DC && "tag context must not be null");
965 for (auto Reader : APINotes.findAPINotes(DC->getLocation())) {
966 // Retrieve the context ID for the parent tag of the decl.
967 std::stack<TagDecl *> TagStack;
968 {
969 for (auto CurrentTag = DC; CurrentTag;
970 CurrentTag = dyn_cast<TagDecl>(CurrentTag->getParent()))
971 TagStack.push(CurrentTag);
972 }
973 assert(!TagStack.empty());
974 std::optional<api_notes::Context> Ctx =
975 UnwindNamespaceContext(TagStack.top()->getDeclContext(), APINotes);
976 while (!TagStack.empty()) {
977 auto CurrentTag = TagStack.top();
978 TagStack.pop();
979 auto CtxID = Reader->lookupTagID(CurrentTag->getName(), Ctx);
980 if (!CtxID)
981 return std::nullopt;
983 }
984 return Ctx;
985 }
986 return std::nullopt;
987}
988
989/// Process API notes that are associated with this declaration, mapping them
990/// to attributes as appropriate.
992 if (!D)
993 return;
994
995 auto *DC = D->getDeclContext();
996 // Globals.
997 if (DC->isFileContext() || DC->isNamespace() ||
998 DC->getDeclKind() == Decl::LinkageSpec) {
999 std::optional<api_notes::Context> APINotesContext =
1001 // Global variables.
1002 if (auto VD = dyn_cast<VarDecl>(D)) {
1003 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1004 auto Info =
1005 Reader->lookupGlobalVariable(VD->getName(), APINotesContext);
1006 ProcessVersionedAPINotes(*this, VD, Info);
1007 }
1008
1009 return;
1010 }
1011
1012 // Global functions.
1013 if (auto FD = dyn_cast<FunctionDecl>(D)) {
1014 if (FD->getDeclName().isIdentifier()) {
1015 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1016 auto Info =
1017 Reader->lookupGlobalFunction(FD->getName(), APINotesContext);
1018 ProcessVersionedAPINotes(*this, FD, Info);
1019 }
1020 }
1021
1022 return;
1023 }
1024
1025 // Objective-C classes.
1026 if (auto Class = dyn_cast<ObjCInterfaceDecl>(D)) {
1027 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1028 auto Info = Reader->lookupObjCClassInfo(Class->getName());
1029 ProcessVersionedAPINotes(*this, Class, Info);
1030 }
1031
1032 return;
1033 }
1034
1035 // Objective-C protocols.
1036 if (auto Protocol = dyn_cast<ObjCProtocolDecl>(D)) {
1037 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1038 auto Info = Reader->lookupObjCProtocolInfo(Protocol->getName());
1039 ProcessVersionedAPINotes(*this, Protocol, Info);
1040 }
1041
1042 return;
1043 }
1044
1045 // Tags
1046 if (auto Tag = dyn_cast<TagDecl>(D)) {
1047 // Determine the name of the entity to search for. If this is an
1048 // anonymous tag that gets its linked name from a typedef, look for the
1049 // typedef name. This allows tag-specific information to be added
1050 // to the declaration.
1051 std::string LookupName;
1052 if (auto typedefName = Tag->getTypedefNameForAnonDecl())
1053 LookupName = typedefName->getName().str();
1054 else
1055 LookupName = Tag->getName().str();
1056
1057 // Use the source location to discern if this Tag is an OPTIONS macro.
1058 // For now we would like to limit this trick of looking up the APINote tag
1059 // using the EnumDecl's QualType in the case where the enum is anonymous.
1060 // This is only being used to support APINotes lookup for C++
1061 // NS/CF_OPTIONS when C++-Interop is enabled.
1062 std::string MacroName =
1063 LookupName.empty() && Tag->getOuterLocStart().isMacroID()
1065 Tag->getOuterLocStart(),
1066 Tag->getASTContext().getSourceManager(), LangOpts)
1067 .str()
1068 : "";
1069
1070 if (LookupName.empty() && isa<clang::EnumDecl>(Tag) &&
1071 (MacroName == "CF_OPTIONS" || MacroName == "NS_OPTIONS" ||
1072 MacroName == "OBJC_OPTIONS" || MacroName == "SWIFT_OPTIONS")) {
1073
1074 clang::QualType T = llvm::cast<clang::EnumDecl>(Tag)->getIntegerType();
1076 T.split(), getASTContext().getPrintingPolicy());
1077 }
1078
1079 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1080 if (auto ParentTag = dyn_cast<TagDecl>(Tag->getDeclContext()))
1081 APINotesContext = UnwindTagContext(ParentTag, APINotes);
1082 auto Info = Reader->lookupTag(LookupName, APINotesContext);
1083 ProcessVersionedAPINotes(*this, Tag, Info);
1084 }
1085
1086 return;
1087 }
1088
1089 // Typedefs
1090 if (auto Typedef = dyn_cast<TypedefNameDecl>(D)) {
1091 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1092 auto Info = Reader->lookupTypedef(Typedef->getName(), APINotesContext);
1093 ProcessVersionedAPINotes(*this, Typedef, Info);
1094 }
1095
1096 return;
1097 }
1098 }
1099
1100 // Enumerators.
1101 if (DC->getRedeclContext()->isFileContext() ||
1102 DC->getRedeclContext()->isExternCContext()) {
1103 if (auto EnumConstant = dyn_cast<EnumConstantDecl>(D)) {
1104 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1105 auto Info = Reader->lookupEnumConstant(EnumConstant->getName());
1106 ProcessVersionedAPINotes(*this, EnumConstant, Info);
1107 }
1108
1109 return;
1110 }
1111 }
1112
1113 if (auto ObjCContainer = dyn_cast<ObjCContainerDecl>(DC)) {
1114 // Location function that looks up an Objective-C context.
1115 auto GetContext = [&](api_notes::APINotesReader *Reader)
1116 -> std::optional<api_notes::ContextID> {
1117 if (auto Protocol = dyn_cast<ObjCProtocolDecl>(ObjCContainer)) {
1118 if (auto Found = Reader->lookupObjCProtocolID(Protocol->getName()))
1119 return *Found;
1120
1121 return std::nullopt;
1122 }
1123
1124 if (auto Impl = dyn_cast<ObjCCategoryImplDecl>(ObjCContainer)) {
1125 if (auto Cat = Impl->getCategoryDecl())
1126 ObjCContainer = Cat->getClassInterface();
1127 else
1128 return std::nullopt;
1129 }
1130
1131 if (auto Category = dyn_cast<ObjCCategoryDecl>(ObjCContainer)) {
1132 if (Category->getClassInterface())
1133 ObjCContainer = Category->getClassInterface();
1134 else
1135 return std::nullopt;
1136 }
1137
1138 if (auto Impl = dyn_cast<ObjCImplDecl>(ObjCContainer)) {
1139 if (Impl->getClassInterface())
1140 ObjCContainer = Impl->getClassInterface();
1141 else
1142 return std::nullopt;
1143 }
1144
1145 if (auto Class = dyn_cast<ObjCInterfaceDecl>(ObjCContainer)) {
1146 if (auto Found = Reader->lookupObjCClassID(Class->getName()))
1147 return *Found;
1148
1149 return std::nullopt;
1150 }
1151
1152 return std::nullopt;
1153 };
1154
1155 // Objective-C methods.
1156 if (auto Method = dyn_cast<ObjCMethodDecl>(D)) {
1157 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1158 if (auto Context = GetContext(Reader)) {
1159 // Map the selector.
1160 Selector Sel = Method->getSelector();
1161 SmallVector<StringRef, 2> SelPieces;
1162 if (Sel.isUnarySelector()) {
1163 SelPieces.push_back(Sel.getNameForSlot(0));
1164 } else {
1165 for (unsigned i = 0, n = Sel.getNumArgs(); i != n; ++i)
1166 SelPieces.push_back(Sel.getNameForSlot(i));
1167 }
1168
1169 api_notes::ObjCSelectorRef SelectorRef;
1170 SelectorRef.NumArgs = Sel.getNumArgs();
1171 SelectorRef.Identifiers = SelPieces;
1172
1173 auto Info = Reader->lookupObjCMethod(*Context, SelectorRef,
1174 Method->isInstanceMethod());
1175 ProcessVersionedAPINotes(*this, Method, Info);
1176 }
1177 }
1178 }
1179
1180 // Objective-C properties.
1181 if (auto Property = dyn_cast<ObjCPropertyDecl>(D)) {
1182 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1183 if (auto Context = GetContext(Reader)) {
1184 bool isInstanceProperty =
1185 (Property->getPropertyAttributesAsWritten() &
1187 auto Info = Reader->lookupObjCProperty(*Context, Property->getName(),
1188 isInstanceProperty);
1189 ProcessVersionedAPINotes(*this, Property, Info);
1190 }
1191 }
1192
1193 return;
1194 }
1195 }
1196
1197 if (auto TagContext = dyn_cast<TagDecl>(DC)) {
1198 if (auto CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1199 if (!isa<CXXConstructorDecl>(CXXMethod) &&
1200 !isa<CXXDestructorDecl>(CXXMethod) &&
1201 !isa<CXXConversionDecl>(CXXMethod)) {
1202 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1203 if (auto Context = UnwindTagContext(TagContext, APINotes)) {
1204 std::string MethodName;
1205 if (CXXMethod->isOverloadedOperator())
1206 MethodName =
1207 std::string("operator") +
1208 getOperatorSpelling(CXXMethod->getOverloadedOperator());
1209 else
1210 MethodName = CXXMethod->getName();
1211
1212 auto Info = Reader->lookupCXXMethod(Context->id, MethodName);
1213 ProcessVersionedAPINotes(*this, CXXMethod, Info);
1214 }
1215 }
1216 }
1217 }
1218
1219 if (auto Field = dyn_cast<FieldDecl>(D)) {
1220 if (!Field->isUnnamedBitField() && !Field->isAnonymousStructOrUnion()) {
1221 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1222 if (auto Context = UnwindTagContext(TagContext, APINotes)) {
1223 auto Info = Reader->lookupField(Context->id, Field->getName());
1224 ProcessVersionedAPINotes(*this, Field, Info);
1225 }
1226 }
1227 }
1228 }
1229
1230 if (auto Tag = dyn_cast<TagDecl>(D)) {
1231 for (auto Reader : APINotes.findAPINotes(D->getLocation())) {
1232 if (auto Context = UnwindTagContext(TagContext, APINotes)) {
1233 auto Info = Reader->lookupTag(Tag->getName(), Context);
1234 ProcessVersionedAPINotes(*this, Tag, Info);
1235 }
1236 }
1237 }
1238 }
1239}
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
FormatToken * Next
The next token in the unwrapped line.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
static std::optional< api_notes::Context > UnwindNamespaceContext(DeclContext *DC, api_notes::APINotesManager &APINotes)
static void ProcessVersionedAPINotes(Sema &S, SpecificDecl *D, const api_notes::APINotesReader::VersionedInfo< SpecificInfo > Info)
Processes all versions of versioned API notes.
static bool checkAPINotesReplacementType(Sema &S, SourceLocation Loc, QualType OrigType, QualType ReplacementType)
Check that the replacement type provided by API notes is reasonable.
static std::optional< api_notes::Context > UnwindTagContext(TagDecl *DC, api_notes::APINotesManager &APINotes)
static StringRef ASTAllocateString(ASTContext &Ctx, StringRef String)
Copy a string into ASTContext-allocated memory.
static void applyAPINotesType(Sema &S, Decl *decl, StringRef typeString, VersionedInfoMetadata metadata)
static void handleAPINotedRetainCountConvention(Sema &S, Decl *D, VersionedInfoMetadata Metadata, std::optional< api_notes::RetainCountConventionKind > Convention)
static void handleAPINotedRetainCountAttribute(Sema &S, Decl *D, bool ShouldAddAttribute, VersionedInfoMetadata Metadata)
static AttributeCommonInfo getPlaceholderAttrInfo()
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
static void applyNullability(Sema &S, Decl *decl, NullabilityKind nullability, VersionedInfoMetadata metadata)
Apply nullability to the given declaration.
static void maybeAttachUnversionedSwiftName(Sema &S, Decl *D, const api_notes::APINotesReader::VersionedInfo< SpecificInfo > Info)
If we're applying API notes with an active, non-default version, and the versioned API notes have a S...
static bool isIndirectPointerType(QualType Type)
Determine whether this is a multi-level pointer type.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis functions specific to Swift.
Defines the clang::SourceLocation class and associated facilities.
Defines the clang::TypeLoc interface and its subclasses.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
IdentifierTable & Idents
Definition ASTContext.h:798
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
void * Allocate(size_t Size, unsigned Align=8) const
Definition ASTContext.h:872
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Attr - This represents one attribute.
Definition Attr.h:46
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition ParsedAttr.h:622
ParsedAttr * create(IdentifierInfo *attrName, SourceRange attrRange, AttributeScopeInfo scope, ArgsUnion *args, unsigned numArgs, ParsedAttr::Form form, SourceLocation ellipsisLoc=SourceLocation())
Definition ParsedAttr.h:735
Type source information for an attributed type.
Definition TypeLoc.h:1008
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
void addAttr(Attr *A)
attr_iterator attr_end() const
Definition DeclBase.h:542
AttrVec::const_iterator attr_iterator
Definition DeclBase.h:532
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition DeclBase.h:198
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition DeclBase.h:210
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
attr_range attrs() const
Definition DeclBase.h:535
AttrVec & getAttrs()
Definition DeclBase.h:524
bool hasAttr() const
Definition DeclBase.h:577
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3438
Represents a member of a struct/union/class.
Definition Decl.h:3175
Represents a function declaration or definition.
Definition Decl.h:2015
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3827
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition TypeBase.h:4935
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
ExtInfo getExtInfo() const
Definition TypeBase.h:4909
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1074
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:948
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
unsigned param_size() const
Definition DeclObjC.h:347
void setReturnTypeSourceInfo(TypeSourceInfo *TInfo)
Definition DeclObjC.h:344
param_const_iterator param_begin() const
Definition DeclObjC.h:354
void setReturnType(QualType T)
Definition DeclObjC.h:330
QualType getReturnType() const
Definition DeclObjC.h:329
ObjCInterfaceDecl * getClassInterface()
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
Represents a parameter to a function.
Definition Decl.h:1805
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
std::string getAsString() const
void * getAsOpaquePtr() const
Definition TypeBase.h:984
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
unsigned getNumArgs() const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
QualType AdjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo)
bool DiagnoseName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync)
Do a check to make sure Name looks like a legal argument for the swift_name attribute applied to decl...
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
ASTContext & Context
Definition Sema.h:1304
SemaObjC & ObjC()
Definition Sema.h:1514
bool captureSwiftVersionIndependentAPINotes()
Whether APINotes should be gathered for all applicable Swift language versions, without being applied...
Definition Sema.h:1665
ASTContext & getASTContext() const
Definition Sema.h:939
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1208
api_notes::APINotesManager APINotes
Definition Sema.h:1308
const LangOptions & LangOpts
Definition Sema.h:1302
SemaSwift & Swift()
Definition Sema.h:1559
std::function< TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback
Callback to the parser to parse a type expressed as a string.
Definition Sema.h:1357
void ApplyNullability(Decl *D, NullabilityKind Nullability)
Apply the 'Nullability:' annotation to the specified declaration.
bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, NullabilityKind Nullability, SourceLocation DiagLoc, bool AllowArrayTypes, bool OverrideExisting)
Check whether a nullability type specifier can be added to the given type through some means not writ...
@ AP_Explicit
The availability attribute was specified explicitly next to the declaration.
Definition Sema.h:4858
void ApplyAPINotesType(Decl *D, StringRef TypeString)
Apply the 'Type:' annotation to the specified declaration.
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Encodes a location in the source.
A trivial tuple used to represent a source range.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3732
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
The base class of the type hierarchy.
Definition TypeBase.h:1866
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isObjCObjectPointerType() const
Definition TypeBase.h:8847
bool isAnyPointerType() const
Definition TypeBase.h:8676
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3577
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
The API notes manager helps find API notes associated with declarations.
llvm::SmallVector< APINotesReader *, 2 > findAPINotes(SourceLocation Loc)
Find the API notes readers that correspond to the given source location.
Captures the completed versioned information for a particular part of API notes, including both unver...
unsigned size() const
Return the number of versioned results we know about.
std::optional< unsigned > getSelected() const
Retrieve the selected index in the result set.
A class that reads API notes data from a binary file that was written by the APINotesWriter.
Describes API notes data for a C++ method.
Definition Types.h:734
std::optional< ParamInfo > This
Definition Types.h:738
Describes API notes data for any entity.
Definition Types.h:54
unsigned UnavailableInSwift
Whether this entity is marked unavailable in Swift.
Definition Types.h:65
unsigned Unavailable
Whether this entity is marked unavailable.
Definition Types.h:61
std::string UnavailableMsg
Message to use when this entity is unavailable.
Definition Types.h:57
std::optional< SwiftSafetyKind > getSwiftSafety() const
Definition Types.h:100
std::optional< bool > isSwiftPrivate() const
Definition Types.h:90
Describes API notes for types.
Definition Types.h:159
std::optional< std::string > getSwiftConformance() const
Definition Types.h:195
const std::optional< std::string > & getSwiftBridge() const
Definition Types.h:174
const std::optional< std::string > & getNSErrorDomain() const
Definition Types.h:182
Describes API notes data for an Objective-C class or protocol or a C++ namespace.
Definition Types.h:235
std::optional< bool > getSwiftImportAsNonGeneric() const
Definition Types.h:285
std::optional< bool > getSwiftObjCMembers() const
Definition Types.h:295
Describes API notes data for an enumerator.
Definition Types.h:752
Describes API notes data for a C/C++ record field.
Definition Types.h:728
API notes for a function or method.
Definition Types.h:551
std::string SwiftReturnOwnership
Ownership convention for return value.
Definition Types.h:584
std::optional< RetainCountConventionKind > getRetainCountConvention() const
Definition Types.h:631
std::vector< ParamInfo > Params
The function parameters.
Definition Types.h:587
NullabilityKind getReturnTypeInfo() const
Definition Types.h:629
NullabilityKind getParamTypeInfo(unsigned index) const
Definition Types.h:625
std::string ResultType
The result type of this function, as a C type.
Definition Types.h:581
unsigned NullabilityAudited
Whether the signature has been audited with respect to nullability.
Definition Types.h:565
Describes API notes data for a global function.
Definition Types.h:722
Describes API notes data for a global variable.
Definition Types.h:716
Describes API notes data for an Objective-C method.
Definition Types.h:675
unsigned DesignatedInit
Whether this is a designated initializer of its class.
Definition Types.h:679
Describes API notes data for an Objective-C property.
Definition Types.h:399
std::optional< bool > getSwiftImportAsAccessors() const
Definition Types.h:409
Describes a function or method parameter.
Definition Types.h:457
std::optional< bool > isNoEscape() const
Definition Types.h:485
std::optional< bool > isLifetimebound() const
Definition Types.h:493
std::optional< RetainCountConventionKind > getRetainCountConvention() const
Definition Types.h:502
Describes API notes data for a tag.
Definition Types.h:758
std::optional< std::string > SwiftReleaseOp
Definition Types.h:777
std::optional< std::string > SwiftRetainOp
Definition Types.h:776
std::optional< std::string > SwiftImportAs
Definition Types.h:775
std::optional< std::string > SwiftDefaultOwnership
Definition Types.h:779
std::optional< EnumExtensibilityKind > EnumExtensibility
Definition Types.h:781
std::optional< std::string > SwiftDestroyOp
Definition Types.h:778
std::optional< bool > isFlagEnum() const
Definition Types.h:788
std::optional< bool > isSwiftCopyable() const
Definition Types.h:798
std::optional< bool > isSwiftEscapable() const
Definition Types.h:807
Describes API notes data for a typedef.
Definition Types.h:869
std::optional< SwiftNewTypeKind > SwiftWrapper
Definition Types.h:871
API notes for a variable/property.
Definition Types.h:342
std::optional< NullabilityKind > getNullability() const
Definition Types.h:358
const std::string & getType() const
Definition Types.h:369
SwiftNewTypeKind
The kind of a swift_wrapper/swift_newtype.
Definition Types.h:43
EnumExtensibilityKind
The payload for an enum_extensibility attribute.
Definition Types.h:36
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ Property
The type of a property.
Definition TypeBase.h:911
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5967
A temporary reference to an Objective-C selector, suitable for referencing selector data on the stack...
Definition Types.h:928
llvm::ArrayRef< llvm::StringRef > Identifiers
Definition Types.h:930