1//===--- SemaDeclAttr.cpp - Declaration Attribute 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 decl-related attribute processing.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTMutationListener.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/CharInfo.h"
26#include "clang/Basic/Cuda.h"
27#include "clang/Basic/DarwinSDKInfo.h"
28#include "clang/Basic/HLSLRuntime.h"
29#include "clang/Basic/LangOptions.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetBuiltins.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/DelayedDiagnostic.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedAttr.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "clang/Sema/SemaInternal.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/IR/Assumptions.h"
46#include "llvm/MC/MCSectionMachO.h"
47#include "llvm/Support/Error.h"
48#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/raw_ostream.h"
50#include <optional>
51
52using namespace clang;
53using namespace sema;
54
55namespace AttributeLangSupport {
56 enum LANG {
57 C,
58 Cpp,
59 ObjC
60 };
61} // end namespace AttributeLangSupport
62
63//===----------------------------------------------------------------------===//
64// Helper functions
65//===----------------------------------------------------------------------===//
66
67/// isFunctionOrMethod - Return true if the given decl has function
68/// type (function or function-typed variable) or an Objective-C
69/// method.
70static bool isFunctionOrMethod(const Decl *D) {
71 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(Val: D);
72}
73
74/// Return true if the given decl has function type (function or
75/// function-typed variable) or an Objective-C method or a block.
76static bool isFunctionOrMethodOrBlock(const Decl *D) {
77 return isFunctionOrMethod(D) || isa<BlockDecl>(Val: D);
78}
79
80/// Return true if the given decl has a declarator that should have
81/// been processed by Sema::GetTypeForDeclarator.
82static bool hasDeclarator(const Decl *D) {
83 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
84 return isa<DeclaratorDecl>(Val: D) || isa<BlockDecl>(Val: D) || isa<TypedefNameDecl>(Val: D) ||
85 isa<ObjCPropertyDecl>(Val: D);
86}
87
88/// hasFunctionProto - Return true if the given decl has a argument
89/// information. This decl should have already passed
90/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
91static bool hasFunctionProto(const Decl *D) {
92 if (const FunctionType *FnTy = D->getFunctionType())
93 return isa<FunctionProtoType>(Val: FnTy);
94 return isa<ObjCMethodDecl>(Val: D) || isa<BlockDecl>(Val: D);
95}
96
97/// getFunctionOrMethodNumParams - Return number of function or method
98/// parameters. It is an error to call this on a K&R function (use
99/// hasFunctionProto first).
100static unsigned getFunctionOrMethodNumParams(const Decl *D) {
101 if (const FunctionType *FnTy = D->getFunctionType())
102 return cast<FunctionProtoType>(Val: FnTy)->getNumParams();
103 if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
104 return BD->getNumParams();
105 return cast<ObjCMethodDecl>(Val: D)->param_size();
106}
107
108static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
109 unsigned Idx) {
110 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
111 return FD->getParamDecl(i: Idx);
112 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
113 return MD->getParamDecl(Idx);
114 if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
115 return BD->getParamDecl(i: Idx);
116 return nullptr;
117}
118
119static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
120 if (const FunctionType *FnTy = D->getFunctionType())
121 return cast<FunctionProtoType>(Val: FnTy)->getParamType(i: Idx);
122 if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
123 return BD->getParamDecl(i: Idx)->getType();
124
125 return cast<ObjCMethodDecl>(Val: D)->parameters()[Idx]->getType();
126}
127
128static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
129 if (auto *PVD = getFunctionOrMethodParam(D, Idx))
130 return PVD->getSourceRange();
131 return SourceRange();
132}
133
134static QualType getFunctionOrMethodResultType(const Decl *D) {
135 if (const FunctionType *FnTy = D->getFunctionType())
136 return FnTy->getReturnType();
137 return cast<ObjCMethodDecl>(Val: D)->getReturnType();
138}
139
140static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
141 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
142 return FD->getReturnTypeSourceRange();
143 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
144 return MD->getReturnTypeSourceRange();
145 return SourceRange();
146}
147
148static bool isFunctionOrMethodVariadic(const Decl *D) {
149 if (const FunctionType *FnTy = D->getFunctionType())
150 return cast<FunctionProtoType>(Val: FnTy)->isVariadic();
151 if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
152 return BD->isVariadic();
153 return cast<ObjCMethodDecl>(Val: D)->isVariadic();
154}
155
156static bool isInstanceMethod(const Decl *D) {
157 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(Val: D))
158 return MethodDecl->isInstance();
159 return false;
160}
161
162static inline bool isNSStringType(QualType T, ASTContext &Ctx,
163 bool AllowNSAttributedString = false) {
164 const auto *PT = T->getAs<ObjCObjectPointerType>();
165 if (!PT)
166 return false;
167
168 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
169 if (!Cls)
170 return false;
171
172 IdentifierInfo* ClsName = Cls->getIdentifier();
173
174 if (AllowNSAttributedString &&
175 ClsName == &Ctx.Idents.get(Name: "NSAttributedString"))
176 return true;
177 // FIXME: Should we walk the chain of classes?
178 return ClsName == &Ctx.Idents.get(Name: "NSString") ||
179 ClsName == &Ctx.Idents.get(Name: "NSMutableString");
180}
181
182static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
183 const auto *PT = T->getAs<PointerType>();
184 if (!PT)
185 return false;
186
187 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
188 if (!RT)
189 return false;
190
191 const RecordDecl *RD = RT->getDecl();
192 if (RD->getTagKind() != TagTypeKind::Struct)
193 return false;
194
195 return RD->getIdentifier() == &Ctx.Idents.get(Name: "__CFString");
196}
197
198static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
199 // FIXME: Include the type in the argument list.
200 return AL.getNumArgs() + AL.hasParsedType();
201}
202
203/// A helper function to provide Attribute Location for the Attr types
204/// AND the ParsedAttr.
205template <typename AttrInfo>
206static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
207getAttrLoc(const AttrInfo &AL) {
208 return AL.getLocation();
209}
210static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
211
212/// If Expr is a valid integer constant, get the value of the integer
213/// expression and return success or failure. May output an error.
214///
215/// Negative argument is implicitly converted to unsigned, unless
216/// \p StrictlyUnsigned is true.
217template <typename AttrInfo>
218static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
219 uint32_t &Val, unsigned Idx = UINT_MAX,
220 bool StrictlyUnsigned = false) {
221 std::optional<llvm::APSInt> I = llvm::APSInt(32);
222 if (Expr->isTypeDependent() ||
223 !(I = Expr->getIntegerConstantExpr(Ctx: S.Context))) {
224 if (Idx != UINT_MAX)
225 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
226 << &AI << Idx << AANT_ArgumentIntegerConstant
227 << Expr->getSourceRange();
228 else
229 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
230 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
231 return false;
232 }
233
234 if (!I->isIntN(N: 32)) {
235 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
236 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
237 return false;
238 }
239
240 if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
241 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
242 << &AI << /*non-negative*/ 1;
243 return false;
244 }
245
246 Val = (uint32_t)I->getZExtValue();
247 return true;
248}
249
250/// Wrapper around checkUInt32Argument, with an extra check to be sure
251/// that the result will fit into a regular (signed) int. All args have the same
252/// purpose as they do in checkUInt32Argument.
253template <typename AttrInfo>
254static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
255 int &Val, unsigned Idx = UINT_MAX) {
256 uint32_t UVal;
257 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
258 return false;
259
260 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
261 llvm::APSInt I(32); // for toString
262 I = UVal;
263 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
264 << toString(I, 10, false) << 32 << /* Unsigned */ 0;
265 return false;
266 }
267
268 Val = UVal;
269 return true;
270}
271
272/// Diagnose mutually exclusive attributes when present on a given
273/// declaration. Returns true if diagnosed.
274template <typename AttrTy>
275static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
276 if (const auto *A = D->getAttr<AttrTy>()) {
277 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
278 << AL << A
279 << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
280 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
281 return true;
282 }
283 return false;
284}
285
286template <typename AttrTy>
287static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
288 if (const auto *A = D->getAttr<AttrTy>()) {
289 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible)
290 << &AL << A
291 << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
292 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
293 return true;
294 }
295 return false;
296}
297
298/// Check if IdxExpr is a valid parameter index for a function or
299/// instance method D. May output an error.
300///
301/// \returns true if IdxExpr is a valid index.
302template <typename AttrInfo>
303static bool checkFunctionOrMethodParameterIndex(
304 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
305 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
306 assert(isFunctionOrMethodOrBlock(D));
307
308 // In C++ the implicit 'this' function parameter also counts.
309 // Parameters are counted from one.
310 bool HP = hasFunctionProto(D);
311 bool HasImplicitThisParam = isInstanceMethod(D);
312 bool IV = HP && isFunctionOrMethodVariadic(D);
313 unsigned NumParams =
314 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
315
316 std::optional<llvm::APSInt> IdxInt;
317 if (IdxExpr->isTypeDependent() ||
318 !(IdxInt = IdxExpr->getIntegerConstantExpr(Ctx: S.Context))) {
319 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
320 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
321 << IdxExpr->getSourceRange();
322 return false;
323 }
324
325 unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
326 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
327 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
328 << &AI << AttrArgNum << IdxExpr->getSourceRange();
329 return false;
330 }
331 if (HasImplicitThisParam && !CanIndexImplicitThis) {
332 if (IdxSource == 1) {
333 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
334 << &AI << IdxExpr->getSourceRange();
335 return false;
336 }
337 }
338
339 Idx = ParamIdx(IdxSource, D);
340 return true;
341}
342
343/// Check if the argument \p E is a ASCII string literal. If not emit an error
344/// and return false, otherwise set \p Str to the value of the string literal
345/// and return true.
346bool Sema::checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
347 const Expr *E, StringRef &Str,
348 SourceLocation *ArgLocation) {
349 const auto *Literal = dyn_cast<StringLiteral>(Val: E->IgnoreParenCasts());
350 if (ArgLocation)
351 *ArgLocation = E->getBeginLoc();
352
353 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
354 Diag(E->getBeginLoc(), diag::err_attribute_argument_type)
355 << CI << AANT_ArgumentString;
356 return false;
357 }
358
359 Str = Literal->getString();
360 return true;
361}
362
363/// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
364/// If not emit an error and return false. If the argument is an identifier it
365/// will emit an error with a fixit hint and treat it as if it was a string
366/// literal.
367bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
368 StringRef &Str,
369 SourceLocation *ArgLocation) {
370 // Look for identifiers. If we have one emit a hint to fix it to a literal.
371 if (AL.isArgIdent(Arg: ArgNum)) {
372 IdentifierLoc *Loc = AL.getArgAsIdent(Arg: ArgNum);
373 Diag(Loc->Loc, diag::err_attribute_argument_type)
374 << AL << AANT_ArgumentString
375 << FixItHint::CreateInsertion(Loc->Loc, "\"")
376 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
377 Str = Loc->Ident->getName();
378 if (ArgLocation)
379 *ArgLocation = Loc->Loc;
380 return true;
381 }
382
383 // Now check for an actual string literal.
384 Expr *ArgExpr = AL.getArgAsExpr(Arg: ArgNum);
385 const auto *Literal = dyn_cast<StringLiteral>(Val: ArgExpr->IgnoreParenCasts());
386 if (ArgLocation)
387 *ArgLocation = ArgExpr->getBeginLoc();
388
389 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
390 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
391 << AL << AANT_ArgumentString;
392 return false;
393 }
394 Str = Literal->getString();
395 return checkStringLiteralArgumentAttr(CI: AL, E: ArgExpr, Str, ArgLocation);
396}
397
398/// Applies the given attribute to the Decl without performing any
399/// additional semantic checking.
400template <typename AttrType>
401static void handleSimpleAttribute(Sema &S, Decl *D,
402 const AttributeCommonInfo &CI) {
403 D->addAttr(A: ::new (S.Context) AttrType(S.Context, CI));
404}
405
406template <typename... DiagnosticArgs>
407static const Sema::SemaDiagnosticBuilder&
408appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
409 return Bldr;
410}
411
412template <typename T, typename... DiagnosticArgs>
413static const Sema::SemaDiagnosticBuilder&
414appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
415 DiagnosticArgs &&... ExtraArgs) {
416 return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
417 std::forward<DiagnosticArgs>(ExtraArgs)...);
418}
419
420/// Add an attribute @c AttrType to declaration @c D, provided that
421/// @c PassesCheck is true.
422/// Otherwise, emit diagnostic @c DiagID, passing in all parameters
423/// specified in @c ExtraArgs.
424template <typename AttrType, typename... DiagnosticArgs>
425static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
426 const AttributeCommonInfo &CI,
427 bool PassesCheck, unsigned DiagID,
428 DiagnosticArgs &&... ExtraArgs) {
429 if (!PassesCheck) {
430 Sema::SemaDiagnosticBuilder DB = S.Diag(Loc: D->getBeginLoc(), DiagID);
431 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
432 return;
433 }
434 handleSimpleAttribute<AttrType>(S, D, CI);
435}
436
437/// Check if the passed-in expression is of type int or bool.
438static bool isIntOrBool(Expr *Exp) {
439 QualType QT = Exp->getType();
440 return QT->isBooleanType() || QT->isIntegerType();
441}
442
443
444// Check to see if the type is a smart pointer of some kind. We assume
445// it's a smart pointer if it defines both operator-> and operator*.
446static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
447 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
448 OverloadedOperatorKind Op) {
449 DeclContextLookupResult Result =
450 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
451 return !Result.empty();
452 };
453
454 const RecordDecl *Record = RT->getDecl();
455 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
456 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
457 if (foundStarOperator && foundArrowOperator)
458 return true;
459
460 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: Record);
461 if (!CXXRecord)
462 return false;
463
464 for (const auto &BaseSpecifier : CXXRecord->bases()) {
465 if (!foundStarOperator)
466 foundStarOperator = IsOverloadedOperatorPresent(
467 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
468 if (!foundArrowOperator)
469 foundArrowOperator = IsOverloadedOperatorPresent(
470 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
471 }
472
473 if (foundStarOperator && foundArrowOperator)
474 return true;
475
476 return false;
477}
478
479/// Check if passed in Decl is a pointer type.
480/// Note that this function may produce an error message.
481/// \return true if the Decl is a pointer type; false otherwise
482static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
483 const ParsedAttr &AL) {
484 const auto *VD = cast<ValueDecl>(Val: D);
485 QualType QT = VD->getType();
486 if (QT->isAnyPointerType())
487 return true;
488
489 if (const auto *RT = QT->getAs<RecordType>()) {
490 // If it's an incomplete type, it could be a smart pointer; skip it.
491 // (We don't want to force template instantiation if we can avoid it,
492 // since that would alter the order in which templates are instantiated.)
493 if (RT->isIncompleteType())
494 return true;
495
496 if (threadSafetyCheckIsSmartPointer(S, RT))
497 return true;
498 }
499
500 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
501 return false;
502}
503
504/// Checks that the passed in QualType either is of RecordType or points
505/// to RecordType. Returns the relevant RecordType, null if it does not exit.
506static const RecordType *getRecordType(QualType QT) {
507 if (const auto *RT = QT->getAs<RecordType>())
508 return RT;
509
510 // Now check if we point to record type.
511 if (const auto *PT = QT->getAs<PointerType>())
512 return PT->getPointeeType()->getAs<RecordType>();
513
514 return nullptr;
515}
516
517template <typename AttrType>
518static bool checkRecordDeclForAttr(const RecordDecl *RD) {
519 // Check if the record itself has the attribute.
520 if (RD->hasAttr<AttrType>())
521 return true;
522
523 // Else check if any base classes have the attribute.
524 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
525 if (!CRD->forallBases(BaseMatches: [](const CXXRecordDecl *Base) {
526 return !Base->hasAttr<AttrType>();
527 }))
528 return true;
529 }
530 return false;
531}
532
533static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
534 const RecordType *RT = getRecordType(QT: Ty);
535
536 if (!RT)
537 return false;
538
539 // Don't check for the capability if the class hasn't been defined yet.
540 if (RT->isIncompleteType())
541 return true;
542
543 // Allow smart pointers to be used as capability objects.
544 // FIXME -- Check the type that the smart pointer points to.
545 if (threadSafetyCheckIsSmartPointer(S, RT))
546 return true;
547
548 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
549}
550
551static bool checkTypedefTypeForCapability(QualType Ty) {
552 const auto *TD = Ty->getAs<TypedefType>();
553 if (!TD)
554 return false;
555
556 TypedefNameDecl *TN = TD->getDecl();
557 if (!TN)
558 return false;
559
560 return TN->hasAttr<CapabilityAttr>();
561}
562
563static bool typeHasCapability(Sema &S, QualType Ty) {
564 if (checkTypedefTypeForCapability(Ty))
565 return true;
566
567 if (checkRecordTypeForCapability(S, Ty))
568 return true;
569
570 return false;
571}
572
573static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
574 // Capability expressions are simple expressions involving the boolean logic
575 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
576 // a DeclRefExpr is found, its type should be checked to determine whether it
577 // is a capability or not.
578
579 if (const auto *E = dyn_cast<CastExpr>(Val: Ex))
580 return isCapabilityExpr(S, Ex: E->getSubExpr());
581 else if (const auto *E = dyn_cast<ParenExpr>(Val: Ex))
582 return isCapabilityExpr(S, Ex: E->getSubExpr());
583 else if (const auto *E = dyn_cast<UnaryOperator>(Val: Ex)) {
584 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
585 E->getOpcode() == UO_Deref)
586 return isCapabilityExpr(S, Ex: E->getSubExpr());
587 return false;
588 } else if (const auto *E = dyn_cast<BinaryOperator>(Val: Ex)) {
589 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
590 return isCapabilityExpr(S, Ex: E->getLHS()) &&
591 isCapabilityExpr(S, Ex: E->getRHS());
592 return false;
593 }
594
595 return typeHasCapability(S, Ty: Ex->getType());
596}
597
598/// Checks that all attribute arguments, starting from Sidx, resolve to
599/// a capability object.
600/// \param Sidx The attribute argument index to start checking with.
601/// \param ParamIdxOk Whether an argument can be indexing into a function
602/// parameter list.
603static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
604 const ParsedAttr &AL,
605 SmallVectorImpl<Expr *> &Args,
606 unsigned Sidx = 0,
607 bool ParamIdxOk = false) {
608 if (Sidx == AL.getNumArgs()) {
609 // If we don't have any capability arguments, the attribute implicitly
610 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
611 // a non-static method, and that the class is a (scoped) capability.
612 const auto *MD = dyn_cast<const CXXMethodDecl>(Val: D);
613 if (MD && !MD->isStatic()) {
614 const CXXRecordDecl *RD = MD->getParent();
615 // FIXME -- need to check this again on template instantiation
616 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
617 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
618 S.Diag(AL.getLoc(),
619 diag::warn_thread_attribute_not_on_capability_member)
620 << AL << MD->getParent();
621 } else {
622 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
623 << AL;
624 }
625 }
626
627 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
628 Expr *ArgExp = AL.getArgAsExpr(Arg: Idx);
629
630 if (ArgExp->isTypeDependent()) {
631 // FIXME -- need to check this again on template instantiation
632 Args.push_back(Elt: ArgExp);
633 continue;
634 }
635
636 if (const auto *StrLit = dyn_cast<StringLiteral>(Val: ArgExp)) {
637 if (StrLit->getLength() == 0 ||
638 (StrLit->isOrdinary() && StrLit->getString() == StringRef("*"))) {
639 // Pass empty strings to the analyzer without warnings.
640 // Treat "*" as the universal lock.
641 Args.push_back(Elt: ArgExp);
642 continue;
643 }
644
645 // We allow constant strings to be used as a placeholder for expressions
646 // that are not valid C++ syntax, but warn that they are ignored.
647 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
648 Args.push_back(Elt: ArgExp);
649 continue;
650 }
651
652 QualType ArgTy = ArgExp->getType();
653
654 // A pointer to member expression of the form &MyClass::mu is treated
655 // specially -- we need to look at the type of the member.
656 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: ArgExp))
657 if (UOp->getOpcode() == UO_AddrOf)
658 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: UOp->getSubExpr()))
659 if (DRE->getDecl()->isCXXInstanceMember())
660 ArgTy = DRE->getDecl()->getType();
661
662 // First see if we can just cast to record type, or pointer to record type.
663 const RecordType *RT = getRecordType(QT: ArgTy);
664
665 // Now check if we index into a record type function param.
666 if(!RT && ParamIdxOk) {
667 const auto *FD = dyn_cast<FunctionDecl>(Val: D);
668 const auto *IL = dyn_cast<IntegerLiteral>(Val: ArgExp);
669 if(FD && IL) {
670 unsigned int NumParams = FD->getNumParams();
671 llvm::APInt ArgValue = IL->getValue();
672 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
673 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
674 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
675 S.Diag(AL.getLoc(),
676 diag::err_attribute_argument_out_of_bounds_extra_info)
677 << AL << Idx + 1 << NumParams;
678 continue;
679 }
680 ArgTy = FD->getParamDecl(i: ParamIdxFromZero)->getType();
681 }
682 }
683
684 // If the type does not have a capability, see if the components of the
685 // expression have capabilities. This allows for writing C code where the
686 // capability may be on the type, and the expression is a capability
687 // boolean logic expression. Eg) requires_capability(A || B && !C)
688 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
689 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
690 << AL << ArgTy;
691
692 Args.push_back(Elt: ArgExp);
693 }
694}
695
696//===----------------------------------------------------------------------===//
697// Attribute Implementations
698//===----------------------------------------------------------------------===//
699
700static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
701 if (!threadSafetyCheckIsPointer(S, D, AL))
702 return;
703
704 D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
705}
706
707static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
708 Expr *&Arg) {
709 SmallVector<Expr *, 1> Args;
710 // check that all arguments are lockable objects
711 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
712 unsigned Size = Args.size();
713 if (Size != 1)
714 return false;
715
716 Arg = Args[0];
717
718 return true;
719}
720
721static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
722 Expr *Arg = nullptr;
723 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
724 return;
725
726 D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
727}
728
729static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
730 Expr *Arg = nullptr;
731 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
732 return;
733
734 if (!threadSafetyCheckIsPointer(S, D, AL))
735 return;
736
737 D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
738}
739
740static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
741 SmallVectorImpl<Expr *> &Args) {
742 if (!AL.checkAtLeastNumArgs(S, Num: 1))
743 return false;
744
745 // Check that this attribute only applies to lockable types.
746 QualType QT = cast<ValueDecl>(Val: D)->getType();
747 if (!QT->isDependentType() && !typeHasCapability(S, Ty: QT)) {
748 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
749 return false;
750 }
751
752 // Check that all arguments are lockable objects.
753 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
754 if (Args.empty())
755 return false;
756
757 return true;
758}
759
760static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
761 SmallVector<Expr *, 1> Args;
762 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
763 return;
764
765 Expr **StartArg = &Args[0];
766 D->addAttr(::new (S.Context)
767 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
768}
769
770static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
771 SmallVector<Expr *, 1> Args;
772 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
773 return;
774
775 Expr **StartArg = &Args[0];
776 D->addAttr(::new (S.Context)
777 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
778}
779
780static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
781 SmallVectorImpl<Expr *> &Args) {
782 // zero or more arguments ok
783 // check that all arguments are lockable objects
784 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, Sidx: 0, /*ParamIdxOk=*/true);
785
786 return true;
787}
788
789static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
790 SmallVector<Expr *, 1> Args;
791 if (!checkLockFunAttrCommon(S, D, AL, Args))
792 return;
793
794 unsigned Size = Args.size();
795 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
796 D->addAttr(::new (S.Context)
797 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
798}
799
800static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
801 const ParsedAttr &AL) {
802 SmallVector<Expr *, 1> Args;
803 if (!checkLockFunAttrCommon(S, D, AL, Args))
804 return;
805
806 unsigned Size = Args.size();
807 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
808 D->addAttr(::new (S.Context)
809 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
810}
811
812/// Checks to be sure that the given parameter number is in bounds, and
813/// is an integral type. Will emit appropriate diagnostics if this returns
814/// false.
815///
816/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
817template <typename AttrInfo>
818static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
819 unsigned AttrArgNo) {
820 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
821 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
822 ParamIdx Idx;
823 if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
824 Idx))
825 return false;
826
827 QualType ParamTy = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
828 if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
829 SourceLocation SrcLoc = AttrArg->getBeginLoc();
830 S.Diag(SrcLoc, diag::err_attribute_integers_only)
831 << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
832 return false;
833 }
834 return true;
835}
836
837static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
838 if (!AL.checkAtLeastNumArgs(S, Num: 1) || !AL.checkAtMostNumArgs(S, Num: 2))
839 return;
840
841 assert(isFunctionOrMethod(D) && hasFunctionProto(D));
842
843 QualType RetTy = getFunctionOrMethodResultType(D);
844 if (!RetTy->isPointerType()) {
845 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
846 return;
847 }
848
849 const Expr *SizeExpr = AL.getArgAsExpr(Arg: 0);
850 int SizeArgNoVal;
851 // Parameter indices are 1-indexed, hence Index=1
852 if (!checkPositiveIntArgument(S, AI: AL, Expr: SizeExpr, Val&: SizeArgNoVal, /*Idx=*/1))
853 return;
854 if (!checkParamIsIntegerType(S, D, AI: AL, /*AttrArgNo=*/0))
855 return;
856 ParamIdx SizeArgNo(SizeArgNoVal, D);
857
858 ParamIdx NumberArgNo;
859 if (AL.getNumArgs() == 2) {
860 const Expr *NumberExpr = AL.getArgAsExpr(Arg: 1);
861 int Val;
862 // Parameter indices are 1-based, hence Index=2
863 if (!checkPositiveIntArgument(S, AI: AL, Expr: NumberExpr, Val, /*Idx=*/2))
864 return;
865 if (!checkParamIsIntegerType(S, D, AI: AL, /*AttrArgNo=*/1))
866 return;
867 NumberArgNo = ParamIdx(Val, D);
868 }
869
870 D->addAttr(::new (S.Context)
871 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
872}
873
874static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
875 SmallVectorImpl<Expr *> &Args) {
876 if (!AL.checkAtLeastNumArgs(S, Num: 1))
877 return false;
878
879 if (!isIntOrBool(Exp: AL.getArgAsExpr(Arg: 0))) {
880 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
881 << AL << 1 << AANT_ArgumentIntOrBool;
882 return false;
883 }
884
885 // check that all arguments are lockable objects
886 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, Sidx: 1);
887
888 return true;
889}
890
891static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
892 const ParsedAttr &AL) {
893 SmallVector<Expr*, 2> Args;
894 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
895 return;
896
897 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
898 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
899}
900
901static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
902 const ParsedAttr &AL) {
903 SmallVector<Expr*, 2> Args;
904 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
905 return;
906
907 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
908 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
909}
910
911static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
912 // check that the argument is lockable object
913 SmallVector<Expr*, 1> Args;
914 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
915 unsigned Size = Args.size();
916 if (Size == 0)
917 return;
918
919 D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
920}
921
922static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
923 if (!AL.checkAtLeastNumArgs(S, Num: 1))
924 return;
925
926 // check that all arguments are lockable objects
927 SmallVector<Expr*, 1> Args;
928 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
929 unsigned Size = Args.size();
930 if (Size == 0)
931 return;
932 Expr **StartArg = &Args[0];
933
934 D->addAttr(::new (S.Context)
935 LocksExcludedAttr(S.Context, AL, StartArg, Size));
936}
937
938static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
939 Expr *&Cond, StringRef &Msg) {
940 Cond = AL.getArgAsExpr(Arg: 0);
941 if (!Cond->isTypeDependent()) {
942 ExprResult Converted = S.PerformContextuallyConvertToBool(From: Cond);
943 if (Converted.isInvalid())
944 return false;
945 Cond = Converted.get();
946 }
947
948 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 1, Str&: Msg))
949 return false;
950
951 if (Msg.empty())
952 Msg = "<no message provided>";
953
954 SmallVector<PartialDiagnosticAt, 8> Diags;
955 if (isa<FunctionDecl>(Val: D) && !Cond->isValueDependent() &&
956 !Expr::isPotentialConstantExprUnevaluated(E: Cond, FD: cast<FunctionDecl>(Val: D),
957 Diags)) {
958 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
959 for (const PartialDiagnosticAt &PDiag : Diags)
960 S.Diag(Loc: PDiag.first, PD: PDiag.second);
961 return false;
962 }
963 return true;
964}
965
966static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
967 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
968
969 Expr *Cond;
970 StringRef Msg;
971 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
972 D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
973}
974
975static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
976 StringRef NewUserDiagnostic;
977 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: NewUserDiagnostic))
978 return;
979 if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
980 D->addAttr(EA);
981}
982
983namespace {
984/// Determines if a given Expr references any of the given function's
985/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
986class ArgumentDependenceChecker
987 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
988#ifndef NDEBUG
989 const CXXRecordDecl *ClassType;
990#endif
991 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
992 bool Result;
993
994public:
995 ArgumentDependenceChecker(const FunctionDecl *FD) {
996#ifndef NDEBUG
997 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
998 ClassType = MD->getParent();
999 else
1000 ClassType = nullptr;
1001#endif
1002 Parms.insert(I: FD->param_begin(), E: FD->param_end());
1003 }
1004
1005 bool referencesArgs(Expr *E) {
1006 Result = false;
1007 TraverseStmt(E);
1008 return Result;
1009 }
1010
1011 bool VisitCXXThisExpr(CXXThisExpr *E) {
1012 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1013 "`this` doesn't refer to the enclosing class?");
1014 Result = true;
1015 return false;
1016 }
1017
1018 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1019 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl()))
1020 if (Parms.count(Ptr: PVD)) {
1021 Result = true;
1022 return false;
1023 }
1024 return true;
1025 }
1026};
1027}
1028
1029static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl *D,
1030 const ParsedAttr &AL) {
1031 const auto *DeclFD = cast<FunctionDecl>(Val: D);
1032
1033 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(Val: DeclFD))
1034 if (!MethodDecl->isStatic()) {
1035 S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
1036 return;
1037 }
1038
1039 auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
1040 SourceLocation Loc = [&]() {
1041 auto Union = AL.getArg(Arg: Index - 1);
1042 if (Union.is<Expr *>())
1043 return Union.get<Expr *>()->getBeginLoc();
1044 return Union.get<IdentifierLoc *>()->Loc;
1045 }();
1046
1047 S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
1048 };
1049
1050 FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
1051 if (!AL.isArgExpr(Arg: 0))
1052 return nullptr;
1053 auto *F = dyn_cast_if_present<DeclRefExpr>(Val: AL.getArgAsExpr(Arg: 0));
1054 if (!F)
1055 return nullptr;
1056 return dyn_cast_if_present<FunctionDecl>(Val: F->getFoundDecl());
1057 }();
1058
1059 if (!AttrFD || !AttrFD->getBuiltinID(ConsiderWrapperFunctions: true)) {
1060 DiagnoseType(1, AANT_ArgumentBuiltinFunction);
1061 return;
1062 }
1063
1064 if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
1065 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
1066 << AL << AttrFD << AttrFD->getNumParams();
1067 return;
1068 }
1069
1070 SmallVector<unsigned, 8> Indices;
1071
1072 for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
1073 if (!AL.isArgExpr(Arg: I)) {
1074 DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
1075 return;
1076 }
1077
1078 const Expr *IndexExpr = AL.getArgAsExpr(Arg: I);
1079 uint32_t Index;
1080
1081 if (!checkUInt32Argument(S, AI: AL, Expr: IndexExpr, Val&: Index, Idx: I + 1, StrictlyUnsigned: false))
1082 return;
1083
1084 if (Index > DeclFD->getNumParams()) {
1085 S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
1086 << AL << Index << DeclFD << DeclFD->getNumParams();
1087 return;
1088 }
1089
1090 QualType T1 = AttrFD->getParamDecl(i: I - 1)->getType();
1091 QualType T2 = DeclFD->getParamDecl(i: Index - 1)->getType();
1092
1093 if (T1.getCanonicalType().getUnqualifiedType() !=
1094 T2.getCanonicalType().getUnqualifiedType()) {
1095 S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
1096 << AL << Index << DeclFD << T2 << I << AttrFD << T1;
1097 return;
1098 }
1099
1100 Indices.push_back(Elt: Index - 1);
1101 }
1102
1103 D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
1104 S.Context, AL, AttrFD, Indices.data(), Indices.size()));
1105}
1106
1107static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1108 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1109
1110 Expr *Cond;
1111 StringRef Msg;
1112 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1113 return;
1114
1115 StringRef DiagTypeStr;
1116 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 2, Str&: DiagTypeStr))
1117 return;
1118
1119 DiagnoseIfAttr::DiagnosticType DiagType;
1120 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1121 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1122 diag::err_diagnose_if_invalid_diagnostic_type);
1123 return;
1124 }
1125
1126 bool ArgDependent = false;
1127 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
1128 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(E: Cond);
1129 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1130 S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1131}
1132
1133static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1134 static constexpr const StringRef kWildcard = "*";
1135
1136 llvm::SmallVector<StringRef, 16> Names;
1137 bool HasWildcard = false;
1138
1139 const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1140 if (Name == kWildcard)
1141 HasWildcard = true;
1142 Names.push_back(Elt: Name);
1143 };
1144
1145 // Add previously defined attributes.
1146 if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1147 for (StringRef BuiltinName : NBA->builtinNames())
1148 AddBuiltinName(BuiltinName);
1149
1150 // Add current attributes.
1151 if (AL.getNumArgs() == 0)
1152 AddBuiltinName(kWildcard);
1153 else
1154 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1155 StringRef BuiltinName;
1156 SourceLocation LiteralLoc;
1157 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: BuiltinName, ArgLocation: &LiteralLoc))
1158 return;
1159
1160 if (Builtin::Context::isBuiltinFunc(Name: BuiltinName))
1161 AddBuiltinName(BuiltinName);
1162 else
1163 S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1164 << BuiltinName << AL;
1165 }
1166
1167 // Repeating the same attribute is fine.
1168 llvm::sort(C&: Names);
1169 Names.erase(CS: std::unique(first: Names.begin(), last: Names.end()), CE: Names.end());
1170
1171 // Empty no_builtin must be on its own.
1172 if (HasWildcard && Names.size() > 1)
1173 S.Diag(D->getLocation(),
1174 diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1175 << AL;
1176
1177 if (D->hasAttr<NoBuiltinAttr>())
1178 D->dropAttr<NoBuiltinAttr>();
1179 D->addAttr(::new (S.Context)
1180 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1181}
1182
1183static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1184 if (D->hasAttr<PassObjectSizeAttr>()) {
1185 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1186 return;
1187 }
1188
1189 Expr *E = AL.getArgAsExpr(Arg: 0);
1190 uint32_t Type;
1191 if (!checkUInt32Argument(S, AI: AL, Expr: E, Val&: Type, /*Idx=*/1))
1192 return;
1193
1194 // pass_object_size's argument is passed in as the second argument of
1195 // __builtin_object_size. So, it has the same constraints as that second
1196 // argument; namely, it must be in the range [0, 3].
1197 if (Type > 3) {
1198 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1199 << AL << 0 << 3 << E->getSourceRange();
1200 return;
1201 }
1202
1203 // pass_object_size is only supported on constant pointer parameters; as a
1204 // kindness to users, we allow the parameter to be non-const for declarations.
1205 // At this point, we have no clue if `D` belongs to a function declaration or
1206 // definition, so we defer the constness check until later.
1207 if (!cast<ParmVarDecl>(Val: D)->getType()->isPointerType()) {
1208 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1209 return;
1210 }
1211
1212 D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1213}
1214
1215static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1216 ConsumableAttr::ConsumedState DefaultState;
1217
1218 if (AL.isArgIdent(Arg: 0)) {
1219 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
1220 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1221 DefaultState)) {
1222 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1223 << IL->Ident;
1224 return;
1225 }
1226 } else {
1227 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1228 << AL << AANT_ArgumentIdentifier;
1229 return;
1230 }
1231
1232 D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1233}
1234
1235static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1236 const ParsedAttr &AL) {
1237 QualType ThisType = MD->getFunctionObjectParameterType();
1238
1239 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1240 if (!RD->hasAttr<ConsumableAttr>()) {
1241 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1242
1243 return false;
1244 }
1245 }
1246
1247 return true;
1248}
1249
1250static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1251 if (!AL.checkAtLeastNumArgs(S, Num: 1))
1252 return;
1253
1254 if (!checkForConsumableClass(S, MD: cast<CXXMethodDecl>(Val: D), AL))
1255 return;
1256
1257 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1258 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1259 CallableWhenAttr::ConsumedState CallableState;
1260
1261 StringRef StateString;
1262 SourceLocation Loc;
1263 if (AL.isArgIdent(Arg: ArgIndex)) {
1264 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: ArgIndex);
1265 StateString = Ident->Ident->getName();
1266 Loc = Ident->Loc;
1267 } else {
1268 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: ArgIndex, Str&: StateString, ArgLocation: &Loc))
1269 return;
1270 }
1271
1272 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1273 CallableState)) {
1274 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1275 return;
1276 }
1277
1278 States.push_back(CallableState);
1279 }
1280
1281 D->addAttr(::new (S.Context)
1282 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1283}
1284
1285static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1286 ParamTypestateAttr::ConsumedState ParamState;
1287
1288 if (AL.isArgIdent(Arg: 0)) {
1289 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: 0);
1290 StringRef StateString = Ident->Ident->getName();
1291
1292 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1293 ParamState)) {
1294 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1295 << AL << StateString;
1296 return;
1297 }
1298 } else {
1299 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1300 << AL << AANT_ArgumentIdentifier;
1301 return;
1302 }
1303
1304 // FIXME: This check is currently being done in the analysis. It can be
1305 // enabled here only after the parser propagates attributes at
1306 // template specialization definition, not declaration.
1307 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1308 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1309 //
1310 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1311 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1312 // ReturnType.getAsString();
1313 // return;
1314 //}
1315
1316 D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1317}
1318
1319static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1320 ReturnTypestateAttr::ConsumedState ReturnState;
1321
1322 if (AL.isArgIdent(Arg: 0)) {
1323 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
1324 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1325 ReturnState)) {
1326 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1327 << IL->Ident;
1328 return;
1329 }
1330 } else {
1331 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1332 << AL << AANT_ArgumentIdentifier;
1333 return;
1334 }
1335
1336 // FIXME: This check is currently being done in the analysis. It can be
1337 // enabled here only after the parser propagates attributes at
1338 // template specialization definition, not declaration.
1339 // QualType ReturnType;
1340 //
1341 // if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1342 // ReturnType = Param->getType();
1343 //
1344 //} else if (const CXXConstructorDecl *Constructor =
1345 // dyn_cast<CXXConstructorDecl>(D)) {
1346 // ReturnType = Constructor->getFunctionObjectParameterType();
1347 //
1348 //} else {
1349 //
1350 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1351 //}
1352 //
1353 // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1354 //
1355 // if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1356 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1357 // ReturnType.getAsString();
1358 // return;
1359 //}
1360
1361 D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1362}
1363
1364static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1365 if (!checkForConsumableClass(S, MD: cast<CXXMethodDecl>(Val: D), AL))
1366 return;
1367
1368 SetTypestateAttr::ConsumedState NewState;
1369 if (AL.isArgIdent(Arg: 0)) {
1370 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: 0);
1371 StringRef Param = Ident->Ident->getName();
1372 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1373 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1374 << Param;
1375 return;
1376 }
1377 } else {
1378 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1379 << AL << AANT_ArgumentIdentifier;
1380 return;
1381 }
1382
1383 D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1384}
1385
1386static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1387 if (!checkForConsumableClass(S, MD: cast<CXXMethodDecl>(Val: D), AL))
1388 return;
1389
1390 TestTypestateAttr::ConsumedState TestState;
1391 if (AL.isArgIdent(Arg: 0)) {
1392 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: 0);
1393 StringRef Param = Ident->Ident->getName();
1394 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1395 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1396 << Param;
1397 return;
1398 }
1399 } else {
1400 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1401 << AL << AANT_ArgumentIdentifier;
1402 return;
1403 }
1404
1405 D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1406}
1407
1408static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1409 // Remember this typedef decl, we will need it later for diagnostics.
1410 S.ExtVectorDecls.push_back(LocalValue: cast<TypedefNameDecl>(Val: D));
1411}
1412
1413static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1414 if (auto *TD = dyn_cast<TagDecl>(Val: D))
1415 TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1416 else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
1417 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1418 !FD->getType()->isIncompleteType() &&
1419 FD->isBitField() &&
1420 S.Context.getTypeAlign(FD->getType()) <= 8);
1421
1422 if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1423 if (BitfieldByteAligned)
1424 // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1425 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1426 << AL << FD->getType();
1427 else
1428 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1429 } else {
1430 // Report warning about changed offset in the newer compiler versions.
1431 if (BitfieldByteAligned)
1432 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1433
1434 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1435 }
1436
1437 } else
1438 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1439}
1440
1441static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1442 auto *RD = cast<CXXRecordDecl>(Val: D);
1443 ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1444 assert(CTD && "attribute does not appertain to this declaration");
1445
1446 ParsedType PT = AL.getTypeArg();
1447 TypeSourceInfo *TSI = nullptr;
1448 QualType T = S.GetTypeFromParser(Ty: PT, TInfo: &TSI);
1449 if (!TSI)
1450 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: AL.getLoc());
1451
1452 if (!T.hasQualifiers() && T->isTypedefNameType()) {
1453 // Find the template name, if this type names a template specialization.
1454 const TemplateDecl *Template = nullptr;
1455 if (const auto *CTSD = dyn_cast_if_present<ClassTemplateSpecializationDecl>(
1456 Val: T->getAsCXXRecordDecl())) {
1457 Template = CTSD->getSpecializedTemplate();
1458 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1459 while (TST && TST->isTypeAlias())
1460 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1461 if (TST)
1462 Template = TST->getTemplateName().getAsTemplateDecl();
1463 }
1464
1465 if (Template && declaresSameEntity(Template, CTD)) {
1466 D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1467 return;
1468 }
1469 }
1470
1471 S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1472 << T << CTD;
1473 if (const auto *TT = T->getAs<TypedefType>())
1474 S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1475 << TT->getDecl();
1476}
1477
1478static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1479 // The IBOutlet/IBOutletCollection attributes only apply to instance
1480 // variables or properties of Objective-C classes. The outlet must also
1481 // have an object reference type.
1482 if (const auto *VD = dyn_cast<ObjCIvarDecl>(Val: D)) {
1483 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1484 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1485 << AL << VD->getType() << 0;
1486 return false;
1487 }
1488 }
1489 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(Val: D)) {
1490 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1491 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1492 << AL << PD->getType() << 1;
1493 return false;
1494 }
1495 }
1496 else {
1497 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1498 return false;
1499 }
1500
1501 return true;
1502}
1503
1504static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1505 if (!checkIBOutletCommon(S, D, AL))
1506 return;
1507
1508 D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1509}
1510
1511static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1512
1513 // The iboutletcollection attribute can have zero or one arguments.
1514 if (AL.getNumArgs() > 1) {
1515 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1516 return;
1517 }
1518
1519 if (!checkIBOutletCommon(S, D, AL))
1520 return;
1521
1522 ParsedType PT;
1523
1524 if (AL.hasParsedType())
1525 PT = AL.getTypeArg();
1526 else {
1527 PT = S.getTypeName(II: S.Context.Idents.get(Name: "NSObject"), NameLoc: AL.getLoc(),
1528 S: S.getScopeForContext(Ctx: D->getDeclContext()->getParent()));
1529 if (!PT) {
1530 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1531 return;
1532 }
1533 }
1534
1535 TypeSourceInfo *QTLoc = nullptr;
1536 QualType QT = S.GetTypeFromParser(Ty: PT, TInfo: &QTLoc);
1537 if (!QTLoc)
1538 QTLoc = S.Context.getTrivialTypeSourceInfo(T: QT, Loc: AL.getLoc());
1539
1540 // Diagnose use of non-object type in iboutletcollection attribute.
1541 // FIXME. Gnu attribute extension ignores use of builtin types in
1542 // attributes. So, __attribute__((iboutletcollection(char))) will be
1543 // treated as __attribute__((iboutletcollection())).
1544 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1545 S.Diag(AL.getLoc(),
1546 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1547 : diag::err_iboutletcollection_type) << QT;
1548 return;
1549 }
1550
1551 D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1552}
1553
1554bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1555 if (RefOkay) {
1556 if (T->isReferenceType())
1557 return true;
1558 } else {
1559 T = T.getNonReferenceType();
1560 }
1561
1562 // The nonnull attribute, and other similar attributes, can be applied to a
1563 // transparent union that contains a pointer type.
1564 if (const RecordType *UT = T->getAsUnionType()) {
1565 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1566 RecordDecl *UD = UT->getDecl();
1567 for (const auto *I : UD->fields()) {
1568 QualType QT = I->getType();
1569 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1570 return true;
1571 }
1572 }
1573 }
1574
1575 return T->isAnyPointerType() || T->isBlockPointerType();
1576}
1577
1578static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1579 SourceRange AttrParmRange,
1580 SourceRange TypeRange,
1581 bool isReturnValue = false) {
1582 if (!S.isValidPointerAttrType(T)) {
1583 if (isReturnValue)
1584 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1585 << AL << AttrParmRange << TypeRange;
1586 else
1587 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1588 << AL << AttrParmRange << TypeRange << 0;
1589 return false;
1590 }
1591 return true;
1592}
1593
1594static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1595 SmallVector<ParamIdx, 8> NonNullArgs;
1596 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1597 Expr *Ex = AL.getArgAsExpr(Arg: I);
1598 ParamIdx Idx;
1599 if (!checkFunctionOrMethodParameterIndex(S, D, AI: AL, AttrArgNum: I + 1, IdxExpr: Ex, Idx))
1600 return;
1601
1602 // Is the function argument a pointer type?
1603 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1604 !attrNonNullArgCheck(
1605 S, getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex()), AL,
1606 Ex->getSourceRange(),
1607 getFunctionOrMethodParamRange(D, Idx: Idx.getASTIndex())))
1608 continue;
1609
1610 NonNullArgs.push_back(Elt: Idx);
1611 }
1612
1613 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1614 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1615 // check if the attribute came from a macro expansion or a template
1616 // instantiation.
1617 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1618 !S.inTemplateInstantiation()) {
1619 bool AnyPointers = isFunctionOrMethodVariadic(D);
1620 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1621 I != E && !AnyPointers; ++I) {
1622 QualType T = getFunctionOrMethodParamType(D, Idx: I);
1623 if (T->isDependentType() || S.isValidPointerAttrType(T))
1624 AnyPointers = true;
1625 }
1626
1627 if (!AnyPointers)
1628 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1629 }
1630
1631 ParamIdx *Start = NonNullArgs.data();
1632 unsigned Size = NonNullArgs.size();
1633 llvm::array_pod_sort(Start, End: Start + Size);
1634 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1635}
1636
1637static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1638 const ParsedAttr &AL) {
1639 if (AL.getNumArgs() > 0) {
1640 if (D->getFunctionType()) {
1641 handleNonNullAttr(S, D, AL);
1642 } else {
1643 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1644 << D->getSourceRange();
1645 }
1646 return;
1647 }
1648
1649 // Is the argument a pointer type?
1650 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1651 D->getSourceRange()))
1652 return;
1653
1654 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1655}
1656
1657static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1658 QualType ResultType = getFunctionOrMethodResultType(D);
1659 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1660 if (!attrNonNullArgCheck(S, T: ResultType, AL, AttrParmRange: SourceRange(), TypeRange: SR,
1661 /* isReturnValue */ true))
1662 return;
1663
1664 D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1665}
1666
1667static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1668 if (D->isInvalidDecl())
1669 return;
1670
1671 // noescape only applies to pointer types.
1672 QualType T = cast<ParmVarDecl>(Val: D)->getType();
1673 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1674 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1675 << AL << AL.getRange() << 0;
1676 return;
1677 }
1678
1679 D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1680}
1681
1682static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1683 Expr *E = AL.getArgAsExpr(Arg: 0),
1684 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(Arg: 1) : nullptr;
1685 S.AddAssumeAlignedAttr(D, CI: AL, E, OE);
1686}
1687
1688static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1689 S.AddAllocAlignAttr(D, CI: AL, ParamExpr: AL.getArgAsExpr(Arg: 0));
1690}
1691
1692void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1693 Expr *OE) {
1694 QualType ResultType = getFunctionOrMethodResultType(D);
1695 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1696
1697 AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1698 SourceLocation AttrLoc = TmpAttr.getLocation();
1699
1700 if (!isValidPointerAttrType(T: ResultType, /* RefOkay */ true)) {
1701 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1702 << &TmpAttr << TmpAttr.getRange() << SR;
1703 return;
1704 }
1705
1706 if (!E->isValueDependent()) {
1707 std::optional<llvm::APSInt> I = llvm::APSInt(64);
1708 if (!(I = E->getIntegerConstantExpr(Ctx: Context))) {
1709 if (OE)
1710 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1711 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1712 << E->getSourceRange();
1713 else
1714 Diag(AttrLoc, diag::err_attribute_argument_type)
1715 << &TmpAttr << AANT_ArgumentIntegerConstant
1716 << E->getSourceRange();
1717 return;
1718 }
1719
1720 if (!I->isPowerOf2()) {
1721 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1722 << E->getSourceRange();
1723 return;
1724 }
1725
1726 if (*I > Sema::MaximumAlignment)
1727 Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1728 << CI.getRange() << Sema::MaximumAlignment;
1729 }
1730
1731 if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Ctx: Context)) {
1732 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1733 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1734 << OE->getSourceRange();
1735 return;
1736 }
1737
1738 D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1739}
1740
1741void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1742 Expr *ParamExpr) {
1743 QualType ResultType = getFunctionOrMethodResultType(D);
1744
1745 AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1746 SourceLocation AttrLoc = CI.getLoc();
1747
1748 if (!ResultType->isDependentType() &&
1749 !isValidPointerAttrType(T: ResultType, /* RefOkay */ true)) {
1750 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1751 << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1752 return;
1753 }
1754
1755 ParamIdx Idx;
1756 const auto *FuncDecl = cast<FunctionDecl>(Val: D);
1757 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1758 /*AttrArgNum=*/1, ParamExpr, Idx))
1759 return;
1760
1761 QualType Ty = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
1762 if (!Ty->isDependentType() && !Ty->isIntegralType(Ctx: Context) &&
1763 !Ty->isAlignValT()) {
1764 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1765 << &TmpAttr
1766 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1767 return;
1768 }
1769
1770 D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1771}
1772
1773/// Check if \p AssumptionStr is a known assumption and warn if not.
1774static void checkAssumptionAttr(Sema &S, SourceLocation Loc,
1775 StringRef AssumptionStr) {
1776 if (llvm::KnownAssumptionStrings.count(Key: AssumptionStr))
1777 return;
1778
1779 unsigned BestEditDistance = 3;
1780 StringRef Suggestion;
1781 for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1782 unsigned EditDistance =
1783 AssumptionStr.edit_distance(Other: KnownAssumptionIt.getKey());
1784 if (EditDistance < BestEditDistance) {
1785 Suggestion = KnownAssumptionIt.getKey();
1786 BestEditDistance = EditDistance;
1787 }
1788 }
1789
1790 if (!Suggestion.empty())
1791 S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
1792 << AssumptionStr << Suggestion;
1793 else
1794 S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
1795}
1796
1797static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1798 // Handle the case where the attribute has a text message.
1799 StringRef Str;
1800 SourceLocation AttrStrLoc;
1801 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &AttrStrLoc))
1802 return;
1803
1804 checkAssumptionAttr(S, Loc: AttrStrLoc, AssumptionStr: Str);
1805
1806 D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
1807}
1808
1809/// Normalize the attribute, __foo__ becomes foo.
1810/// Returns true if normalization was applied.
1811static bool normalizeName(StringRef &AttrName) {
1812 if (AttrName.size() > 4 && AttrName.starts_with(Prefix: "__") &&
1813 AttrName.ends_with(Suffix: "__")) {
1814 AttrName = AttrName.drop_front(N: 2).drop_back(N: 2);
1815 return true;
1816 }
1817 return false;
1818}
1819
1820static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1821 // This attribute must be applied to a function declaration. The first
1822 // argument to the attribute must be an identifier, the name of the resource,
1823 // for example: malloc. The following arguments must be argument indexes, the
1824 // arguments must be of integer type for Returns, otherwise of pointer type.
1825 // The difference between Holds and Takes is that a pointer may still be used
1826 // after being held. free() should be __attribute((ownership_takes)), whereas
1827 // a list append function may well be __attribute((ownership_holds)).
1828
1829 if (!AL.isArgIdent(Arg: 0)) {
1830 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1831 << AL << 1 << AANT_ArgumentIdentifier;
1832 return;
1833 }
1834
1835 // Figure out our Kind.
1836 OwnershipAttr::OwnershipKind K =
1837 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1838
1839 // Check arguments.
1840 switch (K) {
1841 case OwnershipAttr::Takes:
1842 case OwnershipAttr::Holds:
1843 if (AL.getNumArgs() < 2) {
1844 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1845 return;
1846 }
1847 break;
1848 case OwnershipAttr::Returns:
1849 if (AL.getNumArgs() > 2) {
1850 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1851 return;
1852 }
1853 break;
1854 }
1855
1856 IdentifierInfo *Module = AL.getArgAsIdent(Arg: 0)->Ident;
1857
1858 StringRef ModuleName = Module->getName();
1859 if (normalizeName(AttrName&: ModuleName)) {
1860 Module = &S.PP.getIdentifierTable().get(Name: ModuleName);
1861 }
1862
1863 SmallVector<ParamIdx, 8> OwnershipArgs;
1864 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1865 Expr *Ex = AL.getArgAsExpr(Arg: i);
1866 ParamIdx Idx;
1867 if (!checkFunctionOrMethodParameterIndex(S, D, AI: AL, AttrArgNum: i, IdxExpr: Ex, Idx))
1868 return;
1869
1870 // Is the function argument a pointer type?
1871 QualType T = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
1872 int Err = -1; // No error
1873 switch (K) {
1874 case OwnershipAttr::Takes:
1875 case OwnershipAttr::Holds:
1876 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1877 Err = 0;
1878 break;
1879 case OwnershipAttr::Returns:
1880 if (!T->isIntegerType())
1881 Err = 1;
1882 break;
1883 }
1884 if (-1 != Err) {
1885 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1886 << Ex->getSourceRange();
1887 return;
1888 }
1889
1890 // Check we don't have a conflict with another ownership attribute.
1891 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1892 // Cannot have two ownership attributes of different kinds for the same
1893 // index.
1894 if (I->getOwnKind() != K && llvm::is_contained(I->args(), Idx)) {
1895 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1896 << AL << I
1897 << (AL.isRegularKeywordAttribute() ||
1898 I->isRegularKeywordAttribute());
1899 return;
1900 } else if (K == OwnershipAttr::Returns &&
1901 I->getOwnKind() == OwnershipAttr::Returns) {
1902 // A returns attribute conflicts with any other returns attribute using
1903 // a different index.
1904 if (!llvm::is_contained(I->args(), Idx)) {
1905 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1906 << I->args_begin()->getSourceIndex();
1907 if (I->args_size())
1908 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1909 << Idx.getSourceIndex() << Ex->getSourceRange();
1910 return;
1911 }
1912 }
1913 }
1914 OwnershipArgs.push_back(Elt: Idx);
1915 }
1916
1917 ParamIdx *Start = OwnershipArgs.data();
1918 unsigned Size = OwnershipArgs.size();
1919 llvm::array_pod_sort(Start, End: Start + Size);
1920 D->addAttr(::new (S.Context)
1921 OwnershipAttr(S.Context, AL, Module, Start, Size));
1922}
1923
1924static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1925 // Check the attribute arguments.
1926 if (AL.getNumArgs() > 1) {
1927 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1928 return;
1929 }
1930
1931 // gcc rejects
1932 // class c {
1933 // static int a __attribute__((weakref ("v2")));
1934 // static int b() __attribute__((weakref ("f3")));
1935 // };
1936 // and ignores the attributes of
1937 // void f(void) {
1938 // static int a __attribute__((weakref ("v2")));
1939 // }
1940 // we reject them
1941 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1942 if (!Ctx->isFileContext()) {
1943 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1944 << cast<NamedDecl>(D);
1945 return;
1946 }
1947
1948 // The GCC manual says
1949 //
1950 // At present, a declaration to which `weakref' is attached can only
1951 // be `static'.
1952 //
1953 // It also says
1954 //
1955 // Without a TARGET,
1956 // given as an argument to `weakref' or to `alias', `weakref' is
1957 // equivalent to `weak'.
1958 //
1959 // gcc 4.4.1 will accept
1960 // int a7 __attribute__((weakref));
1961 // as
1962 // int a7 __attribute__((weak));
1963 // This looks like a bug in gcc. We reject that for now. We should revisit
1964 // it if this behaviour is actually used.
1965
1966 // GCC rejects
1967 // static ((alias ("y"), weakref)).
1968 // Should we? How to check that weakref is before or after alias?
1969
1970 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1971 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1972 // StringRef parameter it was given anyway.
1973 StringRef Str;
1974 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1975 // GCC will accept anything as the argument of weakref. Should we
1976 // check for an existing decl?
1977 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1978
1979 D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1980}
1981
1982static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1983 StringRef Str;
1984 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
1985 return;
1986
1987 // Aliases should be on declarations, not definitions.
1988 const auto *FD = cast<FunctionDecl>(Val: D);
1989 if (FD->isThisDeclarationADefinition()) {
1990 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1991 return;
1992 }
1993
1994 D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1995}
1996
1997static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1998 StringRef Str;
1999 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
2000 return;
2001
2002 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2003 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
2004 return;
2005 }
2006
2007 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
2008 CudaVersion Version =
2009 ToCudaVersion(S.Context.getTargetInfo().getSDKVersion());
2010 if (Version != CudaVersion::UNKNOWN && Version < CudaVersion::CUDA_100)
2011 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
2012 }
2013
2014 // Aliases should be on declarations, not definitions.
2015 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
2016 if (FD->isThisDeclarationADefinition()) {
2017 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
2018 return;
2019 }
2020 } else {
2021 const auto *VD = cast<VarDecl>(Val: D);
2022 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
2023 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
2024 return;
2025 }
2026 }
2027
2028 // Mark target used to prevent unneeded-internal-declaration warnings.
2029 if (!S.LangOpts.CPlusPlus) {
2030 // FIXME: demangle Str for C++, as the attribute refers to the mangled
2031 // linkage name, not the pre-mangled identifier.
2032 const DeclarationNameInfo target(&S.Context.Idents.get(Name: Str), AL.getLoc());
2033 LookupResult LR(S, target, Sema::LookupOrdinaryName);
2034 if (S.LookupQualifiedName(R&: LR, LookupCtx: S.getCurLexicalContext()))
2035 for (NamedDecl *ND : LR)
2036 ND->markUsed(S.Context);
2037 }
2038
2039 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
2040}
2041
2042static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2043 StringRef Model;
2044 SourceLocation LiteralLoc;
2045 // Check that it is a string.
2046 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Model, ArgLocation: &LiteralLoc))
2047 return;
2048
2049 // Check that the value.
2050 if (Model != "global-dynamic" && Model != "local-dynamic"
2051 && Model != "initial-exec" && Model != "local-exec") {
2052 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
2053 return;
2054 }
2055
2056 if (S.Context.getTargetInfo().getTriple().isOSAIX() &&
2057 Model == "local-dynamic") {
2058 S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model;
2059 return;
2060 }
2061
2062 D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
2063}
2064
2065static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2066 QualType ResultType = getFunctionOrMethodResultType(D);
2067 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
2068 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
2069 return;
2070 }
2071
2072 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
2073 << AL << getFunctionOrMethodResultSourceRange(D);
2074}
2075
2076static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2077 // Ensure we don't combine these with themselves, since that causes some
2078 // confusing behavior.
2079 if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
2080 if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
2081 return;
2082
2083 if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
2084 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2085 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2086 return;
2087 }
2088 } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
2089 if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
2090 return;
2091
2092 if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
2093 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2094 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2095 return;
2096 }
2097 }
2098
2099 FunctionDecl *FD = cast<FunctionDecl>(Val: D);
2100
2101 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
2102 if (MD->getParent()->isLambda()) {
2103 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
2104 return;
2105 }
2106 }
2107
2108 if (!AL.checkAtLeastNumArgs(S, Num: 1))
2109 return;
2110
2111 SmallVector<IdentifierInfo *, 8> CPUs;
2112 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
2113 if (!AL.isArgIdent(Arg: ArgNo)) {
2114 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
2115 << AL << AANT_ArgumentIdentifier;
2116 return;
2117 }
2118
2119 IdentifierLoc *CPUArg = AL.getArgAsIdent(Arg: ArgNo);
2120 StringRef CPUName = CPUArg->Ident->getName().trim();
2121
2122 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(Name: CPUName)) {
2123 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
2124 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
2125 return;
2126 }
2127
2128 const TargetInfo &Target = S.Context.getTargetInfo();
2129 if (llvm::any_of(Range&: CPUs, P: [CPUName, &Target](const IdentifierInfo *Cur) {
2130 return Target.CPUSpecificManglingCharacter(Name: CPUName) ==
2131 Target.CPUSpecificManglingCharacter(Name: Cur->getName());
2132 })) {
2133 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
2134 return;
2135 }
2136 CPUs.push_back(Elt: CPUArg->Ident);
2137 }
2138
2139 FD->setIsMultiVersion(true);
2140 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2141 D->addAttr(::new (S.Context)
2142 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2143 else
2144 D->addAttr(::new (S.Context)
2145 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2146}
2147
2148static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2149 if (S.LangOpts.CPlusPlus) {
2150 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2151 << AL << AttributeLangSupport::Cpp;
2152 return;
2153 }
2154
2155 D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
2156}
2157
2158static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2159 if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
2160 S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2161 return;
2162 }
2163
2164 const auto *FD = cast<FunctionDecl>(Val: D);
2165 if (!FD->isExternallyVisible()) {
2166 S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2167 return;
2168 }
2169
2170 D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2171}
2172
2173static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2174 if (AL.isDeclspecAttribute()) {
2175 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2176 const auto &Arch = Triple.getArch();
2177 if (Arch != llvm::Triple::x86 &&
2178 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2179 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2180 << AL << Triple.getArchName();
2181 return;
2182 }
2183
2184 // This form is not allowed to be written on a member function (static or
2185 // nonstatic) when in Microsoft compatibility mode.
2186 if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(Val: D)) {
2187 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
2188 << AL << AL.isRegularKeywordAttribute() << "non-member functions";
2189 return;
2190 }
2191 }
2192
2193 D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2194}
2195
2196static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2197 if (hasDeclarator(D)) return;
2198
2199 if (!isa<ObjCMethodDecl>(Val: D)) {
2200 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2201 << Attrs << Attrs.isRegularKeywordAttribute()
2202 << ExpectedFunctionOrMethod;
2203 return;
2204 }
2205
2206 D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2207}
2208
2209static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
2210 // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
2211 // issue an appropriate diagnostic. However, don't issue a diagnostic if the
2212 // attribute name comes from a macro expansion. We don't want to punish users
2213 // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
2214 // is defined as a macro which expands to '_Noreturn').
2215 if (!S.getLangOpts().CPlusPlus &&
2216 A.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn &&
2217 !(A.getLoc().isMacroID() &&
2218 S.getSourceManager().isInSystemMacro(A.getLoc())))
2219 S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange();
2220
2221 D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A));
2222}
2223
2224static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2225 if (!S.getLangOpts().CFProtectionBranch)
2226 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2227 else
2228 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2229}
2230
2231bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2232 if (!Attrs.checkExactlyNumArgs(S&: *this, Num: 0)) {
2233 Attrs.setInvalid();
2234 return true;
2235 }
2236
2237 return false;
2238}
2239
2240bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2241 // Check whether the attribute is valid on the current target.
2242 if (!AL.existsInTarget(Target: Context.getTargetInfo())) {
2243 Diag(AL.getLoc(), AL.isRegularKeywordAttribute()
2244 ? diag::err_keyword_not_supported_on_target
2245 : diag::warn_unknown_attribute_ignored)
2246 << AL << AL.getRange();
2247 AL.setInvalid();
2248 return true;
2249 }
2250
2251 return false;
2252}
2253
2254static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2255
2256 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2257 // because 'analyzer_noreturn' does not impact the type.
2258 if (!isFunctionOrMethodOrBlock(D)) {
2259 ValueDecl *VD = dyn_cast<ValueDecl>(Val: D);
2260 if (!VD || (!VD->getType()->isBlockPointerType() &&
2261 !VD->getType()->isFunctionPointerType())) {
2262 S.Diag(AL.getLoc(), AL.isStandardAttributeSyntax()
2263 ? diag::err_attribute_wrong_decl_type
2264 : diag::warn_attribute_wrong_decl_type)
2265 << AL << AL.isRegularKeywordAttribute()
2266 << ExpectedFunctionMethodOrBlock;
2267 return;
2268 }
2269 }
2270
2271 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2272}
2273
2274// PS3 PPU-specific.
2275static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2276 /*
2277 Returning a Vector Class in Registers
2278
2279 According to the PPU ABI specifications, a class with a single member of
2280 vector type is returned in memory when used as the return value of a
2281 function.
2282 This results in inefficient code when implementing vector classes. To return
2283 the value in a single vector register, add the vecreturn attribute to the
2284 class definition. This attribute is also applicable to struct types.
2285
2286 Example:
2287
2288 struct Vector
2289 {
2290 __vector float xyzw;
2291 } __attribute__((vecreturn));
2292
2293 Vector Add(Vector lhs, Vector rhs)
2294 {
2295 Vector result;
2296 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2297 return result; // This will be returned in a register
2298 }
2299 */
2300 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2301 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2302 return;
2303 }
2304
2305 const auto *R = cast<RecordDecl>(Val: D);
2306 int count = 0;
2307
2308 if (!isa<CXXRecordDecl>(Val: R)) {
2309 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2310 return;
2311 }
2312
2313 if (!cast<CXXRecordDecl>(Val: R)->isPOD()) {
2314 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2315 return;
2316 }
2317
2318 for (const auto *I : R->fields()) {
2319 if ((count == 1) || !I->getType()->isVectorType()) {
2320 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2321 return;
2322 }
2323 count++;
2324 }
2325
2326 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2327}
2328
2329static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2330 const ParsedAttr &AL) {
2331 if (isa<ParmVarDecl>(Val: D)) {
2332 // [[carries_dependency]] can only be applied to a parameter if it is a
2333 // parameter of a function declaration or lambda.
2334 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2335 S.Diag(AL.getLoc(),
2336 diag::err_carries_dependency_param_not_function_decl);
2337 return;
2338 }
2339 }
2340
2341 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2342}
2343
2344static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2345 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2346
2347 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2348 // about using it as an extension.
2349 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2350 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2351
2352 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2353}
2354
2355static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2356 uint32_t priority = ConstructorAttr::DefaultPriority;
2357 if (S.getLangOpts().HLSL && AL.getNumArgs()) {
2358 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
2359 return;
2360 }
2361 if (AL.getNumArgs() &&
2362 !checkUInt32Argument(S, AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: priority))
2363 return;
2364
2365 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2366}
2367
2368static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2369 uint32_t priority = DestructorAttr::DefaultPriority;
2370 if (AL.getNumArgs() &&
2371 !checkUInt32Argument(S, AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: priority))
2372 return;
2373
2374 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2375}
2376
2377template <typename AttrTy>
2378static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2379 // Handle the case where the attribute has a text message.
2380 StringRef Str;
2381 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
2382 return;
2383
2384 D->addAttr(A: ::new (S.Context) AttrTy(S.Context, AL, Str));
2385}
2386
2387static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2388 const ParsedAttr &AL) {
2389 if (!cast<ObjCProtocolDecl>(Val: D)->isThisDeclarationADefinition()) {
2390 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2391 << AL << AL.getRange();
2392 return;
2393 }
2394
2395 D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2396}
2397
2398static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2399 IdentifierInfo *Platform,
2400 VersionTuple Introduced,
2401 VersionTuple Deprecated,
2402 VersionTuple Obsoleted) {
2403 StringRef PlatformName
2404 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2405 if (PlatformName.empty())
2406 PlatformName = Platform->getName();
2407
2408 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2409 // of these steps are needed).
2410 if (!Introduced.empty() && !Deprecated.empty() &&
2411 !(Introduced <= Deprecated)) {
2412 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2413 << 1 << PlatformName << Deprecated.getAsString()
2414 << 0 << Introduced.getAsString();
2415 return true;
2416 }
2417
2418 if (!Introduced.empty() && !Obsoleted.empty() &&
2419 !(Introduced <= Obsoleted)) {
2420 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2421 << 2 << PlatformName << Obsoleted.getAsString()
2422 << 0 << Introduced.getAsString();
2423 return true;
2424 }
2425
2426 if (!Deprecated.empty() && !Obsoleted.empty() &&
2427 !(Deprecated <= Obsoleted)) {
2428 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2429 << 2 << PlatformName << Obsoleted.getAsString()
2430 << 1 << Deprecated.getAsString();
2431 return true;
2432 }
2433
2434 return false;
2435}
2436
2437/// Check whether the two versions match.
2438///
2439/// If either version tuple is empty, then they are assumed to match. If
2440/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2441static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2442 bool BeforeIsOkay) {
2443 if (X.empty() || Y.empty())
2444 return true;
2445
2446 if (X == Y)
2447 return true;
2448
2449 if (BeforeIsOkay && X < Y)
2450 return true;
2451
2452 return false;
2453}
2454
2455AvailabilityAttr *Sema::mergeAvailabilityAttr(
2456 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2457 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2458 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2459 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2460 int Priority) {
2461 VersionTuple MergedIntroduced = Introduced;
2462 VersionTuple MergedDeprecated = Deprecated;
2463 VersionTuple MergedObsoleted = Obsoleted;
2464 bool FoundAny = false;
2465 bool OverrideOrImpl = false;
2466 switch (AMK) {
2467 case AMK_None:
2468 case AMK_Redeclaration:
2469 OverrideOrImpl = false;
2470 break;
2471
2472 case AMK_Override:
2473 case AMK_ProtocolImplementation:
2474 case AMK_OptionalProtocolImplementation:
2475 OverrideOrImpl = true;
2476 break;
2477 }
2478
2479 if (D->hasAttrs()) {
2480 AttrVec &Attrs = D->getAttrs();
2481 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2482 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2483 if (!OldAA) {
2484 ++i;
2485 continue;
2486 }
2487
2488 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2489 if (OldPlatform != Platform) {
2490 ++i;
2491 continue;
2492 }
2493
2494 // If there is an existing availability attribute for this platform that
2495 // has a lower priority use the existing one and discard the new
2496 // attribute.
2497 if (OldAA->getPriority() < Priority)
2498 return nullptr;
2499
2500 // If there is an existing attribute for this platform that has a higher
2501 // priority than the new attribute then erase the old one and continue
2502 // processing the attributes.
2503 if (OldAA->getPriority() > Priority) {
2504 Attrs.erase(CI: Attrs.begin() + i);
2505 --e;
2506 continue;
2507 }
2508
2509 FoundAny = true;
2510 VersionTuple OldIntroduced = OldAA->getIntroduced();
2511 VersionTuple OldDeprecated = OldAA->getDeprecated();
2512 VersionTuple OldObsoleted = OldAA->getObsoleted();
2513 bool OldIsUnavailable = OldAA->getUnavailable();
2514
2515 if (!versionsMatch(X: OldIntroduced, Y: Introduced, BeforeIsOkay: OverrideOrImpl) ||
2516 !versionsMatch(X: Deprecated, Y: OldDeprecated, BeforeIsOkay: OverrideOrImpl) ||
2517 !versionsMatch(X: Obsoleted, Y: OldObsoleted, BeforeIsOkay: OverrideOrImpl) ||
2518 !(OldIsUnavailable == IsUnavailable ||
2519 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2520 if (OverrideOrImpl) {
2521 int Which = -1;
2522 VersionTuple FirstVersion;
2523 VersionTuple SecondVersion;
2524 if (!versionsMatch(X: OldIntroduced, Y: Introduced, BeforeIsOkay: OverrideOrImpl)) {
2525 Which = 0;
2526 FirstVersion = OldIntroduced;
2527 SecondVersion = Introduced;
2528 } else if (!versionsMatch(X: Deprecated, Y: OldDeprecated, BeforeIsOkay: OverrideOrImpl)) {
2529 Which = 1;
2530 FirstVersion = Deprecated;
2531 SecondVersion = OldDeprecated;
2532 } else if (!versionsMatch(X: Obsoleted, Y: OldObsoleted, BeforeIsOkay: OverrideOrImpl)) {
2533 Which = 2;
2534 FirstVersion = Obsoleted;
2535 SecondVersion = OldObsoleted;
2536 }
2537
2538 if (Which == -1) {
2539 Diag(OldAA->getLocation(),
2540 diag::warn_mismatched_availability_override_unavail)
2541 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2542 << (AMK == AMK_Override);
2543 } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2544 // Allow different 'introduced' / 'obsoleted' availability versions
2545 // on a method that implements an optional protocol requirement. It
2546 // makes less sense to allow this for 'deprecated' as the user can't
2547 // see if the method is 'deprecated' as 'respondsToSelector' will
2548 // still return true when the method is deprecated.
2549 ++i;
2550 continue;
2551 } else {
2552 Diag(OldAA->getLocation(),
2553 diag::warn_mismatched_availability_override)
2554 << Which
2555 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2556 << FirstVersion.getAsString() << SecondVersion.getAsString()
2557 << (AMK == AMK_Override);
2558 }
2559 if (AMK == AMK_Override)
2560 Diag(CI.getLoc(), diag::note_overridden_method);
2561 else
2562 Diag(CI.getLoc(), diag::note_protocol_method);
2563 } else {
2564 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2565 Diag(CI.getLoc(), diag::note_previous_attribute);
2566 }
2567
2568 Attrs.erase(CI: Attrs.begin() + i);
2569 --e;
2570 continue;
2571 }
2572
2573 VersionTuple MergedIntroduced2 = MergedIntroduced;
2574 VersionTuple MergedDeprecated2 = MergedDeprecated;
2575 VersionTuple MergedObsoleted2 = MergedObsoleted;
2576
2577 if (MergedIntroduced2.empty())
2578 MergedIntroduced2 = OldIntroduced;
2579 if (MergedDeprecated2.empty())
2580 MergedDeprecated2 = OldDeprecated;
2581 if (MergedObsoleted2.empty())
2582 MergedObsoleted2 = OldObsoleted;
2583
2584 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2585 MergedIntroduced2, MergedDeprecated2,
2586 MergedObsoleted2)) {
2587 Attrs.erase(CI: Attrs.begin() + i);
2588 --e;
2589 continue;
2590 }
2591
2592 MergedIntroduced = MergedIntroduced2;
2593 MergedDeprecated = MergedDeprecated2;
2594 MergedObsoleted = MergedObsoleted2;
2595 ++i;
2596 }
2597 }
2598
2599 if (FoundAny &&
2600 MergedIntroduced == Introduced &&
2601 MergedDeprecated == Deprecated &&
2602 MergedObsoleted == Obsoleted)
2603 return nullptr;
2604
2605 // Only create a new attribute if !OverrideOrImpl, but we want to do
2606 // the checking.
2607 if (!checkAvailabilityAttr(S&: *this, Range: CI.getRange(), Platform, Introduced: MergedIntroduced,
2608 Deprecated: MergedDeprecated, Obsoleted: MergedObsoleted) &&
2609 !OverrideOrImpl) {
2610 auto *Avail = ::new (Context) AvailabilityAttr(
2611 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2612 Message, IsStrict, Replacement, Priority);
2613 Avail->setImplicit(Implicit);
2614 return Avail;
2615 }
2616 return nullptr;
2617}
2618
2619static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2620 if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2621 Val: D)) {
2622 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2623 << AL;
2624 return;
2625 }
2626
2627 if (!AL.checkExactlyNumArgs(S, Num: 1))
2628 return;
2629 IdentifierLoc *Platform = AL.getArgAsIdent(Arg: 0);
2630
2631 IdentifierInfo *II = Platform->Ident;
2632 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2633 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2634 << Platform->Ident;
2635
2636 auto *ND = dyn_cast<NamedDecl>(Val: D);
2637 if (!ND) // We warned about this already, so just return.
2638 return;
2639
2640 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2641 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2642 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2643 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2644 bool IsStrict = AL.getStrictLoc().isValid();
2645 StringRef Str;
2646 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getMessageExpr()))
2647 Str = SE->getString();
2648 StringRef Replacement;
2649 if (const auto *SE =
2650 dyn_cast_if_present<StringLiteral>(Val: AL.getReplacementExpr()))
2651 Replacement = SE->getString();
2652
2653 if (II->isStr(Str: "swift")) {
2654 if (Introduced.isValid() || Obsoleted.isValid() ||
2655 (!IsUnavailable && !Deprecated.isValid())) {
2656 S.Diag(AL.getLoc(),
2657 diag::warn_availability_swift_unavailable_deprecated_only);
2658 return;
2659 }
2660 }
2661
2662 if (II->isStr(Str: "fuchsia")) {
2663 std::optional<unsigned> Min, Sub;
2664 if ((Min = Introduced.Version.getMinor()) ||
2665 (Sub = Introduced.Version.getSubminor())) {
2666 S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
2667 return;
2668 }
2669 }
2670
2671 int PriorityModifier = AL.isPragmaClangAttribute()
2672 ? Sema::AP_PragmaClangAttribute
2673 : Sema::AP_Explicit;
2674 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2675 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2676 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2677 Sema::AMK_None, PriorityModifier);
2678 if (NewAttr)
2679 D->addAttr(A: NewAttr);
2680
2681 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2682 // matches before the start of the watchOS platform.
2683 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2684 IdentifierInfo *NewII = nullptr;
2685 if (II->getName() == "ios")
2686 NewII = &S.Context.Idents.get(Name: "watchos");
2687 else if (II->getName() == "ios_app_extension")
2688 NewII = &S.Context.Idents.get(Name: "watchos_app_extension");
2689
2690 if (NewII) {
2691 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2692 const auto *IOSToWatchOSMapping =
2693 SDKInfo ? SDKInfo->getVersionMapping(
2694 Kind: DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair())
2695 : nullptr;
2696
2697 auto adjustWatchOSVersion =
2698 [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2699 if (Version.empty())
2700 return Version;
2701 auto MinimumWatchOSVersion = VersionTuple(2, 0);
2702
2703 if (IOSToWatchOSMapping) {
2704 if (auto MappedVersion = IOSToWatchOSMapping->map(
2705 Key: Version, MinimumValue: MinimumWatchOSVersion, MaximumValue: std::nullopt)) {
2706 return *MappedVersion;
2707 }
2708 }
2709
2710 auto Major = Version.getMajor();
2711 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2712 if (NewMajor >= 2) {
2713 if (Version.getMinor()) {
2714 if (Version.getSubminor())
2715 return VersionTuple(NewMajor, *Version.getMinor(),
2716 *Version.getSubminor());
2717 else
2718 return VersionTuple(NewMajor, *Version.getMinor());
2719 }
2720 return VersionTuple(NewMajor);
2721 }
2722
2723 return MinimumWatchOSVersion;
2724 };
2725
2726 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2727 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2728 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2729
2730 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2731 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2732 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2733 Sema::AMK_None,
2734 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2735 if (NewAttr)
2736 D->addAttr(A: NewAttr);
2737 }
2738 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2739 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2740 // matches before the start of the tvOS platform.
2741 IdentifierInfo *NewII = nullptr;
2742 if (II->getName() == "ios")
2743 NewII = &S.Context.Idents.get(Name: "tvos");
2744 else if (II->getName() == "ios_app_extension")
2745 NewII = &S.Context.Idents.get(Name: "tvos_app_extension");
2746
2747 if (NewII) {
2748 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2749 const auto *IOSToTvOSMapping =
2750 SDKInfo ? SDKInfo->getVersionMapping(
2751 Kind: DarwinSDKInfo::OSEnvPair::iOStoTvOSPair())
2752 : nullptr;
2753
2754 auto AdjustTvOSVersion =
2755 [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2756 if (Version.empty())
2757 return Version;
2758
2759 if (IOSToTvOSMapping) {
2760 if (auto MappedVersion = IOSToTvOSMapping->map(
2761 Key: Version, MinimumValue: VersionTuple(0, 0), MaximumValue: std::nullopt)) {
2762 return *MappedVersion;
2763 }
2764 }
2765 return Version;
2766 };
2767
2768 auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
2769 auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
2770 auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
2771
2772 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2773 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2774 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2775 Sema::AMK_None,
2776 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2777 if (NewAttr)
2778 D->addAttr(A: NewAttr);
2779 }
2780 } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2781 llvm::Triple::IOS &&
2782 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2783 auto GetSDKInfo = [&]() {
2784 return S.getDarwinSDKInfoForAvailabilityChecking(Loc: AL.getRange().getBegin(),
2785 Platform: "macOS");
2786 };
2787
2788 // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2789 IdentifierInfo *NewII = nullptr;
2790 if (II->getName() == "ios")
2791 NewII = &S.Context.Idents.get(Name: "maccatalyst");
2792 else if (II->getName() == "ios_app_extension")
2793 NewII = &S.Context.Idents.get(Name: "maccatalyst_app_extension");
2794 if (NewII) {
2795 auto MinMacCatalystVersion = [](const VersionTuple &V) {
2796 if (V.empty())
2797 return V;
2798 if (V.getMajor() < 13 ||
2799 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2800 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2801 return V;
2802 };
2803 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2804 ND, AL, NewII, true /*Implicit*/,
2805 MinMacCatalystVersion(Introduced.Version),
2806 MinMacCatalystVersion(Deprecated.Version),
2807 MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2808 IsStrict, Replacement, Sema::AMK_None,
2809 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2810 if (NewAttr)
2811 D->addAttr(A: NewAttr);
2812 } else if (II->getName() == "macos" && GetSDKInfo() &&
2813 (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2814 !Obsoleted.Version.empty())) {
2815 if (const auto *MacOStoMacCatalystMapping =
2816 GetSDKInfo()->getVersionMapping(
2817 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
2818 // Infer Mac Catalyst availability from the macOS availability attribute
2819 // if it has versioned availability. Don't infer 'unavailable'. This
2820 // inferred availability has lower priority than the other availability
2821 // attributes that are inferred from 'ios'.
2822 NewII = &S.Context.Idents.get(Name: "maccatalyst");
2823 auto RemapMacOSVersion =
2824 [&](const VersionTuple &V) -> std::optional<VersionTuple> {
2825 if (V.empty())
2826 return std::nullopt;
2827 // API_TO_BE_DEPRECATED is 100000.
2828 if (V.getMajor() == 100000)
2829 return VersionTuple(100000);
2830 // The minimum iosmac version is 13.1
2831 return MacOStoMacCatalystMapping->map(Key: V, MinimumValue: VersionTuple(13, 1),
2832 MaximumValue: std::nullopt);
2833 };
2834 std::optional<VersionTuple> NewIntroduced =
2835 RemapMacOSVersion(Introduced.Version),
2836 NewDeprecated =
2837 RemapMacOSVersion(Deprecated.Version),
2838 NewObsoleted =
2839 RemapMacOSVersion(Obsoleted.Version);
2840 if (NewIntroduced || NewDeprecated || NewObsoleted) {
2841 auto VersionOrEmptyVersion =
2842 [](const std::optional<VersionTuple> &V) -> VersionTuple {
2843 return V ? *V : VersionTuple();
2844 };
2845 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2846 ND, AL, NewII, true /*Implicit*/,
2847 VersionOrEmptyVersion(NewIntroduced),
2848 VersionOrEmptyVersion(NewDeprecated),
2849 VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2850 IsStrict, Replacement, Sema::AMK_None,
2851 PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2852 Sema::AP_InferredFromOtherPlatform);
2853 if (NewAttr)
2854 D->addAttr(A: NewAttr);
2855 }
2856 }
2857 }
2858 }
2859}
2860
2861static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2862 const ParsedAttr &AL) {
2863 if (!AL.checkAtLeastNumArgs(S, Num: 1) || !AL.checkAtMostNumArgs(S, Num: 4))
2864 return;
2865
2866 StringRef Language;
2867 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getArgAsExpr(Arg: 0)))
2868 Language = SE->getString();
2869 StringRef DefinedIn;
2870 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getArgAsExpr(Arg: 1)))
2871 DefinedIn = SE->getString();
2872 bool IsGeneratedDeclaration = AL.getArgAsIdent(Arg: 2) != nullptr;
2873 StringRef USR;
2874 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getArgAsExpr(Arg: 3)))
2875 USR = SE->getString();
2876
2877 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2878 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration, USR));
2879}
2880
2881template <class T>
2882static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2883 typename T::VisibilityType value) {
2884 T *existingAttr = D->getAttr<T>();
2885 if (existingAttr) {
2886 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2887 if (existingValue == value)
2888 return nullptr;
2889 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2890 S.Diag(CI.getLoc(), diag::note_previous_attribute);
2891 D->dropAttr<T>();
2892 }
2893 return ::new (S.Context) T(S.Context, CI, value);
2894}
2895
2896VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2897 const AttributeCommonInfo &CI,
2898 VisibilityAttr::VisibilityType Vis) {
2899 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2900}
2901
2902TypeVisibilityAttr *
2903Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2904 TypeVisibilityAttr::VisibilityType Vis) {
2905 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2906}
2907
2908static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2909 bool isTypeVisibility) {
2910 // Visibility attributes don't mean anything on a typedef.
2911 if (isa<TypedefNameDecl>(Val: D)) {
2912 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2913 return;
2914 }
2915
2916 // 'type_visibility' can only go on a type or namespace.
2917 if (isTypeVisibility && !(isa<TagDecl>(Val: D) || isa<ObjCInterfaceDecl>(Val: D) ||
2918 isa<NamespaceDecl>(Val: D))) {
2919 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2920 << AL << AL.isRegularKeywordAttribute() << ExpectedTypeOrNamespace;
2921 return;
2922 }
2923
2924 // Check that the argument is a string literal.
2925 StringRef TypeStr;
2926 SourceLocation LiteralLoc;
2927 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: TypeStr, ArgLocation: &LiteralLoc))
2928 return;
2929
2930 VisibilityAttr::VisibilityType type;
2931 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2932 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2933 << TypeStr;
2934 return;
2935 }
2936
2937 // Complain about attempts to use protected visibility on targets
2938 // (like Darwin) that don't support it.
2939 if (type == VisibilityAttr::Protected &&
2940 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2941 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2942 type = VisibilityAttr::Default;
2943 }
2944
2945 Attr *newAttr;
2946 if (isTypeVisibility) {
2947 newAttr = S.mergeTypeVisibilityAttr(
2948 D, AL, (TypeVisibilityAttr::VisibilityType)type);
2949 } else {
2950 newAttr = S.mergeVisibilityAttr(D, AL, type);
2951 }
2952 if (newAttr)
2953 D->addAttr(A: newAttr);
2954}
2955
2956static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2957 // objc_direct cannot be set on methods declared in the context of a protocol
2958 if (isa<ObjCProtocolDecl>(Val: D->getDeclContext())) {
2959 S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2960 return;
2961 }
2962
2963 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2964 handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2965 } else {
2966 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2967 }
2968}
2969
2970static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
2971 const ParsedAttr &AL) {
2972 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
2973 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2974 } else {
2975 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2976 }
2977}
2978
2979static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2980 const auto *M = cast<ObjCMethodDecl>(Val: D);
2981 if (!AL.isArgIdent(Arg: 0)) {
2982 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2983 << AL << 1 << AANT_ArgumentIdentifier;
2984 return;
2985 }
2986
2987 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
2988 ObjCMethodFamilyAttr::FamilyKind F;
2989 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2990 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2991 return;
2992 }
2993
2994 if (F == ObjCMethodFamilyAttr::OMF_init &&
2995 !M->getReturnType()->isObjCObjectPointerType()) {
2996 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2997 << M->getReturnType();
2998 // Ignore the attribute.
2999 return;
3000 }
3001
3002 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
3003}
3004
3005static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
3006 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
3007 QualType T = TD->getUnderlyingType();
3008 if (!T->isCARCBridgableType()) {
3009 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
3010 return;
3011 }
3012 }
3013 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(Val: D)) {
3014 QualType T = PD->getType();
3015 if (!T->isCARCBridgableType()) {
3016 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
3017 return;
3018 }
3019 }
3020 else {
3021 // It is okay to include this attribute on properties, e.g.:
3022 //
3023 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
3024 //
3025 // In this case it follows tradition and suppresses an error in the above
3026 // case.
3027 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
3028 }
3029 D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
3030}
3031
3032static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
3033 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
3034 QualType T = TD->getUnderlyingType();
3035 if (!T->isObjCObjectPointerType()) {
3036 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
3037 return;
3038 }
3039 } else {
3040 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
3041 return;
3042 }
3043 D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
3044}
3045
3046static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3047 if (!AL.isArgIdent(Arg: 0)) {
3048 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3049 << AL << 1 << AANT_ArgumentIdentifier;
3050 return;
3051 }
3052
3053 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->Ident;
3054 BlocksAttr::BlockType type;
3055 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
3056 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3057 return;
3058 }
3059
3060 D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
3061}
3062
3063static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3064 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
3065 if (AL.getNumArgs() > 0) {
3066 Expr *E = AL.getArgAsExpr(Arg: 0);
3067 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3068 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(Ctx: S.Context))) {
3069 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3070 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3071 return;
3072 }
3073
3074 if (Idx->isSigned() && Idx->isNegative()) {
3075 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
3076 << E->getSourceRange();
3077 return;
3078 }
3079
3080 sentinel = Idx->getZExtValue();
3081 }
3082
3083 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
3084 if (AL.getNumArgs() > 1) {
3085 Expr *E = AL.getArgAsExpr(Arg: 1);
3086 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3087 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(Ctx: S.Context))) {
3088 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3089 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3090 return;
3091 }
3092 nullPos = Idx->getZExtValue();
3093
3094 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
3095 // FIXME: This error message could be improved, it would be nice
3096 // to say what the bounds actually are.
3097 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
3098 << E->getSourceRange();
3099 return;
3100 }
3101 }
3102
3103 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
3104 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
3105 if (isa<FunctionNoProtoType>(Val: FT)) {
3106 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
3107 return;
3108 }
3109
3110 if (!cast<FunctionProtoType>(Val: FT)->isVariadic()) {
3111 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3112 return;
3113 }
3114 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
3115 if (!MD->isVariadic()) {
3116 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3117 return;
3118 }
3119 } else if (const auto *BD = dyn_cast<BlockDecl>(Val: D)) {
3120 if (!BD->isVariadic()) {
3121 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
3122 return;
3123 }
3124 } else if (const auto *V = dyn_cast<VarDecl>(Val: D)) {
3125 QualType Ty = V->getType();
3126 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
3127 const FunctionType *FT = Ty->isFunctionPointerType()
3128 ? D->getFunctionType()
3129 : Ty->castAs<BlockPointerType>()
3130 ->getPointeeType()
3131 ->castAs<FunctionType>();
3132 if (!cast<FunctionProtoType>(Val: FT)->isVariadic()) {
3133 int m = Ty->isFunctionPointerType() ? 0 : 1;
3134 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
3135 return;
3136 }
3137 } else {
3138 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3139 << AL << AL.isRegularKeywordAttribute()
3140 << ExpectedFunctionMethodOrBlock;
3141 return;
3142 }
3143 } else {
3144 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3145 << AL << AL.isRegularKeywordAttribute()
3146 << ExpectedFunctionMethodOrBlock;
3147 return;
3148 }
3149 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
3150}
3151
3152static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
3153 if (D->getFunctionType() &&
3154 D->getFunctionType()->getReturnType()->isVoidType() &&
3155 !isa<CXXConstructorDecl>(Val: D)) {
3156 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
3157 return;
3158 }
3159 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
3160 if (MD->getReturnType()->isVoidType()) {
3161 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
3162 return;
3163 }
3164
3165 StringRef Str;
3166 if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
3167 // The standard attribute cannot be applied to variable declarations such
3168 // as a function pointer.
3169 if (isa<VarDecl>(D))
3170 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
3171 << AL << AL.isRegularKeywordAttribute()
3172 << "functions, classes, or enumerations";
3173
3174 // If this is spelled as the standard C++17 attribute, but not in C++17,
3175 // warn about using it as an extension. If there are attribute arguments,
3176 // then claim it's a C++20 extension instead.
3177 // FIXME: If WG14 does not seem likely to adopt the same feature, add an
3178 // extension warning for C23 mode.
3179 const LangOptions &LO = S.getLangOpts();
3180 if (AL.getNumArgs() == 1) {
3181 if (LO.CPlusPlus && !LO.CPlusPlus20)
3182 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
3183
3184 // Since this is spelled [[nodiscard]], get the optional string
3185 // literal. If in C++ mode, but not in C++20 mode, diagnose as an
3186 // extension.
3187 // FIXME: C23 should support this feature as well, even as an extension.
3188 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: nullptr))
3189 return;
3190 } else if (LO.CPlusPlus && !LO.CPlusPlus17)
3191 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
3192 }
3193
3194 if ((!AL.isGNUAttribute() &&
3195 !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
3196 isa<TypedefNameDecl>(Val: D)) {
3197 S.Diag(AL.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling)
3198 << AL.isGNUScope();
3199 return;
3200 }
3201
3202 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
3203}
3204
3205static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3206 // weak_import only applies to variable & function declarations.
3207 bool isDef = false;
3208 if (!D->canBeWeakImported(IsDefinition&: isDef)) {
3209 if (isDef)
3210 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
3211 << "weak_import";
3212 else if (isa<ObjCPropertyDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
3213 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
3214 (isa<ObjCInterfaceDecl>(Val: D) || isa<EnumDecl>(Val: D)))) {
3215 // Nothing to warn about here.
3216 } else
3217 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3218 << AL << AL.isRegularKeywordAttribute() << ExpectedVariableOrFunction;
3219
3220 return;
3221 }
3222
3223 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
3224}
3225
3226// Handles reqd_work_group_size and work_group_size_hint.
3227template <typename WorkGroupAttr>
3228static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3229 uint32_t WGSize[3];
3230 for (unsigned i = 0; i < 3; ++i) {
3231 const Expr *E = AL.getArgAsExpr(Arg: i);
3232 if (!checkUInt32Argument(S, AI: AL, Expr: E, Val&: WGSize[i], Idx: i,
3233 /*StrictlyUnsigned=*/true))
3234 return;
3235 if (WGSize[i] == 0) {
3236 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3237 << AL << E->getSourceRange();
3238 return;
3239 }
3240 }
3241
3242 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3243 if (Existing && !(Existing->getXDim() == WGSize[0] &&
3244 Existing->getYDim() == WGSize[1] &&
3245 Existing->getZDim() == WGSize[2]))
3246 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3247
3248 D->addAttr(A: ::new (S.Context)
3249 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3250}
3251
3252// Handles intel_reqd_sub_group_size.
3253static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3254 uint32_t SGSize;
3255 const Expr *E = AL.getArgAsExpr(Arg: 0);
3256 if (!checkUInt32Argument(S, AI: AL, Expr: E, Val&: SGSize))
3257 return;
3258 if (SGSize == 0) {
3259 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3260 << AL << E->getSourceRange();
3261 return;
3262 }
3263
3264 OpenCLIntelReqdSubGroupSizeAttr *Existing =
3265 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3266 if (Existing && Existing->getSubGroupSize() != SGSize)
3267 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3268
3269 D->addAttr(::new (S.Context)
3270 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3271}
3272
3273static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3274 if (!AL.hasParsedType()) {
3275 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3276 return;
3277 }
3278
3279 TypeSourceInfo *ParmTSI = nullptr;
3280 QualType ParmType = S.GetTypeFromParser(Ty: AL.getTypeArg(), TInfo: &ParmTSI);
3281 assert(ParmTSI && "no type source info for attribute argument");
3282
3283 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3284 (ParmType->isBooleanType() ||
3285 !ParmType->isIntegralType(Ctx: S.getASTContext()))) {
3286 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3287 return;
3288 }
3289
3290 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3291 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3292 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3293 return;
3294 }
3295 }
3296
3297 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3298}
3299
3300SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3301 StringRef Name) {
3302 // Explicit or partial specializations do not inherit
3303 // the section attribute from the primary template.
3304 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
3305 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3306 FD->isFunctionTemplateSpecialization())
3307 return nullptr;
3308 }
3309 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3310 if (ExistingAttr->getName() == Name)
3311 return nullptr;
3312 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3313 << 1 /*section*/;
3314 Diag(CI.getLoc(), diag::note_previous_attribute);
3315 return nullptr;
3316 }
3317 return ::new (Context) SectionAttr(Context, CI, Name);
3318}
3319
3320/// Used to implement to perform semantic checking on
3321/// attribute((section("foo"))) specifiers.
3322///
3323/// In this case, "foo" is passed in to be checked. If the section
3324/// specifier is invalid, return an Error that indicates the problem.
3325///
3326/// This is a simple quality of implementation feature to catch errors
3327/// and give good diagnostics in cases when the assembler or code generator
3328/// would otherwise reject the section specifier.
3329llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3330 if (!Context.getTargetInfo().getTriple().isOSDarwin())
3331 return llvm::Error::success();
3332
3333 // Let MCSectionMachO validate this.
3334 StringRef Segment, Section;
3335 unsigned TAA, StubSize;
3336 bool HasTAA;
3337 return llvm::MCSectionMachO::ParseSectionSpecifier(Spec: SecName, Segment, Section,
3338 TAA, TAAParsed&: HasTAA, StubSize);
3339}
3340
3341bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3342 if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3343 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3344 << toString(std::move(E)) << 1 /*'section'*/;
3345 return false;
3346 }
3347 return true;
3348}
3349
3350static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3351 // Make sure that there is a string literal as the sections's single
3352 // argument.
3353 StringRef Str;
3354 SourceLocation LiteralLoc;
3355 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc))
3356 return;
3357
3358 if (!S.checkSectionName(LiteralLoc, SecName: Str))
3359 return;
3360
3361 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3362 if (NewAttr) {
3363 D->addAttr(A: NewAttr);
3364 if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
3365 ObjCPropertyDecl>(Val: D))
3366 S.UnifySection(NewAttr->getName(),
3367 ASTContext::PSF_Execute | ASTContext::PSF_Read,
3368 cast<NamedDecl>(Val: D));
3369 }
3370}
3371
3372static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3373 StringRef Str;
3374 SourceLocation LiteralLoc;
3375 // Check that it is a string.
3376 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc))
3377 return;
3378
3379 llvm::CodeModel::Model CM;
3380 if (!CodeModelAttr::ConvertStrToModel(Str, CM)) {
3381 S.Diag(LiteralLoc, diag::err_attr_codemodel_arg) << Str;
3382 return;
3383 }
3384
3385 D->addAttr(::new (S.Context) CodeModelAttr(S.Context, AL, CM));
3386}
3387
3388// This is used for `__declspec(code_seg("segname"))` on a decl.
3389// `#pragma code_seg("segname")` uses checkSectionName() instead.
3390static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3391 StringRef CodeSegName) {
3392 if (llvm::Error E = S.isValidSectionSpecifier(SecName: CodeSegName)) {
3393 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3394 << toString(std::move(E)) << 0 /*'code-seg'*/;
3395 return false;
3396 }
3397
3398 return true;
3399}
3400
3401CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3402 StringRef Name) {
3403 // Explicit or partial specializations do not inherit
3404 // the code_seg attribute from the primary template.
3405 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
3406 if (FD->isFunctionTemplateSpecialization())
3407 return nullptr;
3408 }
3409 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3410 if (ExistingAttr->getName() == Name)
3411 return nullptr;
3412 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3413 << 0 /*codeseg*/;
3414 Diag(CI.getLoc(), diag::note_previous_attribute);
3415 return nullptr;
3416 }
3417 return ::new (Context) CodeSegAttr(Context, CI, Name);
3418}
3419
3420static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3421 StringRef Str;
3422 SourceLocation LiteralLoc;
3423 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc))
3424 return;
3425 if (!checkCodeSegName(S, LiteralLoc, CodeSegName: Str))
3426 return;
3427 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3428 if (!ExistingAttr->isImplicit()) {
3429 S.Diag(AL.getLoc(),
3430 ExistingAttr->getName() == Str
3431 ? diag::warn_duplicate_codeseg_attribute
3432 : diag::err_conflicting_codeseg_attribute);
3433 return;
3434 }
3435 D->dropAttr<CodeSegAttr>();
3436 }
3437 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3438 D->addAttr(CSA);
3439}
3440
3441// Check for things we'd like to warn about. Multiversioning issues are
3442// handled later in the process, once we know how many exist.
3443bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3444 enum FirstParam { Unsupported, Duplicate, Unknown };
3445 enum SecondParam { None, CPU, Tune };
3446 enum ThirdParam { Target, TargetClones };
3447 if (AttrStr.contains("fpmath="))
3448 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3449 << Unsupported << None << "fpmath=" << Target;
3450
3451 // Diagnose use of tune if target doesn't support it.
3452 if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3453 AttrStr.contains("tune="))
3454 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3455 << Unsupported << None << "tune=" << Target;
3456
3457 ParsedTargetAttr ParsedAttrs =
3458 Context.getTargetInfo().parseTargetAttr(Str: AttrStr);
3459
3460 if (!ParsedAttrs.CPU.empty() &&
3461 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.CPU))
3462 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3463 << Unknown << CPU << ParsedAttrs.CPU << Target;
3464
3465 if (!ParsedAttrs.Tune.empty() &&
3466 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
3467 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3468 << Unknown << Tune << ParsedAttrs.Tune << Target;
3469
3470 if (Context.getTargetInfo().getTriple().isRISCV() &&
3471 ParsedAttrs.Duplicate != "")
3472 return Diag(LiteralLoc, diag::err_duplicate_target_attribute)
3473 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3474
3475 if (ParsedAttrs.Duplicate != "")
3476 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3477 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3478
3479 for (const auto &Feature : ParsedAttrs.Features) {
3480 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3481 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3482 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3483 << Unsupported << None << CurFeature << Target;
3484 }
3485
3486 TargetInfo::BranchProtectionInfo BPI;
3487 StringRef DiagMsg;
3488 if (ParsedAttrs.BranchProtection.empty())
3489 return false;
3490 if (!Context.getTargetInfo().validateBranchProtection(
3491 Spec: ParsedAttrs.BranchProtection, Arch: ParsedAttrs.CPU, BPI, Err&: DiagMsg)) {
3492 if (DiagMsg.empty())
3493 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3494 << Unsupported << None << "branch-protection" << Target;
3495 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3496 << DiagMsg;
3497 }
3498 if (!DiagMsg.empty())
3499 Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
3500
3501 return false;
3502}
3503
3504static bool hasArmStreamingInterface(const FunctionDecl *FD) {
3505 if (const auto *T = FD->getType()->getAs<FunctionProtoType>())
3506 if (T->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)
3507 return true;
3508 return false;
3509}
3510
3511// Check Target Version attrs
3512bool Sema::checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D,
3513 StringRef &AttrStr, bool &isDefault) {
3514 enum FirstParam { Unsupported };
3515 enum SecondParam { None };
3516 enum ThirdParam { Target, TargetClones, TargetVersion };
3517 if (AttrStr.trim() == "default")
3518 isDefault = true;
3519 llvm::SmallVector<StringRef, 8> Features;
3520 AttrStr.split(A&: Features, Separator: "+");
3521 for (auto &CurFeature : Features) {
3522 CurFeature = CurFeature.trim();
3523 if (CurFeature == "default")
3524 continue;
3525 if (!Context.getTargetInfo().validateCpuSupports(CurFeature))
3526 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3527 << Unsupported << None << CurFeature << TargetVersion;
3528 }
3529 if (hasArmStreamingInterface(cast<FunctionDecl>(D)))
3530 return Diag(LiteralLoc, diag::err_sme_streaming_cannot_be_multiversioned);
3531 return false;
3532}
3533
3534static void handleTargetVersionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3535 StringRef Str;
3536 SourceLocation LiteralLoc;
3537 bool isDefault = false;
3538 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc) ||
3539 S.checkTargetVersionAttr(LiteralLoc, D, AttrStr&: Str, isDefault))
3540 return;
3541 // Do not create default only target_version attribute
3542 if (!isDefault) {
3543 TargetVersionAttr *NewAttr =
3544 ::new (S.Context) TargetVersionAttr(S.Context, AL, Str);
3545 D->addAttr(A: NewAttr);
3546 }
3547}
3548
3549static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3550 StringRef Str;
3551 SourceLocation LiteralLoc;
3552 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc) ||
3553 S.checkTargetAttr(LiteralLoc, AttrStr: Str))
3554 return;
3555
3556 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3557 D->addAttr(NewAttr);
3558}
3559
3560bool Sema::checkTargetClonesAttrString(
3561 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
3562 Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
3563 SmallVectorImpl<SmallString<64>> &StringsBuffer) {
3564 enum FirstParam { Unsupported, Duplicate, Unknown };
3565 enum SecondParam { None, CPU, Tune };
3566 enum ThirdParam { Target, TargetClones };
3567 HasCommas = HasCommas || Str.contains(C: ',');
3568 const TargetInfo &TInfo = Context.getTargetInfo();
3569 // Warn on empty at the beginning of a string.
3570 if (Str.size() == 0)
3571 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3572 << Unsupported << None << "" << TargetClones;
3573
3574 std::pair<StringRef, StringRef> Parts = {{}, Str};
3575 while (!Parts.second.empty()) {
3576 Parts = Parts.second.split(Separator: ',');
3577 StringRef Cur = Parts.first.trim();
3578 SourceLocation CurLoc =
3579 Literal->getLocationOfByte(ByteNo: Cur.data() - Literal->getString().data(),
3580 SM: getSourceManager(), Features: getLangOpts(), Target: TInfo);
3581
3582 bool DefaultIsDupe = false;
3583 bool HasCodeGenImpact = false;
3584 if (Cur.empty())
3585 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3586 << Unsupported << None << "" << TargetClones;
3587
3588 if (TInfo.getTriple().isAArch64()) {
3589 // AArch64 target clones specific
3590 if (Cur == "default") {
3591 DefaultIsDupe = HasDefault;
3592 HasDefault = true;
3593 if (llvm::is_contained(Range&: StringsBuffer, Element: Cur) || DefaultIsDupe)
3594 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3595 else
3596 StringsBuffer.push_back(Elt: Cur);
3597 } else {
3598 std::pair<StringRef, StringRef> CurParts = {{}, Cur};
3599 llvm::SmallVector<StringRef, 8> CurFeatures;
3600 while (!CurParts.second.empty()) {
3601 CurParts = CurParts.second.split(Separator: '+');
3602 StringRef CurFeature = CurParts.first.trim();
3603 if (!TInfo.validateCpuSupports(Name: CurFeature)) {
3604 Diag(CurLoc, diag::warn_unsupported_target_attribute)
3605 << Unsupported << None << CurFeature << TargetClones;
3606 continue;
3607 }
3608 if (TInfo.doesFeatureAffectCodeGen(Feature: CurFeature))
3609 HasCodeGenImpact = true;
3610 CurFeatures.push_back(Elt: CurFeature);
3611 }
3612 // Canonize TargetClones Attributes
3613 llvm::sort(C&: CurFeatures);
3614 SmallString<64> Res;
3615 for (auto &CurFeat : CurFeatures) {
3616 if (!Res.equals(RHS: ""))
3617 Res.append(RHS: "+");
3618 Res.append(RHS: CurFeat);
3619 }
3620 if (llvm::is_contained(Range&: StringsBuffer, Element: Res) || DefaultIsDupe)
3621 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3622 else if (!HasCodeGenImpact)
3623 // Ignore features in target_clone attribute that don't impact
3624 // code generation
3625 Diag(CurLoc, diag::warn_target_clone_no_impact_options);
3626 else if (!Res.empty()) {
3627 StringsBuffer.push_back(Elt: Res);
3628 HasNotDefault = true;
3629 }
3630 }
3631 if (hasArmStreamingInterface(cast<FunctionDecl>(D)))
3632 return Diag(LiteralLoc,
3633 diag::err_sme_streaming_cannot_be_multiversioned);
3634 } else {
3635 // Other targets ( currently X86 )
3636 if (Cur.starts_with(Prefix: "arch=")) {
3637 if (!Context.getTargetInfo().isValidCPUName(
3638 Cur.drop_front(sizeof("arch=") - 1)))
3639 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3640 << Unsupported << CPU << Cur.drop_front(sizeof("arch=") - 1)
3641 << TargetClones;
3642 } else if (Cur == "default") {
3643 DefaultIsDupe = HasDefault;
3644 HasDefault = true;
3645 } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
3646 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3647 << Unsupported << None << Cur << TargetClones;
3648 if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3649 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3650 // Note: Add even if there are duplicates, since it changes name mangling.
3651 StringsBuffer.push_back(Elt: Cur);
3652 }
3653 }
3654 if (Str.rtrim().ends_with(","))
3655 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3656 << Unsupported << None << "" << TargetClones;
3657 return false;
3658}
3659
3660static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3661 if (S.Context.getTargetInfo().getTriple().isAArch64() &&
3662 !S.Context.getTargetInfo().hasFeature(Feature: "fmv"))
3663 return;
3664
3665 // Ensure we don't combine these with themselves, since that causes some
3666 // confusing behavior.
3667 if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
3668 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
3669 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
3670 return;
3671 }
3672 if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
3673 return;
3674
3675 SmallVector<StringRef, 2> Strings;
3676 SmallVector<SmallString<64>, 2> StringsBuffer;
3677 bool HasCommas = false, HasDefault = false, HasNotDefault = false;
3678
3679 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
3680 StringRef CurStr;
3681 SourceLocation LiteralLoc;
3682 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: CurStr, ArgLocation: &LiteralLoc) ||
3683 S.checkTargetClonesAttrString(
3684 LiteralLoc, Str: CurStr,
3685 Literal: cast<StringLiteral>(Val: AL.getArgAsExpr(Arg: I)->IgnoreParenCasts()), D,
3686 HasDefault, HasCommas, HasNotDefault, StringsBuffer))
3687 return;
3688 }
3689 for (auto &SmallStr : StringsBuffer)
3690 Strings.push_back(Elt: SmallStr.str());
3691
3692 if (HasCommas && AL.getNumArgs() > 1)
3693 S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
3694
3695 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasDefault) {
3696 // Add default attribute if there is no one
3697 HasDefault = true;
3698 Strings.push_back(Elt: "default");
3699 }
3700
3701 if (!HasDefault) {
3702 S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
3703 return;
3704 }
3705
3706 // FIXME: We could probably figure out how to get this to work for lambdas
3707 // someday.
3708 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
3709 if (MD->getParent()->isLambda()) {
3710 S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
3711 << static_cast<unsigned>(MultiVersionKind::TargetClones)
3712 << /*Lambda*/ 9;
3713 return;
3714 }
3715 }
3716
3717 // No multiversion if we have default version only.
3718 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasNotDefault)
3719 return;
3720
3721 cast<FunctionDecl>(Val: D)->setIsMultiVersion();
3722 TargetClonesAttr *NewAttr = ::new (S.Context)
3723 TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
3724 D->addAttr(A: NewAttr);
3725}
3726
3727static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3728 Expr *E = AL.getArgAsExpr(Arg: 0);
3729 uint32_t VecWidth;
3730 if (!checkUInt32Argument(S, AI: AL, Expr: E, Val&: VecWidth)) {
3731 AL.setInvalid();
3732 return;
3733 }
3734
3735 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3736 if (Existing && Existing->getVectorWidth() != VecWidth) {
3737 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3738 return;
3739 }
3740
3741 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3742}
3743
3744static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3745 Expr *E = AL.getArgAsExpr(Arg: 0);
3746 SourceLocation Loc = E->getExprLoc();
3747 FunctionDecl *FD = nullptr;
3748 DeclarationNameInfo NI;
3749
3750 // gcc only allows for simple identifiers. Since we support more than gcc, we
3751 // will warn the user.
3752 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
3753 if (DRE->hasQualifier())
3754 S.Diag(Loc, diag::warn_cleanup_ext);
3755 FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
3756 NI = DRE->getNameInfo();
3757 if (!FD) {
3758 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3759 << NI.getName();
3760 return;
3761 }
3762 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
3763 if (ULE->hasExplicitTemplateArgs())
3764 S.Diag(Loc, diag::warn_cleanup_ext);
3765 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3766 NI = ULE->getNameInfo();
3767 if (!FD) {
3768 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3769 << NI.getName();
3770 if (ULE->getType() == S.Context.OverloadTy)
3771 S.NoteAllOverloadCandidates(ULE);
3772 return;
3773 }
3774 } else {
3775 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3776 return;
3777 }
3778
3779 if (FD->getNumParams() != 1) {
3780 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3781 << NI.getName();
3782 return;
3783 }
3784
3785 // We're currently more strict than GCC about what function types we accept.
3786 // If this ever proves to be a problem it should be easy to fix.
3787 QualType Ty = S.Context.getPointerType(cast<VarDecl>(Val: D)->getType());
3788 QualType ParamTy = FD->getParamDecl(i: 0)->getType();
3789 if (S.CheckAssignmentConstraints(FD->getParamDecl(i: 0)->getLocation(),
3790 ParamTy, Ty) != Sema::Compatible) {
3791 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3792 << NI.getName() << ParamTy << Ty;
3793 return;
3794 }
3795
3796 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3797}
3798
3799static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3800 const ParsedAttr &AL) {
3801 if (!AL.isArgIdent(Arg: 0)) {
3802 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3803 << AL << 0 << AANT_ArgumentIdentifier;
3804 return;
3805 }
3806
3807 EnumExtensibilityAttr::Kind ExtensibilityKind;
3808 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->Ident;
3809 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3810 ExtensibilityKind)) {
3811 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3812 return;
3813 }
3814
3815 D->addAttr(::new (S.Context)
3816 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3817}
3818
3819/// Handle __attribute__((format_arg((idx)))) attribute based on
3820/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3821static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3822 const Expr *IdxExpr = AL.getArgAsExpr(Arg: 0);
3823 ParamIdx Idx;
3824 if (!checkFunctionOrMethodParameterIndex(S, D, AI: AL, AttrArgNum: 1, IdxExpr, Idx))
3825 return;
3826
3827 // Make sure the format string is really a string.
3828 QualType Ty = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
3829
3830 bool NotNSStringTy = !isNSStringType(T: Ty, Ctx&: S.Context);
3831 if (NotNSStringTy &&
3832 !isCFStringType(T: Ty, Ctx&: S.Context) &&
3833 (!Ty->isPointerType() ||
3834 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3835 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3836 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3837 return;
3838 }
3839 Ty = getFunctionOrMethodResultType(D);
3840 // replace instancetype with the class type
3841 auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
3842 if (Ty->getAs<TypedefType>() == Instancetype)
3843 if (auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
3844 if (auto *Interface = OMD->getClassInterface())
3845 Ty = S.Context.getObjCObjectPointerType(
3846 OIT: QualType(Interface->getTypeForDecl(), 0));
3847 if (!isNSStringType(T: Ty, Ctx&: S.Context, /*AllowNSAttributedString=*/true) &&
3848 !isCFStringType(T: Ty, Ctx&: S.Context) &&
3849 (!Ty->isPointerType() ||
3850 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3851 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3852 << (NotNSStringTy ? "string type" : "NSString")
3853 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3854 return;
3855 }
3856
3857 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3858}
3859
3860enum FormatAttrKind {
3861 CFStringFormat,
3862 NSStringFormat,
3863 StrftimeFormat,
3864 SupportedFormat,
3865 IgnoredFormat,
3866 InvalidFormat
3867};
3868
3869/// getFormatAttrKind - Map from format attribute names to supported format
3870/// types.
3871static FormatAttrKind getFormatAttrKind(StringRef Format) {
3872 return llvm::StringSwitch<FormatAttrKind>(Format)
3873 // Check for formats that get handled specially.
3874 .Case(S: "NSString", Value: NSStringFormat)
3875 .Case(S: "CFString", Value: CFStringFormat)
3876 .Case(S: "strftime", Value: StrftimeFormat)
3877
3878 // Otherwise, check for supported formats.
3879 .Cases(S0: "scanf", S1: "printf", S2: "printf0", S3: "strfmon", Value: SupportedFormat)
3880 .Cases(S0: "cmn_err", S1: "vcmn_err", S2: "zcmn_err", Value: SupportedFormat)
3881 .Case(S: "kprintf", Value: SupportedFormat) // OpenBSD.
3882 .Case(S: "freebsd_kprintf", Value: SupportedFormat) // FreeBSD.
3883 .Case(S: "os_trace", Value: SupportedFormat)
3884 .Case(S: "os_log", Value: SupportedFormat)
3885
3886 .Cases(S0: "gcc_diag", S1: "gcc_cdiag", S2: "gcc_cxxdiag", S3: "gcc_tdiag", Value: IgnoredFormat)
3887 .Default(Value: InvalidFormat);
3888}
3889
3890/// Handle __attribute__((init_priority(priority))) attributes based on
3891/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3892static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3893 if (!S.getLangOpts().CPlusPlus) {
3894 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3895 return;
3896 }
3897
3898 if (S.getLangOpts().HLSL) {
3899 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
3900 return;
3901 }
3902
3903 if (S.getCurFunctionOrMethodDecl()) {
3904 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3905 AL.setInvalid();
3906 return;
3907 }
3908 QualType T = cast<VarDecl>(Val: D)->getType();
3909 if (S.Context.getAsArrayType(T))
3910 T = S.Context.getBaseElementType(QT: T);
3911 if (!T->getAs<RecordType>()) {
3912 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3913 AL.setInvalid();
3914 return;
3915 }
3916
3917 Expr *E = AL.getArgAsExpr(Arg: 0);
3918 uint32_t prioritynum;
3919 if (!checkUInt32Argument(S, AI: AL, Expr: E, Val&: prioritynum)) {
3920 AL.setInvalid();
3921 return;
3922 }
3923
3924 // Only perform the priority check if the attribute is outside of a system
3925 // header. Values <= 100 are reserved for the implementation, and libc++
3926 // benefits from being able to specify values in that range.
3927 if ((prioritynum < 101 || prioritynum > 65535) &&
3928 !S.getSourceManager().isInSystemHeader(Loc: AL.getLoc())) {
3929 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3930 << E->getSourceRange() << AL << 101 << 65535;
3931 AL.setInvalid();
3932 return;
3933 }
3934 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3935}
3936
3937ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3938 StringRef NewUserDiagnostic) {
3939 if (const auto *EA = D->getAttr<ErrorAttr>()) {
3940 std::string NewAttr = CI.getNormalizedFullName();
3941 assert((NewAttr == "error" || NewAttr == "warning") &&
3942 "unexpected normalized full name");
3943 bool Match = (EA->isError() && NewAttr == "error") ||
3944 (EA->isWarning() && NewAttr == "warning");
3945 if (!Match) {
3946 Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3947 << CI << EA
3948 << (CI.isRegularKeywordAttribute() ||
3949 EA->isRegularKeywordAttribute());
3950 Diag(CI.getLoc(), diag::note_conflicting_attribute);
3951 return nullptr;
3952 }
3953 if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3954 Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3955 Diag(EA->getLoc(), diag::note_previous_attribute);
3956 }
3957 D->dropAttr<ErrorAttr>();
3958 }
3959 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3960}
3961
3962FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3963 IdentifierInfo *Format, int FormatIdx,
3964 int FirstArg) {
3965 // Check whether we already have an equivalent format attribute.
3966 for (auto *F : D->specific_attrs<FormatAttr>()) {
3967 if (F->getType() == Format &&
3968 F->getFormatIdx() == FormatIdx &&
3969 F->getFirstArg() == FirstArg) {
3970 // If we don't have a valid location for this attribute, adopt the
3971 // location.
3972 if (F->getLocation().isInvalid())
3973 F->setRange(CI.getRange());
3974 return nullptr;
3975 }
3976 }
3977
3978 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3979}
3980
3981/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3982/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3983static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3984 if (!AL.isArgIdent(Arg: 0)) {
3985 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3986 << AL << 1 << AANT_ArgumentIdentifier;
3987 return;
3988 }
3989
3990 // In C++ the implicit 'this' function parameter also counts, and they are
3991 // counted from one.
3992 bool HasImplicitThisParam = isInstanceMethod(D);
3993 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3994
3995 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->Ident;
3996 StringRef Format = II->getName();
3997
3998 if (normalizeName(AttrName&: Format)) {
3999 // If we've modified the string name, we need a new identifier for it.
4000 II = &S.Context.Idents.get(Name: Format);
4001 }
4002
4003 // Check for supported formats.
4004 FormatAttrKind Kind = getFormatAttrKind(Format);
4005
4006 if (Kind == IgnoredFormat)
4007 return;
4008
4009 if (Kind == InvalidFormat) {
4010 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
4011 << AL << II->getName();
4012 return;
4013 }
4014
4015 // checks for the 2nd argument
4016 Expr *IdxExpr = AL.getArgAsExpr(Arg: 1);
4017 uint32_t Idx;
4018 if (!checkUInt32Argument(S, AI: AL, Expr: IdxExpr, Val&: Idx, Idx: 2))
4019 return;
4020
4021 if (Idx < 1 || Idx > NumArgs) {
4022 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4023 << AL << 2 << IdxExpr->getSourceRange();
4024 return;
4025 }
4026
4027 // FIXME: Do we need to bounds check?
4028 unsigned ArgIdx = Idx - 1;
4029
4030 if (HasImplicitThisParam) {
4031 if (ArgIdx == 0) {
4032 S.Diag(AL.getLoc(),
4033 diag::err_format_attribute_implicit_this_format_string)
4034 << IdxExpr->getSourceRange();
4035 return;
4036 }
4037 ArgIdx--;
4038 }
4039
4040 // make sure the format string is really a string
4041 QualType Ty = getFunctionOrMethodParamType(D, Idx: ArgIdx);
4042
4043 if (!isNSStringType(T: Ty, Ctx&: S.Context, AllowNSAttributedString: true) &&
4044 !isCFStringType(T: Ty, Ctx&: S.Context) &&
4045 (!Ty->isPointerType() ||
4046 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
4047 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
4048 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx);
4049 return;
4050 }
4051
4052 // check the 3rd argument
4053 Expr *FirstArgExpr = AL.getArgAsExpr(Arg: 2);
4054 uint32_t FirstArg;
4055 if (!checkUInt32Argument(S, AI: AL, Expr: FirstArgExpr, Val&: FirstArg, Idx: 3))
4056 return;
4057
4058 // FirstArg == 0 is is always valid.
4059 if (FirstArg != 0) {
4060 if (Kind == StrftimeFormat) {
4061 // If the kind is strftime, FirstArg must be 0 because strftime does not
4062 // use any variadic arguments.
4063 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
4064 << FirstArgExpr->getSourceRange()
4065 << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(), "0");
4066 return;
4067 } else if (isFunctionOrMethodVariadic(D)) {
4068 // Else, if the function is variadic, then FirstArg must be 0 or the
4069 // "position" of the ... parameter. It's unusual to use 0 with variadic
4070 // functions, so the fixit proposes the latter.
4071 if (FirstArg != NumArgs + 1) {
4072 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4073 << AL << 3 << FirstArgExpr->getSourceRange()
4074 << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(),
4075 std::to_string(NumArgs + 1));
4076 return;
4077 }
4078 } else {
4079 // Inescapable GCC compatibility diagnostic.
4080 S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
4081 if (FirstArg <= Idx) {
4082 // Else, the function is not variadic, and FirstArg must be 0 or any
4083 // parameter after the format parameter. We don't offer a fixit because
4084 // there are too many possible good values.
4085 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4086 << AL << 3 << FirstArgExpr->getSourceRange();
4087 return;
4088 }
4089 }
4090 }
4091
4092 FormatAttr *NewAttr = S.mergeFormatAttr(D, CI: AL, Format: II, FormatIdx: Idx, FirstArg);
4093 if (NewAttr)
4094 D->addAttr(NewAttr);
4095}
4096
4097/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
4098static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4099 // The index that identifies the callback callee is mandatory.
4100 if (AL.getNumArgs() == 0) {
4101 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
4102 << AL.getRange();
4103 return;
4104 }
4105
4106 bool HasImplicitThisParam = isInstanceMethod(D);
4107 int32_t NumArgs = getFunctionOrMethodNumParams(D);
4108
4109 FunctionDecl *FD = D->getAsFunction();
4110 assert(FD && "Expected a function declaration!");
4111
4112 llvm::StringMap<int> NameIdxMapping;
4113 NameIdxMapping["__"] = -1;
4114
4115 NameIdxMapping["this"] = 0;
4116
4117 int Idx = 1;
4118 for (const ParmVarDecl *PVD : FD->parameters())
4119 NameIdxMapping[PVD->getName()] = Idx++;
4120
4121 auto UnknownName = NameIdxMapping.end();
4122
4123 SmallVector<int, 8> EncodingIndices;
4124 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
4125 SourceRange SR;
4126 int32_t ArgIdx;
4127
4128 if (AL.isArgIdent(Arg: I)) {
4129 IdentifierLoc *IdLoc = AL.getArgAsIdent(Arg: I);
4130 auto It = NameIdxMapping.find(Key: IdLoc->Ident->getName());
4131 if (It == UnknownName) {
4132 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
4133 << IdLoc->Ident << IdLoc->Loc;
4134 return;
4135 }
4136
4137 SR = SourceRange(IdLoc->Loc);
4138 ArgIdx = It->second;
4139 } else if (AL.isArgExpr(Arg: I)) {
4140 Expr *IdxExpr = AL.getArgAsExpr(Arg: I);
4141
4142 // If the expression is not parseable as an int32_t we have a problem.
4143 if (!checkUInt32Argument(S, AI: AL, Expr: IdxExpr, Val&: (uint32_t &)ArgIdx, Idx: I + 1,
4144 StrictlyUnsigned: false)) {
4145 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4146 << AL << (I + 1) << IdxExpr->getSourceRange();
4147 return;
4148 }
4149
4150 // Check oob, excluding the special values, 0 and -1.
4151 if (ArgIdx < -1 || ArgIdx > NumArgs) {
4152 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
4153 << AL << (I + 1) << IdxExpr->getSourceRange();
4154 return;
4155 }
4156
4157 SR = IdxExpr->getSourceRange();
4158 } else {
4159 llvm_unreachable("Unexpected ParsedAttr argument type!");
4160 }
4161
4162 if (ArgIdx == 0 && !HasImplicitThisParam) {
4163 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
4164 << (I + 1) << SR;
4165 return;
4166 }
4167
4168 // Adjust for the case we do not have an implicit "this" parameter. In this
4169 // case we decrease all positive values by 1 to get LLVM argument indices.
4170 if (!HasImplicitThisParam && ArgIdx > 0)
4171 ArgIdx -= 1;
4172
4173 EncodingIndices.push_back(Elt: ArgIdx);
4174 }
4175
4176 int CalleeIdx = EncodingIndices.front();
4177 // Check if the callee index is proper, thus not "this" and not "unknown".
4178 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
4179 // is false and positive if "HasImplicitThisParam" is true.
4180 if (CalleeIdx < (int)HasImplicitThisParam) {
4181 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
4182 << AL.getRange();
4183 return;
4184 }
4185
4186 // Get the callee type, note the index adjustment as the AST doesn't contain
4187 // the this type (which the callee cannot reference anyway!).
4188 const Type *CalleeType =
4189 getFunctionOrMethodParamType(D, Idx: CalleeIdx - HasImplicitThisParam)
4190 .getTypePtr();
4191 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
4192 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4193 << AL.getRange();
4194 return;
4195 }
4196
4197 const Type *CalleeFnType =
4198 CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
4199
4200 // TODO: Check the type of the callee arguments.
4201
4202 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(Val: CalleeFnType);
4203 if (!CalleeFnProtoType) {
4204 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4205 << AL.getRange();
4206 return;
4207 }
4208
4209 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
4210 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4211 << AL << (unsigned)(EncodingIndices.size() - 1);
4212 return;
4213 }
4214
4215 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
4216 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4217 << AL << (unsigned)(EncodingIndices.size() - 1);
4218 return;
4219 }
4220
4221 if (CalleeFnProtoType->isVariadic()) {
4222 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
4223 return;
4224 }
4225
4226 // Do not allow multiple callback attributes.
4227 if (D->hasAttr<CallbackAttr>()) {
4228 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
4229 return;
4230 }
4231
4232 D->addAttr(::new (S.Context) CallbackAttr(
4233 S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
4234}
4235
4236static bool isFunctionLike(const Type &T) {
4237 // Check for explicit function types.
4238 // 'called_once' is only supported in Objective-C and it has
4239 // function pointers and block pointers.
4240 return T.isFunctionPointerType() || T.isBlockPointerType();
4241}
4242
4243/// Handle 'called_once' attribute.
4244static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4245 // 'called_once' only applies to parameters representing functions.
4246 QualType T = cast<ParmVarDecl>(Val: D)->getType();
4247
4248 if (!isFunctionLike(T: *T)) {
4249 S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
4250 return;
4251 }
4252
4253 D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
4254}
4255
4256static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4257 // Try to find the underlying union declaration.
4258 RecordDecl *RD = nullptr;
4259 const auto *TD = dyn_cast<TypedefNameDecl>(Val: D);
4260 if (TD && TD->getUnderlyingType()->isUnionType())
4261 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
4262 else
4263 RD = dyn_cast<RecordDecl>(Val: D);
4264
4265 if (!RD || !RD->isUnion()) {
4266 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4267 << AL << AL.isRegularKeywordAttribute() << ExpectedUnion;
4268 return;
4269 }
4270
4271 if (!RD->isCompleteDefinition()) {
4272 if (!RD->isBeingDefined())
4273 S.Diag(AL.getLoc(),
4274 diag::warn_transparent_union_attribute_not_definition);
4275 return;
4276 }
4277
4278 RecordDecl::field_iterator Field = RD->field_begin(),
4279 FieldEnd = RD->field_end();
4280 if (Field == FieldEnd) {
4281 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
4282 return;
4283 }
4284
4285 FieldDecl *FirstField = *Field;
4286 QualType FirstType = FirstField->getType();
4287 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
4288 S.Diag(FirstField->getLocation(),
4289 diag::warn_transparent_union_attribute_floating)
4290 << FirstType->isVectorType() << FirstType;
4291 return;
4292 }
4293
4294 if (FirstType->isIncompleteType())
4295 return;
4296 uint64_t FirstSize = S.Context.getTypeSize(T: FirstType);
4297 uint64_t FirstAlign = S.Context.getTypeAlign(T: FirstType);
4298 for (; Field != FieldEnd; ++Field) {
4299 QualType FieldType = Field->getType();
4300 if (FieldType->isIncompleteType())
4301 return;
4302 // FIXME: this isn't fully correct; we also need to test whether the
4303 // members of the union would all have the same calling convention as the
4304 // first member of the union. Checking just the size and alignment isn't
4305 // sufficient (consider structs passed on the stack instead of in registers
4306 // as an example).
4307 if (S.Context.getTypeSize(T: FieldType) != FirstSize ||
4308 S.Context.getTypeAlign(T: FieldType) > FirstAlign) {
4309 // Warn if we drop the attribute.
4310 bool isSize = S.Context.getTypeSize(T: FieldType) != FirstSize;
4311 unsigned FieldBits = isSize ? S.Context.getTypeSize(T: FieldType)
4312 : S.Context.getTypeAlign(T: FieldType);
4313 S.Diag(Field->getLocation(),
4314 diag::warn_transparent_union_attribute_field_size_align)
4315 << isSize << *Field << FieldBits;
4316 unsigned FirstBits = isSize ? FirstSize : FirstAlign;
4317 S.Diag(FirstField->getLocation(),
4318 diag::note_transparent_union_first_field_size_align)
4319 << isSize << FirstBits;
4320 return;
4321 }
4322 }
4323
4324 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
4325}
4326
4327void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
4328 StringRef Str, MutableArrayRef<Expr *> Args) {
4329 auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
4330 if (ConstantFoldAttrArgs(
4331 CI, Args: MutableArrayRef<Expr *>(Attr->args_begin(), Attr->args_end()))) {
4332 D->addAttr(A: Attr);
4333 }
4334}
4335
4336static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4337 // Make sure that there is a string literal as the annotation's first
4338 // argument.
4339 StringRef Str;
4340 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
4341 return;
4342
4343 llvm::SmallVector<Expr *, 4> Args;
4344 Args.reserve(N: AL.getNumArgs() - 1);
4345 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
4346 assert(!AL.isArgIdent(Idx));
4347 Args.push_back(Elt: AL.getArgAsExpr(Arg: Idx));
4348 }
4349
4350 S.AddAnnotationAttr(D, CI: AL, Str, Args);
4351}
4352
4353static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4354 S.AddAlignValueAttr(D, CI: AL, E: AL.getArgAsExpr(Arg: 0));
4355}
4356
4357void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
4358 AlignValueAttr TmpAttr(Context, CI, E);
4359 SourceLocation AttrLoc = CI.getLoc();
4360
4361 QualType T;
4362 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
4363 T = TD->getUnderlyingType();
4364 else if (const auto *VD = dyn_cast<ValueDecl>(Val: D))
4365 T = VD->getType();
4366 else
4367 llvm_unreachable("Unknown decl type for align_value");
4368
4369 if (!T->isDependentType() && !T->isAnyPointerType() &&
4370 !T->isReferenceType() && !T->isMemberPointerType()) {
4371 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
4372 << &TmpAttr << T << D->getSourceRange();
4373 return;
4374 }
4375
4376 if (!E->isValueDependent()) {
4377 llvm::APSInt Alignment;
4378 ExprResult ICE = VerifyIntegerConstantExpression(
4379 E, &Alignment, diag::err_align_value_attribute_argument_not_int);
4380 if (ICE.isInvalid())
4381 return;
4382
4383 if (!Alignment.isPowerOf2()) {
4384 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4385 << E->getSourceRange();
4386 return;
4387 }
4388
4389 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
4390 return;
4391 }
4392
4393 // Save dependent expressions in the AST to be instantiated.
4394 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
4395}
4396
4397static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4398 if (AL.hasParsedType()) {
4399 const ParsedType &TypeArg = AL.getTypeArg();
4400 TypeSourceInfo *TInfo;
4401 (void)S.GetTypeFromParser(
4402 Ty: ParsedType::getFromOpaquePtr(P: TypeArg.getAsOpaquePtr()), TInfo: &TInfo);
4403 if (AL.isPackExpansion() &&
4404 !TInfo->getType()->containsUnexpandedParameterPack()) {
4405 S.Diag(AL.getEllipsisLoc(),
4406 diag::err_pack_expansion_without_parameter_packs);
4407 return;
4408 }
4409
4410 if (!AL.isPackExpansion() &&
4411 S.DiagnoseUnexpandedParameterPack(Loc: TInfo->getTypeLoc().getBeginLoc(),
4412 T: TInfo, UPPC: Sema::UPPC_Expression))
4413 return;
4414
4415 S.AddAlignedAttr(D, CI: AL, T: TInfo, IsPackExpansion: AL.isPackExpansion());
4416 return;
4417 }
4418
4419 // check the attribute arguments.
4420 if (AL.getNumArgs() > 1) {
4421 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
4422 return;
4423 }
4424
4425 if (AL.getNumArgs() == 0) {
4426 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
4427 return;
4428 }
4429
4430 Expr *E = AL.getArgAsExpr(Arg: 0);
4431 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
4432 S.Diag(AL.getEllipsisLoc(),
4433 diag::err_pack_expansion_without_parameter_packs);
4434 return;
4435 }
4436
4437 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
4438 return;
4439
4440 S.AddAlignedAttr(D, CI: AL, E, IsPackExpansion: AL.isPackExpansion());
4441}
4442
4443/// Perform checking of type validity
4444///
4445/// C++11 [dcl.align]p1:
4446/// An alignment-specifier may be applied to a variable or to a class
4447/// data member, but it shall not be applied to a bit-field, a function
4448/// parameter, the formal parameter of a catch clause, or a variable
4449/// declared with the register storage class specifier. An
4450/// alignment-specifier may also be applied to the declaration of a class
4451/// or enumeration type.
4452/// CWG 2354:
4453/// CWG agreed to remove permission for alignas to be applied to
4454/// enumerations.
4455/// C11 6.7.5/2:
4456/// An alignment attribute shall not be specified in a declaration of
4457/// a typedef, or a bit-field, or a function, or a parameter, or an
4458/// object declared with the register storage-class specifier.
4459static bool validateAlignasAppliedType(Sema &S, Decl *D,
4460 const AlignedAttr &Attr,
4461 SourceLocation AttrLoc) {
4462 int DiagKind = -1;
4463 if (isa<ParmVarDecl>(Val: D)) {
4464 DiagKind = 0;
4465 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
4466 if (VD->getStorageClass() == SC_Register)
4467 DiagKind = 1;
4468 if (VD->isExceptionVariable())
4469 DiagKind = 2;
4470 } else if (const auto *FD = dyn_cast<FieldDecl>(Val: D)) {
4471 if (FD->isBitField())
4472 DiagKind = 3;
4473 } else if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
4474 if (ED->getLangOpts().CPlusPlus)
4475 DiagKind = 4;
4476 } else if (!isa<TagDecl>(Val: D)) {
4477 return S.Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
4478 << &Attr << Attr.isRegularKeywordAttribute()
4479 << (Attr.isC11() ? ExpectedVariableOrField
4480 : ExpectedVariableFieldOrTag);
4481 }
4482 if (DiagKind != -1) {
4483 return S.Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4484 << &Attr << DiagKind;
4485 }
4486 return false;
4487}
4488
4489void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4490 bool IsPackExpansion) {
4491 AlignedAttr TmpAttr(Context, CI, true, E);
4492 SourceLocation AttrLoc = CI.getLoc();
4493
4494 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4495 if (TmpAttr.isAlignas() &&
4496 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4497 return;
4498
4499 if (E->isValueDependent()) {
4500 // We can't support a dependent alignment on a non-dependent type,
4501 // because we have no way to model that a type is "alignment-dependent"
4502 // but not dependent in any other way.
4503 if (const auto *TND = dyn_cast<TypedefNameDecl>(Val: D)) {
4504 if (!TND->getUnderlyingType()->isDependentType()) {
4505 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4506 << E->getSourceRange();
4507 return;
4508 }
4509 }
4510
4511 // Save dependent expressions in the AST to be instantiated.
4512 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4513 AA->setPackExpansion(IsPackExpansion);
4514 D->addAttr(A: AA);
4515 return;
4516 }
4517
4518 // FIXME: Cache the number on the AL object?
4519 llvm::APSInt Alignment;
4520 ExprResult ICE = VerifyIntegerConstantExpression(
4521 E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4522 if (ICE.isInvalid())
4523 return;
4524
4525 uint64_t MaximumAlignment = Sema::MaximumAlignment;
4526 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4527 MaximumAlignment = std::min(a: MaximumAlignment, b: uint64_t(8192));
4528 if (Alignment > MaximumAlignment) {
4529 Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4530 << MaximumAlignment << E->getSourceRange();
4531 return;
4532 }
4533
4534 uint64_t AlignVal = Alignment.getZExtValue();
4535 // C++11 [dcl.align]p2:
4536 // -- if the constant expression evaluates to zero, the alignment
4537 // specifier shall have no effect
4538 // C11 6.7.5p6:
4539 // An alignment specification of zero has no effect.
4540 if (!(TmpAttr.isAlignas() && !Alignment)) {
4541 if (!llvm::isPowerOf2_64(Value: AlignVal)) {
4542 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4543 << E->getSourceRange();
4544 return;
4545 }
4546 }
4547
4548 const auto *VD = dyn_cast<VarDecl>(Val: D);
4549 if (VD) {
4550 unsigned MaxTLSAlign =
4551 Context.toCharUnitsFromBits(BitSize: Context.getTargetInfo().getMaxTLSAlign())
4552 .getQuantity();
4553 if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4554 VD->getTLSKind() != VarDecl::TLS_None) {
4555 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4556 << (unsigned)AlignVal << VD << MaxTLSAlign;
4557 return;
4558 }
4559 }
4560
4561 // On AIX, an aligned attribute can not decrease the alignment when applied
4562 // to a variable declaration with vector type.
4563 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4564 const Type *Ty = VD->getType().getTypePtr();
4565 if (Ty->isVectorType() && AlignVal < 16) {
4566 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4567 << VD->getType() << 16;
4568 return;
4569 }
4570 }
4571
4572 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4573 AA->setPackExpansion(IsPackExpansion);
4574 AA->setCachedAlignmentValue(
4575 static_cast<unsigned>(AlignVal * Context.getCharWidth()));
4576 D->addAttr(A: AA);
4577}
4578
4579void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4580 TypeSourceInfo *TS, bool IsPackExpansion) {
4581 AlignedAttr TmpAttr(Context, CI, false, TS);
4582 SourceLocation AttrLoc = CI.getLoc();
4583
4584 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4585 if (TmpAttr.isAlignas() &&
4586 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4587 return;
4588
4589 if (TS->getType()->isDependentType()) {
4590 // We can't support a dependent alignment on a non-dependent type,
4591 // because we have no way to model that a type is "type-dependent"
4592 // but not dependent in any other way.
4593 if (const auto *TND = dyn_cast<TypedefNameDecl>(Val: D)) {
4594 if (!TND->getUnderlyingType()->isDependentType()) {
4595 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4596 << TS->getTypeLoc().getSourceRange();
4597 return;
4598 }
4599 }
4600
4601 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4602 AA->setPackExpansion(IsPackExpansion);
4603 D->addAttr(A: AA);
4604 return;
4605 }
4606
4607 const auto *VD = dyn_cast<VarDecl>(Val: D);
4608 unsigned AlignVal = TmpAttr.getAlignment(Context);
4609 // On AIX, an aligned attribute can not decrease the alignment when applied
4610 // to a variable declaration with vector type.
4611 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4612 const Type *Ty = VD->getType().getTypePtr();
4613 if (Ty->isVectorType() &&
4614 Context.toCharUnitsFromBits(BitSize: AlignVal).getQuantity() < 16) {
4615 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4616 << VD->getType() << 16;
4617 return;
4618 }
4619 }
4620
4621 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4622 AA->setPackExpansion(IsPackExpansion);
4623 AA->setCachedAlignmentValue(AlignVal);
4624 D->addAttr(A: AA);
4625}
4626
4627void Sema::CheckAlignasUnderalignment(Decl *D) {
4628 assert(D->hasAttrs() && "no attributes on decl");
4629
4630 QualType UnderlyingTy, DiagTy;
4631 if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
4632 UnderlyingTy = DiagTy = VD->getType();
4633 } else {
4634 UnderlyingTy = DiagTy = Context.getTagDeclType(Decl: cast<TagDecl>(Val: D));
4635 if (const auto *ED = dyn_cast<EnumDecl>(Val: D))
4636 UnderlyingTy = ED->getIntegerType();
4637 }
4638 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4639 return;
4640
4641 // C++11 [dcl.align]p5, C11 6.7.5/4:
4642 // The combined effect of all alignment attributes in a declaration shall
4643 // not specify an alignment that is less strict than the alignment that
4644 // would otherwise be required for the entity being declared.
4645 AlignedAttr *AlignasAttr = nullptr;
4646 AlignedAttr *LastAlignedAttr = nullptr;
4647 unsigned Align = 0;
4648 for (auto *I : D->specific_attrs<AlignedAttr>()) {
4649 if (I->isAlignmentDependent())
4650 return;
4651 if (I->isAlignas())
4652 AlignasAttr = I;
4653 Align = std::max(Align, I->getAlignment(Context));
4654 LastAlignedAttr = I;
4655 }
4656
4657 if (Align && DiagTy->isSizelessType()) {
4658 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4659 << LastAlignedAttr << DiagTy;
4660 } else if (AlignasAttr && Align) {
4661 CharUnits RequestedAlign = Context.toCharUnitsFromBits(BitSize: Align);
4662 CharUnits NaturalAlign = Context.getTypeAlignInChars(T: UnderlyingTy);
4663 if (NaturalAlign > RequestedAlign)
4664 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4665 << DiagTy << (unsigned)NaturalAlign.getQuantity();
4666 }
4667}
4668
4669bool Sema::checkMSInheritanceAttrOnDefinition(
4670 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4671 MSInheritanceModel ExplicitModel) {
4672 assert(RD->hasDefinition() && "RD has no definition!");
4673
4674 // We may not have seen base specifiers or any virtual methods yet. We will
4675 // have to wait until the record is defined to catch any mismatches.
4676 if (!RD->getDefinition()->isCompleteDefinition())
4677 return false;
4678
4679 // The unspecified model never matches what a definition could need.
4680 if (ExplicitModel == MSInheritanceModel::Unspecified)
4681 return false;
4682
4683 if (BestCase) {
4684 if (RD->calculateInheritanceModel() == ExplicitModel)
4685 return false;
4686 } else {
4687 if (RD->calculateInheritanceModel() <= ExplicitModel)
4688 return false;
4689 }
4690
4691 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4692 << 0 /*definition*/;
4693 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4694 return true;
4695}
4696
4697/// parseModeAttrArg - Parses attribute mode string and returns parsed type
4698/// attribute.
4699static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4700 bool &IntegerMode, bool &ComplexMode,
4701 FloatModeKind &ExplicitType) {
4702 IntegerMode = true;
4703 ComplexMode = false;
4704 ExplicitType = FloatModeKind::NoFloat;
4705 switch (Str.size()) {
4706 case 2:
4707 switch (Str[0]) {
4708 case 'Q':
4709 DestWidth = 8;
4710 break;
4711 case 'H':
4712 DestWidth = 16;
4713 break;
4714 case 'S':
4715 DestWidth = 32;
4716 break;
4717 case 'D':
4718 DestWidth = 64;
4719 break;
4720 case 'X':
4721 DestWidth = 96;
4722 break;
4723 case 'K': // KFmode - IEEE quad precision (__float128)
4724 ExplicitType = FloatModeKind::Float128;
4725 DestWidth = Str[1] == 'I' ? 0 : 128;
4726 break;
4727 case 'T':
4728 ExplicitType = FloatModeKind::LongDouble;
4729 DestWidth = 128;
4730 break;
4731 case 'I':
4732 ExplicitType = FloatModeKind::Ibm128;
4733 DestWidth = Str[1] == 'I' ? 0 : 128;
4734 break;
4735 }
4736 if (Str[1] == 'F') {
4737 IntegerMode = false;
4738 } else if (Str[1] == 'C') {
4739 IntegerMode = false;
4740 ComplexMode = true;
4741 } else if (Str[1] != 'I') {
4742 DestWidth = 0;
4743 }
4744 break;
4745 case 4:
4746 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4747 // pointer on PIC16 and other embedded platforms.
4748 if (Str == "word")
4749 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4750 else if (Str == "byte")
4751 DestWidth = S.Context.getTargetInfo().getCharWidth();
4752 break;
4753 case 7:
4754 if (Str == "pointer")
4755 DestWidth = S.Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
4756 break;
4757 case 11:
4758 if (Str == "unwind_word")
4759 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4760 break;
4761 }
4762}
4763
4764/// handleModeAttr - This attribute modifies the width of a decl with primitive
4765/// type.
4766///
4767/// Despite what would be logical, the mode attribute is a decl attribute, not a
4768/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4769/// HImode, not an intermediate pointer.
4770static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4771 // This attribute isn't documented, but glibc uses it. It changes
4772 // the width of an int or unsigned int to the specified size.
4773 if (!AL.isArgIdent(Arg: 0)) {
4774 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4775 << AL << AANT_ArgumentIdentifier;
4776 return;
4777 }
4778
4779 IdentifierInfo *Name = AL.getArgAsIdent(Arg: 0)->Ident;
4780
4781 S.AddModeAttr(D, CI: AL, Name);
4782}
4783
4784void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
4785 IdentifierInfo *Name, bool InInstantiation) {
4786 StringRef Str = Name->getName();
4787 normalizeName(AttrName&: Str);
4788 SourceLocation AttrLoc = CI.getLoc();
4789
4790 unsigned DestWidth = 0;
4791 bool IntegerMode = true;
4792 bool ComplexMode = false;
4793 FloatModeKind ExplicitType = FloatModeKind::NoFloat;
4794 llvm::APInt VectorSize(64, 0);
4795 if (Str.size() >= 4 && Str[0] == 'V') {
4796 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4797 size_t StrSize = Str.size();
4798 size_t VectorStringLength = 0;
4799 while ((VectorStringLength + 1) < StrSize &&
4800 isdigit(Str[VectorStringLength + 1]))
4801 ++VectorStringLength;
4802 if (VectorStringLength &&
4803 !Str.substr(Start: 1, N: VectorStringLength).getAsInteger(Radix: 10, Result&: VectorSize) &&
4804 VectorSize.isPowerOf2()) {
4805 parseModeAttrArg(S&: *this, Str: Str.substr(Start: VectorStringLength + 1), DestWidth,
4806 IntegerMode, ComplexMode, ExplicitType);
4807 // Avoid duplicate warning from template instantiation.
4808 if (!InInstantiation)
4809 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4810 } else {
4811 VectorSize = 0;
4812 }
4813 }
4814
4815 if (!VectorSize)
4816 parseModeAttrArg(S&: *this, Str, DestWidth, IntegerMode, ComplexMode,
4817 ExplicitType);
4818
4819 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4820 // and friends, at least with glibc.
4821 // FIXME: Make sure floating-point mappings are accurate
4822 // FIXME: Support XF and TF types
4823 if (!DestWidth) {
4824 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4825 return;
4826 }
4827
4828 QualType OldTy;
4829 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
4830 OldTy = TD->getUnderlyingType();
4831 else if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
4832 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4833 // Try to get type from enum declaration, default to int.
4834 OldTy = ED->getIntegerType();
4835 if (OldTy.isNull())
4836 OldTy = Context.IntTy;
4837 } else
4838 OldTy = cast<ValueDecl>(Val: D)->getType();
4839
4840 if (OldTy->isDependentType()) {
4841 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4842 return;
4843 }
4844
4845 // Base type can also be a vector type (see PR17453).
4846 // Distinguish between base type and base element type.
4847 QualType OldElemTy = OldTy;
4848 if (const auto *VT = OldTy->getAs<VectorType>())
4849 OldElemTy = VT->getElementType();
4850
4851 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4852 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4853 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4854 if ((isa<EnumDecl>(Val: D) || OldElemTy->getAs<EnumType>()) &&
4855 VectorSize.getBoolValue()) {
4856 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4857 return;
4858 }
4859 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4860 !OldElemTy->isBitIntType()) ||
4861 OldElemTy->getAs<EnumType>();
4862
4863 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4864 !IntegralOrAnyEnumType)
4865 Diag(AttrLoc, diag::err_mode_not_primitive);
4866 else if (IntegerMode) {
4867 if (!IntegralOrAnyEnumType)
4868 Diag(AttrLoc, diag::err_mode_wrong_type);
4869 } else if (ComplexMode) {
4870 if (!OldElemTy->isComplexType())
4871 Diag(AttrLoc, diag::err_mode_wrong_type);
4872 } else {
4873 if (!OldElemTy->isFloatingType())
4874 Diag(AttrLoc, diag::err_mode_wrong_type);
4875 }
4876
4877 QualType NewElemTy;
4878
4879 if (IntegerMode)
4880 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4881 Signed: OldElemTy->isSignedIntegerType());
4882 else
4883 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
4884
4885 if (NewElemTy.isNull()) {
4886 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4887 return;
4888 }
4889
4890 if (ComplexMode) {
4891 NewElemTy = Context.getComplexType(T: NewElemTy);
4892 }
4893
4894 QualType NewTy = NewElemTy;
4895 if (VectorSize.getBoolValue()) {
4896 NewTy = Context.getVectorType(VectorType: NewTy, NumElts: VectorSize.getZExtValue(),
4897 VecKind: VectorKind::Generic);
4898 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4899 // Complex machine mode does not support base vector types.
4900 if (ComplexMode) {
4901 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4902 return;
4903 }
4904 unsigned NumElements = Context.getTypeSize(T: OldElemTy) *
4905 OldVT->getNumElements() /
4906 Context.getTypeSize(T: NewElemTy);
4907 NewTy =
4908 Context.getVectorType(VectorType: NewElemTy, NumElts: NumElements, VecKind: OldVT->getVectorKind());
4909 }
4910
4911 if (NewTy.isNull()) {
4912 Diag(AttrLoc, diag::err_mode_wrong_type);
4913 return;
4914 }
4915
4916 // Install the new type.
4917 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
4918 TD->setModedTypeSourceInfo(unmodedTSI: TD->getTypeSourceInfo(), modedTy: NewTy);
4919 else if (auto *ED = dyn_cast<EnumDecl>(Val: D))
4920 ED->setIntegerType(NewTy);
4921 else
4922 cast<ValueDecl>(Val: D)->setType(NewTy);
4923
4924 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4925}
4926
4927static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4928 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4929}
4930
4931AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4932 const AttributeCommonInfo &CI,
4933 const IdentifierInfo *Ident) {
4934 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4935 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4936 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4937 return nullptr;
4938 }
4939
4940 if (D->hasAttr<AlwaysInlineAttr>())
4941 return nullptr;
4942
4943 return ::new (Context) AlwaysInlineAttr(Context, CI);
4944}
4945
4946InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4947 const ParsedAttr &AL) {
4948 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
4949 // Attribute applies to Var but not any subclass of it (like ParmVar,
4950 // ImplicitParm or VarTemplateSpecialization).
4951 if (VD->getKind() != Decl::Var) {
4952 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4953 << AL << AL.isRegularKeywordAttribute()
4954 << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4955 : ExpectedVariableOrFunction);
4956 return nullptr;
4957 }
4958 // Attribute does not apply to non-static local variables.
4959 if (VD->hasLocalStorage()) {
4960 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4961 return nullptr;
4962 }
4963 }
4964
4965 return ::new (Context) InternalLinkageAttr(Context, AL);
4966}
4967InternalLinkageAttr *
4968Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4969 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
4970 // Attribute applies to Var but not any subclass of it (like ParmVar,
4971 // ImplicitParm or VarTemplateSpecialization).
4972 if (VD->getKind() != Decl::Var) {
4973 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4974 << &AL << AL.isRegularKeywordAttribute()
4975 << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4976 : ExpectedVariableOrFunction);
4977 return nullptr;
4978 }
4979 // Attribute does not apply to non-static local variables.
4980 if (VD->hasLocalStorage()) {
4981 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4982 return nullptr;
4983 }
4984 }
4985
4986 return ::new (Context) InternalLinkageAttr(Context, AL);
4987}
4988
4989MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4990 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4991 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4992 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4993 return nullptr;
4994 }
4995
4996 if (D->hasAttr<MinSizeAttr>())
4997 return nullptr;
4998
4999 return ::new (Context) MinSizeAttr(Context, CI);
5000}
5001
5002SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
5003 StringRef Name) {
5004 if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
5005 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
5006 Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
5007 << PrevSNA << &SNA
5008 << (PrevSNA->isRegularKeywordAttribute() ||
5009 SNA.isRegularKeywordAttribute());
5010 Diag(SNA.getLoc(), diag::note_conflicting_attribute);
5011 }
5012
5013 D->dropAttr<SwiftNameAttr>();
5014 }
5015 return ::new (Context) SwiftNameAttr(Context, SNA, Name);
5016}
5017
5018OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
5019 const AttributeCommonInfo &CI) {
5020 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
5021 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
5022 Diag(CI.getLoc(), diag::note_conflicting_attribute);
5023 D->dropAttr<AlwaysInlineAttr>();
5024 }
5025 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
5026 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
5027 Diag(CI.getLoc(), diag::note_conflicting_attribute);
5028 D->dropAttr<MinSizeAttr>();
5029 }
5030
5031 if (D->hasAttr<OptimizeNoneAttr>())
5032 return nullptr;
5033
5034 return ::new (Context) OptimizeNoneAttr(Context, CI);
5035}
5036
5037static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5038 if (AlwaysInlineAttr *Inline =
5039 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
5040 D->addAttr(Inline);
5041}
5042
5043static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5044 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
5045 D->addAttr(MinSize);
5046}
5047
5048static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5049 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
5050 D->addAttr(Optnone);
5051}
5052
5053static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5054 const auto *VD = cast<VarDecl>(Val: D);
5055 if (VD->hasLocalStorage()) {
5056 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5057 return;
5058 }
5059 // constexpr variable may already get an implicit constant attr, which should
5060 // be replaced by the explicit constant attr.
5061 if (auto *A = D->getAttr<CUDAConstantAttr>()) {
5062 if (!A->isImplicit())
5063 return;
5064 D->dropAttr<CUDAConstantAttr>();
5065 }
5066 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
5067}
5068
5069static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5070 const auto *VD = cast<VarDecl>(Val: D);
5071 // extern __shared__ is only allowed on arrays with no length (e.g.
5072 // "int x[]").
5073 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
5074 !isa<IncompleteArrayType>(VD->getType())) {
5075 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
5076 return;
5077 }
5078 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
5079 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
5080 << S.CurrentCUDATarget())
5081 return;
5082 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
5083}
5084
5085static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5086 const auto *FD = cast<FunctionDecl>(Val: D);
5087 if (!FD->getReturnType()->isVoidType() &&
5088 !FD->getReturnType()->getAs<AutoType>() &&
5089 !FD->getReturnType()->isInstantiationDependentType()) {
5090 SourceRange RTRange = FD->getReturnTypeSourceRange();
5091 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
5092 << FD->getType()
5093 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
5094 : FixItHint());
5095 return;
5096 }
5097 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD)) {
5098 if (Method->isInstance()) {
5099 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
5100 << Method;
5101 return;
5102 }
5103 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
5104 }
5105 // Only warn for "inline" when compiling for host, to cut down on noise.
5106 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
5107 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
5108
5109 if (AL.getKind() == ParsedAttr::AT_NVPTXKernel)
5110 D->addAttr(::new (S.Context) NVPTXKernelAttr(S.Context, AL));
5111 else
5112 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
5113 // In host compilation the kernel is emitted as a stub function, which is
5114 // a helper function for launching the kernel. The instructions in the helper
5115 // function has nothing to do with the source code of the kernel. Do not emit
5116 // debug info for the stub function to avoid confusing the debugger.
5117 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
5118 D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
5119}
5120
5121static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5122 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
5123 if (VD->hasLocalStorage()) {
5124 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5125 return;
5126 }
5127 }
5128
5129 if (auto *A = D->getAttr<CUDADeviceAttr>()) {
5130 if (!A->isImplicit())
5131 return;
5132 D->dropAttr<CUDADeviceAttr>();
5133 }
5134 D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
5135}
5136
5137static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5138 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
5139 if (VD->hasLocalStorage()) {
5140 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
5141 return;
5142 }
5143 }
5144 if (!D->hasAttr<HIPManagedAttr>())
5145 D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
5146 if (!D->hasAttr<CUDADeviceAttr>())
5147 D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
5148}
5149
5150static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5151 const auto *Fn = cast<FunctionDecl>(Val: D);
5152 if (!Fn->isInlineSpecified()) {
5153 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
5154 return;
5155 }
5156
5157 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
5158 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
5159
5160 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
5161}
5162
5163static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5164 if (hasDeclarator(D)) return;
5165
5166 // Diagnostic is emitted elsewhere: here we store the (valid) AL
5167 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
5168 CallingConv CC;
5169 if (S.CheckCallingConvAttr(attr: AL, CC, /*FD*/ nullptr,
5170 CFT: S.IdentifyCUDATarget(D: dyn_cast<FunctionDecl>(Val: D))))
5171 return;
5172
5173 if (!isa<ObjCMethodDecl>(Val: D)) {
5174 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5175 << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
5176 return;
5177 }
5178
5179 switch (AL.getKind()) {
5180 case ParsedAttr::AT_FastCall:
5181 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
5182 return;
5183 case ParsedAttr::AT_StdCall:
5184 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
5185 return;
5186 case ParsedAttr::AT_ThisCall:
5187 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
5188 return;
5189 case ParsedAttr::AT_CDecl:
5190 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
5191 return;
5192 case ParsedAttr::AT_Pascal:
5193 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
5194 return;
5195 case ParsedAttr::AT_SwiftCall:
5196 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
5197 return;
5198 case ParsedAttr::AT_SwiftAsyncCall:
5199 D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
5200 return;
5201 case ParsedAttr::AT_VectorCall:
5202 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
5203 return;
5204 case ParsedAttr::AT_MSABI:
5205 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
5206 return;
5207 case ParsedAttr::AT_SysVABI:
5208 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
5209 return;
5210 case ParsedAttr::AT_RegCall:
5211 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
5212 return;
5213 case ParsedAttr::AT_Pcs: {
5214 PcsAttr::PCSType PCS;
5215 switch (CC) {
5216 case CC_AAPCS:
5217 PCS = PcsAttr::AAPCS;
5218 break;
5219 case CC_AAPCS_VFP:
5220 PCS = PcsAttr::AAPCS_VFP;
5221 break;
5222 default:
5223 llvm_unreachable("unexpected calling convention in pcs attribute");
5224 }
5225
5226 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
5227 return;
5228 }
5229 case ParsedAttr::AT_AArch64VectorPcs:
5230 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
5231 return;
5232 case ParsedAttr::AT_AArch64SVEPcs:
5233 D->addAttr(::new (S.Context) AArch64SVEPcsAttr(S.Context, AL));
5234 return;
5235 case ParsedAttr::AT_AMDGPUKernelCall:
5236 D->addAttr(::new (S.Context) AMDGPUKernelCallAttr(S.Context, AL));
5237 return;
5238 case ParsedAttr::AT_IntelOclBicc:
5239 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
5240 return;
5241 case ParsedAttr::AT_PreserveMost:
5242 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
5243 return;
5244 case ParsedAttr::AT_PreserveAll:
5245 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
5246 return;
5247 case ParsedAttr::AT_M68kRTD:
5248 D->addAttr(::new (S.Context) M68kRTDAttr(S.Context, AL));
5249 return;
5250 case ParsedAttr::AT_PreserveNone:
5251 D->addAttr(::new (S.Context) PreserveNoneAttr(S.Context, AL));
5252 return;
5253 default:
5254 llvm_unreachable("unexpected attribute kind");
5255 }
5256}
5257
5258static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5259 if (AL.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress) {
5260 // Suppression attribute with GSL spelling requires at least 1 argument.
5261 if (!AL.checkAtLeastNumArgs(S, Num: 1))
5262 return;
5263 }
5264
5265 std::vector<StringRef> DiagnosticIdentifiers;
5266 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5267 StringRef RuleName;
5268
5269 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: RuleName, ArgLocation: nullptr))
5270 return;
5271
5272 DiagnosticIdentifiers.push_back(x: RuleName);
5273 }
5274 D->addAttr(::new (S.Context)
5275 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
5276 DiagnosticIdentifiers.size()));
5277}
5278
5279static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5280 TypeSourceInfo *DerefTypeLoc = nullptr;
5281 QualType ParmType;
5282 if (AL.hasParsedType()) {
5283 ParmType = S.GetTypeFromParser(Ty: AL.getTypeArg(), TInfo: &DerefTypeLoc);
5284
5285 unsigned SelectIdx = ~0U;
5286 if (ParmType->isReferenceType())
5287 SelectIdx = 0;
5288 else if (ParmType->isArrayType())
5289 SelectIdx = 1;
5290
5291 if (SelectIdx != ~0U) {
5292 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
5293 << SelectIdx << AL;
5294 return;
5295 }
5296 }
5297
5298 // To check if earlier decl attributes do not conflict the newly parsed ones
5299 // we always add (and check) the attribute to the canonical decl. We need
5300 // to repeat the check for attribute mutual exclusion because we're attaching
5301 // all of the attributes to the canonical declaration rather than the current
5302 // declaration.
5303 D = D->getCanonicalDecl();
5304 if (AL.getKind() == ParsedAttr::AT_Owner) {
5305 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
5306 return;
5307 if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
5308 const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
5309 ? OAttr->getDerefType().getTypePtr()
5310 : nullptr;
5311 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5312 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5313 << AL << OAttr
5314 << (AL.isRegularKeywordAttribute() ||
5315 OAttr->isRegularKeywordAttribute());
5316 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
5317 }
5318 return;
5319 }
5320 for (Decl *Redecl : D->redecls()) {
5321 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
5322 }
5323 } else {
5324 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
5325 return;
5326 if (const auto *PAttr = D->getAttr<PointerAttr>()) {
5327 const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
5328 ? PAttr->getDerefType().getTypePtr()
5329 : nullptr;
5330 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5331 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5332 << AL << PAttr
5333 << (AL.isRegularKeywordAttribute() ||
5334 PAttr->isRegularKeywordAttribute());
5335 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
5336 }
5337 return;
5338 }
5339 for (Decl *Redecl : D->redecls()) {
5340 Redecl->addAttr(::new (S.Context)
5341 PointerAttr(S.Context, AL, DerefTypeLoc));
5342 }
5343 }
5344}
5345
5346static void handleRandomizeLayoutAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5347 if (checkAttrMutualExclusion<NoRandomizeLayoutAttr>(S, D, AL))
5348 return;
5349 if (!D->hasAttr<RandomizeLayoutAttr>())
5350 D->addAttr(::new (S.Context) RandomizeLayoutAttr(S.Context, AL));
5351}
5352
5353static void handleNoRandomizeLayoutAttr(Sema &S, Decl *D,
5354 const ParsedAttr &AL) {
5355 if (checkAttrMutualExclusion<RandomizeLayoutAttr>(S, D, AL))
5356 return;
5357 if (!D->hasAttr<NoRandomizeLayoutAttr>())
5358 D->addAttr(::new (S.Context) NoRandomizeLayoutAttr(S.Context, AL));
5359}
5360
5361bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
5362 const FunctionDecl *FD,
5363 CUDAFunctionTarget CFT) {
5364 if (Attrs.isInvalid())
5365 return true;
5366
5367 if (Attrs.hasProcessingCache()) {
5368 CC = (CallingConv) Attrs.getProcessingCache();
5369 return false;
5370 }
5371
5372 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
5373 if (!Attrs.checkExactlyNumArgs(S&: *this, Num: ReqArgs)) {
5374 Attrs.setInvalid();
5375 return true;
5376 }
5377
5378 // TODO: diagnose uses of these conventions on the wrong target.
5379 switch (Attrs.getKind()) {
5380 case ParsedAttr::AT_CDecl:
5381 CC = CC_C;
5382 break;
5383 case ParsedAttr::AT_FastCall:
5384 CC = CC_X86FastCall;
5385 break;
5386 case ParsedAttr::AT_StdCall:
5387 CC = CC_X86StdCall;
5388 break;
5389 case ParsedAttr::AT_ThisCall:
5390 CC = CC_X86ThisCall;
5391 break;
5392 case ParsedAttr::AT_Pascal:
5393 CC = CC_X86Pascal;
5394 break;
5395 case ParsedAttr::AT_SwiftCall:
5396 CC = CC_Swift;
5397 break;
5398 case ParsedAttr::AT_SwiftAsyncCall:
5399 CC = CC_SwiftAsync;
5400 break;
5401 case ParsedAttr::AT_VectorCall:
5402 CC = CC_X86VectorCall;
5403 break;
5404 case ParsedAttr::AT_AArch64VectorPcs:
5405 CC = CC_AArch64VectorCall;
5406 break;
5407 case ParsedAttr::AT_AArch64SVEPcs:
5408 CC = CC_AArch64SVEPCS;
5409 break;
5410 case ParsedAttr::AT_AMDGPUKernelCall:
5411 CC = CC_AMDGPUKernelCall;
5412 break;
5413 case ParsedAttr::AT_RegCall:
5414 CC = CC_X86RegCall;
5415 break;
5416 case ParsedAttr::AT_MSABI:
5417 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
5418 CC_Win64;
5419 break;
5420 case ParsedAttr::AT_SysVABI:
5421 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
5422 CC_C;
5423 break;
5424 case ParsedAttr::AT_Pcs: {
5425 StringRef StrRef;
5426 if (!checkStringLiteralArgumentAttr(AL: Attrs, ArgNum: 0, Str&: StrRef)) {
5427 Attrs.setInvalid();
5428 return true;
5429 }
5430 if (StrRef == "aapcs") {
5431 CC = CC_AAPCS;
5432 break;
5433 } else if (StrRef == "aapcs-vfp") {
5434 CC = CC_AAPCS_VFP;
5435 break;
5436 }
5437
5438 Attrs.setInvalid();
5439 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
5440 return true;
5441 }
5442 case ParsedAttr::AT_IntelOclBicc:
5443 CC = CC_IntelOclBicc;
5444 break;
5445 case ParsedAttr::AT_PreserveMost:
5446 CC = CC_PreserveMost;
5447 break;
5448 case ParsedAttr::AT_PreserveAll:
5449 CC = CC_PreserveAll;
5450 break;
5451 case ParsedAttr::AT_M68kRTD:
5452 CC = CC_M68kRTD;
5453 break;
5454 case ParsedAttr::AT_PreserveNone:
5455 CC = CC_PreserveNone;
5456 break;
5457 default: llvm_unreachable("unexpected attribute kind");
5458 }
5459
5460 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
5461 const TargetInfo &TI = Context.getTargetInfo();
5462 // CUDA functions may have host and/or device attributes which indicate
5463 // their targeted execution environment, therefore the calling convention
5464 // of functions in CUDA should be checked against the target deduced based
5465 // on their host/device attributes.
5466 if (LangOpts.CUDA) {
5467 auto *Aux = Context.getAuxTargetInfo();
5468 assert(FD || CFT != CFT_InvalidTarget);
5469 auto CudaTarget = FD ? IdentifyCUDATarget(D: FD) : CFT;
5470 bool CheckHost = false, CheckDevice = false;
5471 switch (CudaTarget) {
5472 case CFT_HostDevice:
5473 CheckHost = true;
5474 CheckDevice = true;
5475 break;
5476 case CFT_Host:
5477 CheckHost = true;
5478 break;
5479 case CFT_Device:
5480 case CFT_Global:
5481 CheckDevice = true;
5482 break;
5483 case CFT_InvalidTarget:
5484 llvm_unreachable("unexpected cuda target");
5485 }
5486 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
5487 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
5488 if (CheckHost && HostTI)
5489 A = HostTI->checkCallingConvention(CC);
5490 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
5491 A = DeviceTI->checkCallingConvention(CC);
5492 } else {
5493 A = TI.checkCallingConvention(CC);
5494 }
5495
5496 switch (A) {
5497 case TargetInfo::CCCR_OK:
5498 break;
5499
5500 case TargetInfo::CCCR_Ignore:
5501 // Treat an ignored convention as if it was an explicit C calling convention
5502 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
5503 // that command line flags that change the default convention to
5504 // __vectorcall don't affect declarations marked __stdcall.
5505 CC = CC_C;
5506 break;
5507
5508 case TargetInfo::CCCR_Error:
5509 Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
5510 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5511 break;
5512
5513 case TargetInfo::CCCR_Warning: {
5514 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
5515 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5516
5517 // This convention is not valid for the target. Use the default function or
5518 // method calling convention.
5519 bool IsCXXMethod = false, IsVariadic = false;
5520 if (FD) {
5521 IsCXXMethod = FD->isCXXInstanceMember();
5522 IsVariadic = FD->isVariadic();
5523 }
5524 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
5525 break;
5526 }
5527 }
5528
5529 Attrs.setProcessingCache((unsigned) CC);
5530 return false;
5531}
5532
5533/// Pointer-like types in the default address space.
5534static bool isValidSwiftContextType(QualType Ty) {
5535 if (!Ty->hasPointerRepresentation())
5536 return Ty->isDependentType();
5537 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
5538}
5539
5540/// Pointers and references in the default address space.
5541static bool isValidSwiftIndirectResultType(QualType Ty) {
5542 if (const auto *PtrType = Ty->getAs<PointerType>()) {
5543 Ty = PtrType->getPointeeType();
5544 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5545 Ty = RefType->getPointeeType();
5546 } else {
5547 return Ty->isDependentType();
5548 }
5549 return Ty.getAddressSpace() == LangAS::Default;
5550}
5551
5552/// Pointers and references to pointers in the default address space.
5553static bool isValidSwiftErrorResultType(QualType Ty) {
5554 if (const auto *PtrType = Ty->getAs<PointerType>()) {
5555 Ty = PtrType->getPointeeType();
5556 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5557 Ty = RefType->getPointeeType();
5558 } else {
5559 return Ty->isDependentType();
5560 }
5561 if (!Ty.getQualifiers().empty())
5562 return false;
5563 return isValidSwiftContextType(Ty);
5564}
5565
5566void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
5567 ParameterABI abi) {
5568
5569 QualType type = cast<ParmVarDecl>(Val: D)->getType();
5570
5571 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
5572 if (existingAttr->getABI() != abi) {
5573 Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
5574 << getParameterABISpelling(abi) << existingAttr
5575 << (CI.isRegularKeywordAttribute() ||
5576 existingAttr->isRegularKeywordAttribute());
5577 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
5578 return;
5579 }
5580 }
5581
5582 switch (abi) {
5583 case ParameterABI::Ordinary:
5584 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
5585
5586 case ParameterABI::SwiftContext:
5587 if (!isValidSwiftContextType(Ty: type)) {
5588 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5589 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5590 }
5591 D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
5592 return;
5593
5594 case ParameterABI::SwiftAsyncContext:
5595 if (!isValidSwiftContextType(Ty: type)) {
5596 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5597 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5598 }
5599 D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
5600 return;
5601
5602 case ParameterABI::SwiftErrorResult:
5603 if (!isValidSwiftErrorResultType(Ty: type)) {
5604 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5605 << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
5606 }
5607 D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
5608 return;
5609
5610 case ParameterABI::SwiftIndirectResult:
5611 if (!isValidSwiftIndirectResultType(Ty: type)) {
5612 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5613 << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
5614 }
5615 D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
5616 return;
5617 }
5618 llvm_unreachable("bad parameter ABI attribute");
5619}
5620
5621/// Checks a regparm attribute, returning true if it is ill-formed and
5622/// otherwise setting numParams to the appropriate value.
5623bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
5624 if (AL.isInvalid())
5625 return true;
5626
5627 if (!AL.checkExactlyNumArgs(S&: *this, Num: 1)) {
5628 AL.setInvalid();
5629 return true;
5630 }
5631
5632 uint32_t NP;
5633 Expr *NumParamsExpr = AL.getArgAsExpr(Arg: 0);
5634 if (!checkUInt32Argument(S&: *this, AI: AL, Expr: NumParamsExpr, Val&: NP)) {
5635 AL.setInvalid();
5636 return true;
5637 }
5638
5639 if (Context.getTargetInfo().getRegParmMax() == 0) {
5640 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
5641 << NumParamsExpr->getSourceRange();
5642 AL.setInvalid();
5643 return true;
5644 }
5645
5646 numParams = NP;
5647 if (numParams > Context.getTargetInfo().getRegParmMax()) {
5648 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
5649 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
5650 AL.setInvalid();
5651 return true;
5652 }
5653
5654 return false;
5655}
5656
5657// Helper to get CudaArch.
5658static CudaArch getCudaArch(const TargetInfo &TI) {
5659 if (!TI.getTriple().isNVPTX())
5660 llvm_unreachable("getCudaArch is only valid for NVPTX triple");
5661 auto &TO = TI.getTargetOpts();
5662 return StringToCudaArch(S: TO.CPU);
5663}
5664
5665// Checks whether an argument of launch_bounds attribute is
5666// acceptable, performs implicit conversion to Rvalue, and returns
5667// non-nullptr Expr result on success. Otherwise, it returns nullptr
5668// and may output an error.
5669static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
5670 const CUDALaunchBoundsAttr &AL,
5671 const unsigned Idx) {
5672 if (S.DiagnoseUnexpandedParameterPack(E))
5673 return nullptr;
5674
5675 // Accept template arguments for now as they depend on something else.
5676 // We'll get to check them when they eventually get instantiated.
5677 if (E->isValueDependent())
5678 return E;
5679
5680 std::optional<llvm::APSInt> I = llvm::APSInt(64);
5681 if (!(I = E->getIntegerConstantExpr(Ctx: S.Context))) {
5682 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
5683 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
5684 return nullptr;
5685 }
5686 // Make sure we can fit it in 32 bits.
5687 if (!I->isIntN(N: 32)) {
5688 S.Diag(E->getExprLoc(), diag::err_ice_too_large)
5689 << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
5690 return nullptr;
5691 }
5692 if (*I < 0)
5693 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
5694 << &AL << Idx << E->getSourceRange();
5695
5696 // We may need to perform implicit conversion of the argument.
5697 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5698 S.Context, S.Context.getConstType(T: S.Context.IntTy), /*consume*/ false);
5699 ExprResult ValArg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
5700 assert(!ValArg.isInvalid() &&
5701 "Unexpected PerformCopyInitialization() failure.");
5702
5703 return ValArg.getAs<Expr>();
5704}
5705
5706CUDALaunchBoundsAttr *
5707Sema::CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads,
5708 Expr *MinBlocks, Expr *MaxBlocks) {
5709 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
5710 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
5711 if (!MaxThreads)
5712 return nullptr;
5713
5714 if (MinBlocks) {
5715 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
5716 if (!MinBlocks)
5717 return nullptr;
5718 }
5719
5720 if (MaxBlocks) {
5721 // '.maxclusterrank' ptx directive requires .target sm_90 or higher.
5722 auto SM = getCudaArch(TI: Context.getTargetInfo());
5723 if (SM == CudaArch::UNKNOWN || SM < CudaArch::SM_90) {
5724 Diag(MaxBlocks->getBeginLoc(), diag::warn_cuda_maxclusterrank_sm_90)
5725 << CudaArchToString(SM) << CI << MaxBlocks->getSourceRange();
5726 // Ignore it by setting MaxBlocks to null;
5727 MaxBlocks = nullptr;
5728 } else {
5729 MaxBlocks = makeLaunchBoundsArgExpr(*this, MaxBlocks, TmpAttr, 2);
5730 if (!MaxBlocks)
5731 return nullptr;
5732 }
5733 }
5734
5735 return ::new (Context)
5736 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
5737}
5738
5739void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
5740 Expr *MaxThreads, Expr *MinBlocks,
5741 Expr *MaxBlocks) {
5742 if (auto *Attr = CreateLaunchBoundsAttr(CI, MaxThreads, MinBlocks, MaxBlocks))
5743 D->addAttr(A: Attr);
5744}
5745
5746static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5747 if (!AL.checkAtLeastNumArgs(S, Num: 1) || !AL.checkAtMostNumArgs(S, Num: 3))
5748 return;
5749
5750 S.AddLaunchBoundsAttr(D, CI: AL, MaxThreads: AL.getArgAsExpr(Arg: 0),
5751 MinBlocks: AL.getNumArgs() > 1 ? AL.getArgAsExpr(Arg: 1) : nullptr,
5752 MaxBlocks: AL.getNumArgs() > 2 ? AL.getArgAsExpr(Arg: 2) : nullptr);
5753}
5754
5755static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
5756 const ParsedAttr &AL) {
5757 if (!AL.isArgIdent(Arg: 0)) {
5758 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5759 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
5760 return;
5761 }
5762
5763 ParamIdx ArgumentIdx;
5764 if (!checkFunctionOrMethodParameterIndex(S, D, AI: AL, AttrArgNum: 2, IdxExpr: AL.getArgAsExpr(Arg: 1),
5765 Idx&: ArgumentIdx))
5766 return;
5767
5768 ParamIdx TypeTagIdx;
5769 if (!checkFunctionOrMethodParameterIndex(S, D, AI: AL, AttrArgNum: 3, IdxExpr: AL.getArgAsExpr(Arg: 2),
5770 Idx&: TypeTagIdx))
5771 return;
5772
5773 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
5774 if (IsPointer) {
5775 // Ensure that buffer has a pointer type.
5776 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
5777 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
5778 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
5779 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
5780 }
5781
5782 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
5783 S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
5784 IsPointer));
5785}
5786
5787static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
5788 const ParsedAttr &AL) {
5789 if (!AL.isArgIdent(Arg: 0)) {
5790 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5791 << AL << 1 << AANT_ArgumentIdentifier;
5792 return;
5793 }
5794
5795 if (!AL.checkExactlyNumArgs(S, Num: 1))
5796 return;
5797
5798 if (!isa<VarDecl>(Val: D)) {
5799 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
5800 << AL << AL.isRegularKeywordAttribute() << ExpectedVariable;
5801 return;
5802 }
5803
5804 IdentifierInfo *PointerKind = AL.getArgAsIdent(Arg: 0)->Ident;
5805 TypeSourceInfo *MatchingCTypeLoc = nullptr;
5806 S.GetTypeFromParser(Ty: AL.getMatchingCType(), TInfo: &MatchingCTypeLoc);
5807 assert(MatchingCTypeLoc && "no type source info for attribute argument");
5808
5809 D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
5810 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
5811 AL.getMustBeNull()));
5812}
5813
5814static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5815 ParamIdx ArgCount;
5816
5817 if (!checkFunctionOrMethodParameterIndex(S, D, AI: AL, AttrArgNum: 1, IdxExpr: AL.getArgAsExpr(Arg: 0),
5818 Idx&: ArgCount,
5819 CanIndexImplicitThis: true /* CanIndexImplicitThis */))
5820 return;
5821
5822 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
5823 D->addAttr(::new (S.Context)
5824 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
5825}
5826
5827static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
5828 const ParsedAttr &AL) {
5829 uint32_t Count = 0, Offset = 0;
5830 if (!checkUInt32Argument(S, AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Count, Idx: 0, StrictlyUnsigned: true))
5831 return;
5832 if (AL.getNumArgs() == 2) {
5833 Expr *Arg = AL.getArgAsExpr(Arg: 1);
5834 if (!checkUInt32Argument(S, AI: AL, Expr: Arg, Val&: Offset, Idx: 1, StrictlyUnsigned: true))
5835 return;
5836 if (Count < Offset) {
5837 S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
5838 << &AL << 0 << Count << Arg->getBeginLoc();
5839 return;
5840 }
5841 }
5842 D->addAttr(::new (S.Context)
5843 PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
5844}
5845
5846namespace {
5847struct IntrinToName {
5848 uint32_t Id;
5849 int32_t FullName;
5850 int32_t ShortName;
5851};
5852} // unnamed namespace
5853
5854static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
5855 ArrayRef<IntrinToName> Map,
5856 const char *IntrinNames) {
5857 AliasName.consume_front(Prefix: "__arm_");
5858 const IntrinToName *It =
5859 llvm::lower_bound(Range&: Map, Value&: BuiltinID, C: [](const IntrinToName &L, unsigned Id) {
5860 return L.Id < Id;
5861 });
5862 if (It == Map.end() || It->Id != BuiltinID)
5863 return false;
5864 StringRef FullName(&IntrinNames[It->FullName]);
5865 if (AliasName == FullName)
5866 return true;
5867 if (It->ShortName == -1)
5868 return false;
5869 StringRef ShortName(&IntrinNames[It->ShortName]);
5870 return AliasName == ShortName;
5871}
5872
5873static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
5874#include "clang/Basic/arm_mve_builtin_aliases.inc"
5875 // The included file defines:
5876 // - ArrayRef<IntrinToName> Map
5877 // - const char IntrinNames[]
5878 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5879}
5880
5881static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
5882#include "clang/Basic/arm_cde_builtin_aliases.inc"
5883 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
5884}
5885
5886static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
5887 StringRef AliasName) {
5888 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
5889 BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID);
5890 return BuiltinID >= AArch64::FirstSVEBuiltin &&
5891 BuiltinID <= AArch64::LastSVEBuiltin;
5892}
5893
5894static bool ArmSmeAliasValid(ASTContext &Context, unsigned BuiltinID,
5895 StringRef AliasName) {
5896 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID))
5897 BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID);
5898 return BuiltinID >= AArch64::FirstSMEBuiltin &&
5899 BuiltinID <= AArch64::LastSMEBuiltin;
5900}
5901
5902static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5903 if (!AL.isArgIdent(Arg: 0)) {
5904 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5905 << AL << 1 << AANT_ArgumentIdentifier;
5906 return;
5907 }
5908
5909 IdentifierInfo *Ident = AL.getArgAsIdent(Arg: 0)->Ident;
5910 unsigned BuiltinID = Ident->getBuiltinID();
5911 StringRef AliasName = cast<FunctionDecl>(Val: D)->getIdentifier()->getName();
5912
5913 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5914 if ((IsAArch64 && !ArmSveAliasValid(Context&: S.Context, BuiltinID, AliasName) &&
5915 !ArmSmeAliasValid(Context&: S.Context, BuiltinID, AliasName)) ||
5916 (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
5917 !ArmCdeAliasValid(BuiltinID, AliasName))) {
5918 S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
5919 return;
5920 }
5921
5922 D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
5923}
5924
5925static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) {
5926 return BuiltinID >= RISCV::FirstRVVBuiltin &&
5927 BuiltinID <= RISCV::LastRVVBuiltin;
5928}
5929
5930static void handleBuiltinAliasAttr(Sema &S, Decl *D,
5931 const ParsedAttr &AL) {
5932 if (!AL.isArgIdent(Arg: 0)) {
5933 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5934 << AL << 1 << AANT_ArgumentIdentifier;
5935 return;
5936 }
5937
5938 IdentifierInfo *Ident = AL.getArgAsIdent(Arg: 0)->Ident;
5939 unsigned BuiltinID = Ident->getBuiltinID();
5940 StringRef AliasName = cast<FunctionDecl>(Val: D)->getIdentifier()->getName();
5941
5942 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5943 bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
5944 bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
5945 bool IsHLSL = S.Context.getLangOpts().HLSL;
5946 if ((IsAArch64 && !ArmSveAliasValid(Context&: S.Context, BuiltinID, AliasName)) ||
5947 (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) &&
5948 !ArmCdeAliasValid(BuiltinID, AliasName)) ||
5949 (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) ||
5950 (!IsAArch64 && !IsARM && !IsRISCV && !IsHLSL)) {
5951 S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL;
5952 return;
5953 }
5954
5955 D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
5956}
5957
5958static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5959 if (!AL.hasParsedType()) {
5960 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
5961 return;
5962 }
5963
5964 TypeSourceInfo *ParmTSI = nullptr;
5965 QualType QT = S.GetTypeFromParser(Ty: AL.getTypeArg(), TInfo: &ParmTSI);
5966 assert(ParmTSI && "no type source info for attribute argument");
5967 S.RequireCompleteType(ParmTSI->getTypeLoc().getBeginLoc(), QT,
5968 diag::err_incomplete_type);
5969
5970 D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
5971}
5972
5973//===----------------------------------------------------------------------===//
5974// Checker-specific attribute handlers.
5975//===----------------------------------------------------------------------===//
5976static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
5977 return QT->isDependentType() || QT->isObjCRetainableType();
5978}
5979
5980static bool isValidSubjectOfNSAttribute(QualType QT) {
5981 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
5982 QT->isObjCNSObjectType();
5983}
5984
5985static bool isValidSubjectOfCFAttribute(QualType QT) {
5986 return QT->isDependentType() || QT->isPointerType() ||
5987 isValidSubjectOfNSAttribute(QT);
5988}
5989
5990static bool isValidSubjectOfOSAttribute(QualType QT) {
5991 if (QT->isDependentType())
5992 return true;
5993 QualType PT = QT->getPointeeType();
5994 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5995}
5996
5997void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
5998 RetainOwnershipKind K,
5999 bool IsTemplateInstantiation) {
6000 ValueDecl *VD = cast<ValueDecl>(Val: D);
6001 switch (K) {
6002 case RetainOwnershipKind::OS:
6003 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
6004 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
6005 diag::warn_ns_attribute_wrong_parameter_type,
6006 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
6007 return;
6008 case RetainOwnershipKind::NS:
6009 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
6010 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
6011
6012 // These attributes are normally just advisory, but in ARC, ns_consumed
6013 // is significant. Allow non-dependent code to contain inappropriate
6014 // attributes even in ARC, but require template instantiations to be
6015 // set up correctly.
6016 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
6017 ? diag::err_ns_attribute_wrong_parameter_type
6018 : diag::warn_ns_attribute_wrong_parameter_type),
6019 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
6020 return;
6021 case RetainOwnershipKind::CF:
6022 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
6023 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
6024 diag::warn_ns_attribute_wrong_parameter_type,
6025 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
6026 return;
6027 }
6028}
6029
6030static Sema::RetainOwnershipKind
6031parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
6032 switch (AL.getKind()) {
6033 case ParsedAttr::AT_CFConsumed:
6034 case ParsedAttr::AT_CFReturnsRetained:
6035 case ParsedAttr::AT_CFReturnsNotRetained:
6036 return Sema::RetainOwnershipKind::CF;
6037 case ParsedAttr::AT_OSConsumesThis:
6038 case ParsedAttr::AT_OSConsumed:
6039 case ParsedAttr::AT_OSReturnsRetained:
6040 case ParsedAttr::AT_OSReturnsNotRetained:
6041 case ParsedAttr::AT_OSReturnsRetainedOnZero:
6042 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
6043 return Sema::RetainOwnershipKind::OS;
6044 case ParsedAttr::AT_NSConsumesSelf:
6045 case ParsedAttr::AT_NSConsumed:
6046 case ParsedAttr::AT_NSReturnsRetained:
6047 case ParsedAttr::AT_NSReturnsNotRetained:
6048 case ParsedAttr::AT_NSReturnsAutoreleased:
6049 return Sema::RetainOwnershipKind::NS;
6050 default:
6051 llvm_unreachable("Wrong argument supplied");
6052 }
6053}
6054
6055bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
6056 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
6057 return false;
6058
6059 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
6060 << "'ns_returns_retained'" << 0 << 0;
6061 return true;
6062}
6063
6064/// \return whether the parameter is a pointer to OSObject pointer.
6065static bool isValidOSObjectOutParameter(const Decl *D) {
6066 const auto *PVD = dyn_cast<ParmVarDecl>(Val: D);
6067 if (!PVD)
6068 return false;
6069 QualType QT = PVD->getType();
6070 QualType PT = QT->getPointeeType();
6071 return !PT.isNull() && isValidSubjectOfOSAttribute(QT: PT);
6072}
6073
6074static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
6075 const ParsedAttr &AL) {
6076 QualType ReturnType;
6077 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
6078
6079 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
6080 ReturnType = MD->getReturnType();
6081 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
6082 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
6083 return; // ignore: was handled as a type attribute
6084 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(Val: D)) {
6085 ReturnType = PD->getType();
6086 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6087 ReturnType = FD->getReturnType();
6088 } else if (const auto *Param = dyn_cast<ParmVarDecl>(Val: D)) {
6089 // Attributes on parameters are used for out-parameters,
6090 // passed as pointers-to-pointers.
6091 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
6092 ? /*pointer-to-CF-pointer*/2
6093 : /*pointer-to-OSObject-pointer*/3;
6094 ReturnType = Param->getType()->getPointeeType();
6095 if (ReturnType.isNull()) {
6096 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
6097 << AL << DiagID << AL.getRange();
6098 return;
6099 }
6100 } else if (AL.isUsedAsTypeAttr()) {
6101 return;
6102 } else {
6103 AttributeDeclKind ExpectedDeclKind;
6104 switch (AL.getKind()) {
6105 default: llvm_unreachable("invalid ownership attribute");
6106 case ParsedAttr::AT_NSReturnsRetained:
6107 case ParsedAttr::AT_NSReturnsAutoreleased:
6108 case ParsedAttr::AT_NSReturnsNotRetained:
6109 ExpectedDeclKind = ExpectedFunctionOrMethod;
6110 break;
6111
6112 case ParsedAttr::AT_OSReturnsRetained:
6113 case ParsedAttr::AT_OSReturnsNotRetained:
6114 case ParsedAttr::AT_CFReturnsRetained:
6115 case ParsedAttr::AT_CFReturnsNotRetained:
6116 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
6117 break;
6118 }
6119 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
6120 << AL.getRange() << AL << AL.isRegularKeywordAttribute()
6121 << ExpectedDeclKind;
6122 return;
6123 }
6124
6125 bool TypeOK;
6126 bool Cf;
6127 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
6128 switch (AL.getKind()) {
6129 default: llvm_unreachable("invalid ownership attribute");
6130 case ParsedAttr::AT_NSReturnsRetained:
6131 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(QT: ReturnType);
6132 Cf = false;
6133 break;
6134
6135 case ParsedAttr::AT_NSReturnsAutoreleased:
6136 case ParsedAttr::AT_NSReturnsNotRetained:
6137 TypeOK = isValidSubjectOfNSAttribute(QT: ReturnType);
6138 Cf = false;
6139 break;
6140
6141 case ParsedAttr::AT_CFReturnsRetained:
6142 case ParsedAttr::AT_CFReturnsNotRetained:
6143 TypeOK = isValidSubjectOfCFAttribute(QT: ReturnType);
6144 Cf = true;
6145 break;
6146
6147 case ParsedAttr::AT_OSReturnsRetained:
6148 case ParsedAttr::AT_OSReturnsNotRetained:
6149 TypeOK = isValidSubjectOfOSAttribute(QT: ReturnType);
6150 Cf = true;
6151 ParmDiagID = 3; // Pointer-to-OSObject-pointer
6152 break;
6153 }
6154
6155 if (!TypeOK) {
6156 if (AL.isUsedAsTypeAttr())
6157 return;
6158
6159 if (isa<ParmVarDecl>(Val: D)) {
6160 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
6161 << AL << ParmDiagID << AL.getRange();
6162 } else {
6163 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
6164 enum : unsigned {
6165 Function,
6166 Method,
6167 Property
6168 } SubjectKind = Function;
6169 if (isa<ObjCMethodDecl>(Val: D))
6170 SubjectKind = Method;
6171 else if (isa<ObjCPropertyDecl>(Val: D))
6172 SubjectKind = Property;
6173 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
6174 << AL << SubjectKind << Cf << AL.getRange();
6175 }
6176 return;
6177 }
6178
6179 switch (AL.getKind()) {
6180 default:
6181 llvm_unreachable("invalid ownership attribute");
6182 case ParsedAttr::AT_NSReturnsAutoreleased:
6183 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
6184 return;
6185 case ParsedAttr::AT_CFReturnsNotRetained:
6186 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
6187 return;
6188 case ParsedAttr::AT_NSReturnsNotRetained:
6189 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
6190 return;
6191 case ParsedAttr::AT_CFReturnsRetained:
6192 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
6193 return;
6194 case ParsedAttr::AT_NSReturnsRetained:
6195 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
6196 return;
6197 case ParsedAttr::AT_OSReturnsRetained:
6198 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
6199 return;
6200 case ParsedAttr::AT_OSReturnsNotRetained:
6201 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
6202 return;
6203 };
6204}
6205
6206static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
6207 const ParsedAttr &Attrs) {
6208 const int EP_ObjCMethod = 1;
6209 const int EP_ObjCProperty = 2;
6210
6211 SourceLocation loc = Attrs.getLoc();
6212 QualType resultType;
6213 if (isa<ObjCMethodDecl>(Val: D))
6214 resultType = cast<ObjCMethodDecl>(Val: D)->getReturnType();
6215 else
6216 resultType = cast<ObjCPropertyDecl>(Val: D)->getType();
6217
6218 if (!resultType->isReferenceType() &&
6219 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
6220 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
6221 << SourceRange(loc) << Attrs
6222 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
6223 << /*non-retainable pointer*/ 2;
6224
6225 // Drop the attribute.
6226 return;
6227 }
6228
6229 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
6230}
6231
6232static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
6233 const ParsedAttr &Attrs) {
6234 const auto *Method = cast<ObjCMethodDecl>(Val: D);
6235
6236 const DeclContext *DC = Method->getDeclContext();
6237 if (const auto *PDecl = dyn_cast_if_present<ObjCProtocolDecl>(DC)) {
6238 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
6239 << 0;
6240 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
6241 return;
6242 }
6243 if (Method->getMethodFamily() == OMF_dealloc) {
6244 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
6245 << 1;
6246 return;
6247 }
6248
6249 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
6250}
6251
6252static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
6253 if (!isa<TagDecl>(Val: D)) {
6254 S.Diag(D->getBeginLoc(), diag::err_nserrordomain_invalid_decl) << 0;
6255 return;
6256 }
6257
6258 IdentifierLoc *IdentLoc =
6259 Attr.isArgIdent(Arg: 0) ? Attr.getArgAsIdent(Arg: 0) : nullptr;
6260 if (!IdentLoc || !IdentLoc->Ident) {
6261 // Try to locate the argument directly.
6262 SourceLocation Loc = Attr.getLoc();
6263 if (Attr.isArgExpr(Arg: 0) && Attr.getArgAsExpr(Arg: 0))
6264 Loc = Attr.getArgAsExpr(Arg: 0)->getBeginLoc();
6265
6266 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
6267 return;
6268 }
6269
6270 // Verify that the identifier is a valid decl in the C decl namespace.
6271 LookupResult Result(S, DeclarationName(IdentLoc->Ident), SourceLocation(),
6272 Sema::LookupNameKind::LookupOrdinaryName);
6273 if (!S.LookupName(R&: Result, S: S.TUScope) || !Result.getAsSingle<VarDecl>()) {
6274 S.Diag(IdentLoc->Loc, diag::err_nserrordomain_invalid_decl)
6275 << 1 << IdentLoc->Ident;
6276 return;
6277 }
6278
6279 D->addAttr(::new (S.Context)
6280 NSErrorDomainAttr(S.Context, Attr, IdentLoc->Ident));
6281}
6282
6283static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6284 IdentifierLoc *Parm = AL.isArgIdent(Arg: 0) ? AL.getArgAsIdent(Arg: 0) : nullptr;
6285
6286 if (!Parm) {
6287 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6288 return;
6289 }
6290
6291 // Typedefs only allow objc_bridge(id) and have some additional checking.
6292 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D)) {
6293 if (!Parm->Ident->isStr(Str: "id")) {
6294 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
6295 return;
6296 }
6297
6298 // Only allow 'cv void *'.
6299 QualType T = TD->getUnderlyingType();
6300 if (!T->isVoidPointerType()) {
6301 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
6302 return;
6303 }
6304 }
6305
6306 D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
6307}
6308
6309static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
6310 const ParsedAttr &AL) {
6311 IdentifierLoc *Parm = AL.isArgIdent(Arg: 0) ? AL.getArgAsIdent(Arg: 0) : nullptr;
6312
6313 if (!Parm) {
6314 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6315 return;
6316 }
6317
6318 D->addAttr(::new (S.Context)
6319 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
6320}
6321
6322static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
6323 const ParsedAttr &AL) {
6324 IdentifierInfo *RelatedClass =
6325 AL.isArgIdent(Arg: 0) ? AL.getArgAsIdent(Arg: 0)->Ident : nullptr;
6326 if (!RelatedClass) {
6327 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
6328 return;
6329 }
6330 IdentifierInfo *ClassMethod =
6331 AL.getArgAsIdent(Arg: 1) ? AL.getArgAsIdent(Arg: 1)->Ident : nullptr;
6332 IdentifierInfo *InstanceMethod =
6333 AL.getArgAsIdent(Arg: 2) ? AL.getArgAsIdent(Arg: 2)->Ident : nullptr;
6334 D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
6335 S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
6336}
6337
6338static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
6339 const ParsedAttr &AL) {
6340 DeclContext *Ctx = D->getDeclContext();
6341
6342 // This attribute can only be applied to methods in interfaces or class
6343 // extensions.
6344 if (!isa<ObjCInterfaceDecl>(Val: Ctx) &&
6345 !(isa<ObjCCategoryDecl>(Val: Ctx) &&
6346 cast<ObjCCategoryDecl>(Val: Ctx)->IsClassExtension())) {
6347 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
6348 return;
6349 }
6350
6351 ObjCInterfaceDecl *IFace;
6352 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Val: Ctx))
6353 IFace = CatDecl->getClassInterface();
6354 else
6355 IFace = cast<ObjCInterfaceDecl>(Val: Ctx);
6356
6357 if (!IFace)
6358 return;
6359
6360 IFace->setHasDesignatedInitializers();
6361 D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
6362}
6363
6364static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
6365 StringRef MetaDataName;
6366 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: MetaDataName))
6367 return;
6368 D->addAttr(::new (S.Context)
6369 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
6370}
6371
6372// When a user wants to use objc_boxable with a union or struct
6373// but they don't have access to the declaration (legacy/third-party code)
6374// then they can 'enable' this feature with a typedef:
6375// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
6376static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
6377 bool notify = false;
6378
6379 auto *RD = dyn_cast<RecordDecl>(Val: D);
6380 if (RD && RD->getDefinition()) {
6381 RD = RD->getDefinition();
6382 notify = true;
6383 }
6384
6385 if (RD) {
6386 ObjCBoxableAttr *BoxableAttr =
6387 ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
6388 RD->addAttr(A: BoxableAttr);
6389 if (notify) {
6390 // we need to notify ASTReader/ASTWriter about
6391 // modification of existing declaration
6392 if (ASTMutationListener *L = S.getASTMutationListener())
6393 L->AddedAttributeToRecord(Attr: BoxableAttr, Record: RD);
6394 }
6395 }
6396}
6397
6398static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6399 if (hasDeclarator(D))
6400 return;
6401
6402 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
6403 << AL.getRange() << AL << AL.isRegularKeywordAttribute()
6404 << ExpectedVariable;
6405}
6406
6407static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
6408 const ParsedAttr &AL) {
6409 const auto *VD = cast<ValueDecl>(Val: D);
6410 QualType QT = VD->getType();
6411
6412 if (!QT->isDependentType() &&
6413 !QT->isObjCLifetimeType()) {
6414 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
6415 << QT;
6416 return;
6417 }
6418
6419 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
6420
6421 // If we have no lifetime yet, check the lifetime we're presumably
6422 // going to infer.
6423 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
6424 Lifetime = QT->getObjCARCImplicitLifetime();
6425
6426 switch (Lifetime) {
6427 case Qualifiers::OCL_None:
6428 assert(QT->isDependentType() &&
6429 "didn't infer lifetime for non-dependent type?");
6430 break;
6431
6432 case Qualifiers::OCL_Weak: // meaningful
6433 case Qualifiers::OCL_Strong: // meaningful
6434 break;
6435
6436 case Qualifiers::OCL_ExplicitNone:
6437 case Qualifiers::OCL_Autoreleasing:
6438 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
6439 << (Lifetime == Qualifiers::OCL_Autoreleasing);
6440 break;
6441 }
6442
6443 D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
6444}
6445
6446static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6447 // Make sure that there is a string literal as the annotation's single
6448 // argument.
6449 StringRef Str;
6450 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
6451 return;
6452
6453 D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
6454}
6455
6456static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
6457 // Make sure that there is a string literal as the annotation's single
6458 // argument.
6459 StringRef BT;
6460 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: BT))
6461 return;
6462
6463 // Warn about duplicate attributes if they have different arguments, but drop
6464 // any duplicate attributes regardless.
6465 if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
6466 if (Other->getSwiftType() != BT)
6467 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
6468 return;
6469 }
6470
6471 D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
6472}
6473
6474static bool isErrorParameter(Sema &S, QualType QT) {
6475 const auto *PT = QT->getAs<PointerType>();
6476 if (!PT)
6477 return false;
6478
6479 QualType Pointee = PT->getPointeeType();
6480
6481 // Check for NSError**.
6482 if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
6483 if (const auto *ID = OPT->getInterfaceDecl())
6484 if (ID->getIdentifier() == S.getNSErrorIdent())
6485 return true;
6486
6487 // Check for CFError**.
6488 if (const auto *PT = Pointee->getAs<PointerType>())
6489 if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
6490 if (S.isCFError(D: RT->getDecl()))
6491 return true;
6492
6493 return false;
6494}
6495
6496static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
6497 auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6498 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6499 if (isErrorParameter(S, QT: getFunctionOrMethodParamType(D, Idx: I)))
6500 return true;
6501 }
6502
6503 S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
6504 << AL << isa<ObjCMethodDecl>(D);
6505 return false;
6506 };
6507
6508 auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6509 // - C, ObjC, and block pointers are definitely okay.
6510 // - References are definitely not okay.
6511 // - nullptr_t is weird, but acceptable.
6512 QualType RT = getFunctionOrMethodResultType(D);
6513 if (RT->hasPointerRepresentation() && !RT->isReferenceType())
6514 return true;
6515
6516 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
6517 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
6518 << /*pointer*/ 1;
6519 return false;
6520 };
6521
6522 auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
6523 QualType RT = getFunctionOrMethodResultType(D);
6524 if (RT->isIntegralType(Ctx: S.Context))
6525 return true;
6526
6527 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
6528 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
6529 << /*integral*/ 0;
6530 return false;
6531 };
6532
6533 if (D->isInvalidDecl())
6534 return;
6535
6536 IdentifierLoc *Loc = AL.getArgAsIdent(Arg: 0);
6537 SwiftErrorAttr::ConventionKind Convention;
6538 if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
6539 Convention)) {
6540 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6541 << AL << Loc->Ident;
6542 return;
6543 }
6544
6545 switch (Convention) {
6546 case SwiftErrorAttr::None:
6547 // No additional validation required.
6548 break;
6549
6550 case SwiftErrorAttr::NonNullError:
6551 if (!hasErrorParameter(S, D, AL))
6552 return;
6553 break;
6554
6555 case SwiftErrorAttr::NullResult:
6556 if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
6557 return;
6558 break;
6559
6560 case SwiftErrorAttr::NonZeroResult:
6561 case SwiftErrorAttr::ZeroResult:
6562 if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
6563 return;
6564 break;
6565 }
6566
6567 D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
6568}
6569
6570static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
6571 const SwiftAsyncErrorAttr *ErrorAttr,
6572 const SwiftAsyncAttr *AsyncAttr) {
6573 if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
6574 if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
6575 S.Diag(AsyncAttr->getLocation(),
6576 diag::err_swift_async_error_without_swift_async)
6577 << AsyncAttr << isa<ObjCMethodDecl>(D);
6578 }
6579 return;
6580 }
6581
6582 const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
6583 D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
6584 // handleSwiftAsyncAttr already verified the type is correct, so no need to
6585 // double-check it here.
6586 const auto *FuncTy = HandlerParam->getType()
6587 ->castAs<BlockPointerType>()
6588 ->getPointeeType()
6589 ->getAs<FunctionProtoType>();
6590 ArrayRef<QualType> BlockParams;
6591 if (FuncTy)
6592 BlockParams = FuncTy->getParamTypes();
6593
6594 switch (ErrorAttr->getConvention()) {
6595 case SwiftAsyncErrorAttr::ZeroArgument:
6596 case SwiftAsyncErrorAttr::NonZeroArgument: {
6597 uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
6598 if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
6599 S.Diag(ErrorAttr->getLocation(),
6600 diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2;
6601 return;
6602 }
6603 QualType ErrorParam = BlockParams[ParamIdx - 1];
6604 if (!ErrorParam->isIntegralType(Ctx: S.Context)) {
6605 StringRef ConvStr =
6606 ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
6607 ? "zero_argument"
6608 : "nonzero_argument";
6609 S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
6610 << ErrorAttr << ConvStr << ParamIdx << ErrorParam;
6611 return;
6612 }
6613 break;
6614 }
6615 case SwiftAsyncErrorAttr::NonNullError: {
6616 bool AnyErrorParams = false;
6617 for (QualType Param : BlockParams) {
6618 // Check for NSError *.
6619 if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
6620 if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
6621 if (ID->getIdentifier() == S.getNSErrorIdent()) {
6622 AnyErrorParams = true;
6623 break;
6624 }
6625 }
6626 }
6627 // Check for CFError *.
6628 if (const auto *PtrTy = Param->getAs<PointerType>()) {
6629 if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
6630 if (S.isCFError(D: RT->getDecl())) {
6631 AnyErrorParams = true;
6632 break;
6633 }
6634 }
6635 }
6636 }
6637
6638 if (!AnyErrorParams) {
6639 S.Diag(ErrorAttr->getLocation(),
6640 diag::err_swift_async_error_no_error_parameter)
6641 << ErrorAttr << isa<ObjCMethodDecl>(D);
6642 return;
6643 }
6644 break;
6645 }
6646 case SwiftAsyncErrorAttr::None:
6647 break;
6648 }
6649}
6650
6651static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) {
6652 IdentifierLoc *IDLoc = AL.getArgAsIdent(Arg: 0);
6653 SwiftAsyncErrorAttr::ConventionKind ConvKind;
6654 if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
6655 ConvKind)) {
6656 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
6657 << AL << IDLoc->Ident;
6658 return;
6659 }
6660
6661 uint32_t ParamIdx = 0;
6662 switch (ConvKind) {
6663 case SwiftAsyncErrorAttr::ZeroArgument:
6664 case SwiftAsyncErrorAttr::NonZeroArgument: {
6665 if (!AL.checkExactlyNumArgs(S, Num: 2))
6666 return;
6667
6668 Expr *IdxExpr = AL.getArgAsExpr(Arg: 1);
6669 if (!checkUInt32Argument(S, AI: AL, Expr: IdxExpr, Val&: ParamIdx))
6670 return;
6671 break;
6672 }
6673 case SwiftAsyncErrorAttr::NonNullError:
6674 case SwiftAsyncErrorAttr::None: {
6675 if (!AL.checkExactlyNumArgs(S, Num: 1))
6676 return;
6677 break;
6678 }
6679 }
6680
6681 auto *ErrorAttr =
6682 ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx);
6683 D->addAttr(A: ErrorAttr);
6684
6685 if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
6686 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
6687}
6688
6689// For a function, this will validate a compound Swift name, e.g.
6690// <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
6691// the function will output the number of parameter names, and whether this is a
6692// single-arg initializer.
6693//
6694// For a type, enum constant, property, or variable declaration, this will
6695// validate either a simple identifier, or a qualified
6696// <code>context.identifier</code> name.
6697static bool
6698validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
6699 StringRef Name, unsigned &SwiftParamCount,
6700 bool &IsSingleParamInit) {
6701 SwiftParamCount = 0;
6702 IsSingleParamInit = false;
6703
6704 // Check whether this will be mapped to a getter or setter of a property.
6705 bool IsGetter = false, IsSetter = false;
6706 if (Name.consume_front(Prefix: "getter:"))
6707 IsGetter = true;
6708 else if (Name.consume_front(Prefix: "setter:"))
6709 IsSetter = true;
6710
6711 if (Name.back() != ')') {
6712 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6713 return false;
6714 }
6715
6716 bool IsMember = false;
6717 StringRef ContextName, BaseName, Parameters;
6718
6719 std::tie(args&: BaseName, args&: Parameters) = Name.split(Separator: '(');
6720
6721 // Split at the first '.', if it exists, which separates the context name
6722 // from the base name.
6723 std::tie(args&: ContextName, args&: BaseName) = BaseName.split(Separator: '.');
6724 if (BaseName.empty()) {
6725 BaseName = ContextName;
6726 ContextName = StringRef();
6727 } else if (ContextName.empty() || !isValidAsciiIdentifier(S: ContextName)) {
6728 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6729 << AL << /*context*/ 1;
6730 return false;
6731 } else {
6732 IsMember = true;
6733 }
6734
6735 if (!isValidAsciiIdentifier(S: BaseName) || BaseName == "_") {
6736 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6737 << AL << /*basename*/ 0;
6738 return false;
6739 }
6740
6741 bool IsSubscript = BaseName == "subscript";
6742 // A subscript accessor must be a getter or setter.
6743 if (IsSubscript && !IsGetter && !IsSetter) {
6744 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6745 << AL << /* getter or setter */ 0;
6746 return false;
6747 }
6748
6749 if (Parameters.empty()) {
6750 S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
6751 return false;
6752 }
6753
6754 assert(Parameters.back() == ')' && "expected ')'");
6755 Parameters = Parameters.drop_back(); // ')'
6756
6757 if (Parameters.empty()) {
6758 // Setters and subscripts must have at least one parameter.
6759 if (IsSubscript) {
6760 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6761 << AL << /* have at least one parameter */1;
6762 return false;
6763 }
6764
6765 if (IsSetter) {
6766 S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
6767 return false;
6768 }
6769
6770 return true;
6771 }
6772
6773 if (Parameters.back() != ':') {
6774 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
6775 return false;
6776 }
6777
6778 StringRef CurrentParam;
6779 std::optional<unsigned> SelfLocation;
6780 unsigned NewValueCount = 0;
6781 std::optional<unsigned> NewValueLocation;
6782 do {
6783 std::tie(args&: CurrentParam, args&: Parameters) = Parameters.split(Separator: ':');
6784
6785 if (!isValidAsciiIdentifier(S: CurrentParam)) {
6786 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
6787 << AL << /*parameter*/2;
6788 return false;
6789 }
6790
6791 if (IsMember && CurrentParam == "self") {
6792 // "self" indicates the "self" argument for a member.
6793
6794 // More than one "self"?
6795 if (SelfLocation) {
6796 S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
6797 return false;
6798 }
6799
6800 // The "self" location is the current parameter.
6801 SelfLocation = SwiftParamCount;
6802 } else if (CurrentParam == "newValue") {
6803 // "newValue" indicates the "newValue" argument for a setter.
6804
6805 // There should only be one 'newValue', but it's only significant for
6806 // subscript accessors, so don't error right away.
6807 ++NewValueCount;
6808
6809 NewValueLocation = SwiftParamCount;
6810 }
6811
6812 ++SwiftParamCount;
6813 } while (!Parameters.empty());
6814
6815 // Only instance subscripts are currently supported.
6816 if (IsSubscript && !SelfLocation) {
6817 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
6818 << AL << /*have a 'self:' parameter*/2;
6819 return false;
6820 }
6821
6822 IsSingleParamInit =
6823 SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
6824
6825 // Check the number of parameters for a getter/setter.
6826 if (IsGetter || IsSetter) {
6827 // Setters have one parameter for the new value.
6828 unsigned NumExpectedParams = IsGetter ? 0 : 1;
6829 unsigned ParamDiag =
6830 IsGetter ? diag::warn_attr_swift_name_getter_parameters
6831 : diag::warn_attr_swift_name_setter_parameters;
6832
6833 // Instance methods have one parameter for "self".
6834 if (SelfLocation)
6835 ++NumExpectedParams;
6836
6837 // Subscripts may have additional parameters beyond the expected params for
6838 // the index.
6839 if (IsSubscript) {
6840 if (SwiftParamCount < NumExpectedParams) {
6841 S.Diag(Loc, DiagID: ParamDiag) << AL;
6842 return false;
6843 }
6844
6845 // A subscript setter must explicitly label its newValue parameter to
6846 // distinguish it from index parameters.
6847 if (IsSetter) {
6848 if (!NewValueLocation) {
6849 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
6850 << AL;
6851 return false;
6852 }
6853 if (NewValueCount > 1) {
6854 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
6855 << AL;
6856 return false;
6857 }
6858 } else {
6859 // Subscript getters should have no 'newValue:' parameter.
6860 if (NewValueLocation) {
6861 S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
6862 << AL;
6863 return false;
6864 }
6865 }
6866 } else {
6867 // Property accessors must have exactly the number of expected params.
6868 if (SwiftParamCount != NumExpectedParams) {
6869 S.Diag(Loc, DiagID: ParamDiag) << AL;
6870 return false;
6871 }
6872 }
6873 }
6874
6875 return true;
6876}
6877
6878bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
6879 const ParsedAttr &AL, bool IsAsync) {
6880 if (isa<ObjCMethodDecl>(Val: D) || isa<FunctionDecl>(Val: D)) {
6881 ArrayRef<ParmVarDecl*> Params;
6882 unsigned ParamCount;
6883
6884 if (const auto *Method = dyn_cast<ObjCMethodDecl>(Val: D)) {
6885 ParamCount = Method->getSelector().getNumArgs();
6886 Params = Method->parameters().slice(N: 0, M: ParamCount);
6887 } else {
6888 const auto *F = cast<FunctionDecl>(Val: D);
6889
6890 ParamCount = F->getNumParams();
6891 Params = F->parameters();
6892
6893 if (!F->hasWrittenPrototype()) {
6894 Diag(Loc, diag::warn_attribute_wrong_decl_type)
6895 << AL << AL.isRegularKeywordAttribute()
6896 << ExpectedFunctionWithProtoType;
6897 return false;
6898 }
6899 }
6900
6901 // The async name drops the last callback parameter.
6902 if (IsAsync) {
6903 if (ParamCount == 0) {
6904 Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
6905 << AL << isa<ObjCMethodDecl>(D);
6906 return false;
6907 }
6908 ParamCount -= 1;
6909 }
6910
6911 unsigned SwiftParamCount;
6912 bool IsSingleParamInit;
6913 if (!validateSwiftFunctionName(S&: *this, AL, Loc, Name,
6914 SwiftParamCount, IsSingleParamInit))
6915 return false;
6916
6917 bool ParamCountValid;
6918 if (SwiftParamCount == ParamCount) {
6919 ParamCountValid = true;
6920 } else if (SwiftParamCount > ParamCount) {
6921 ParamCountValid = IsSingleParamInit && ParamCount == 0;
6922 } else {
6923 // We have fewer Swift parameters than Objective-C parameters, but that
6924 // might be because we've transformed some of them. Check for potential
6925 // "out" parameters and err on the side of not warning.
6926 unsigned MaybeOutParamCount =
6927 llvm::count_if(Range&: Params, P: [](const ParmVarDecl *Param) -> bool {
6928 QualType ParamTy = Param->getType();
6929 if (ParamTy->isReferenceType() || ParamTy->isPointerType())
6930 return !ParamTy->getPointeeType().isConstQualified();
6931 return false;
6932 });
6933
6934 ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
6935 }
6936
6937 if (!ParamCountValid) {
6938 Diag(Loc, diag::warn_attr_swift_name_num_params)
6939 << (SwiftParamCount > ParamCount) << AL << ParamCount
6940 << SwiftParamCount;
6941 return false;
6942 }
6943 } else if ((isa<EnumConstantDecl>(Val: D) || isa<ObjCProtocolDecl>(Val: D) ||
6944 isa<ObjCInterfaceDecl>(Val: D) || isa<ObjCPropertyDecl>(Val: D) ||
6945 isa<VarDecl>(Val: D) || isa<TypedefNameDecl>(Val: D) || isa<TagDecl>(Val: D) ||
6946 isa<IndirectFieldDecl>(Val: D) || isa<FieldDecl>(Val: D)) &&
6947 !IsAsync) {
6948 StringRef ContextName, BaseName;
6949
6950 std::tie(args&: ContextName, args&: BaseName) = Name.split(Separator: '.');
6951 if (BaseName.empty()) {
6952 BaseName = ContextName;
6953 ContextName = StringRef();
6954 } else if (!isValidAsciiIdentifier(S: ContextName)) {
6955 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6956 << /*context*/1;
6957 return false;
6958 }
6959
6960 if (!isValidAsciiIdentifier(S: BaseName)) {
6961 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
6962 << /*basename*/0;
6963 return false;
6964 }
6965 } else {
6966 Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
6967 return false;
6968 }
6969 return true;
6970}
6971
6972static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
6973 StringRef Name;
6974 SourceLocation Loc;
6975 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Name, ArgLocation: &Loc))
6976 return;
6977
6978 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
6979 return;
6980
6981 D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
6982}
6983
6984static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
6985 StringRef Name;
6986 SourceLocation Loc;
6987 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Name, ArgLocation: &Loc))
6988 return;
6989
6990 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
6991 return;
6992
6993 D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
6994}
6995
6996static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
6997 // Make sure that there is an identifier as the annotation's single argument.
6998 if (!AL.checkExactlyNumArgs(S, Num: 1))
6999 return;
7000
7001 if (!AL.isArgIdent(Arg: 0)) {
7002 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7003 << AL << AANT_ArgumentIdentifier;
7004 return;
7005 }
7006
7007 SwiftNewTypeAttr::NewtypeKind Kind;
7008 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->Ident;
7009 if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
7010 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
7011 return;
7012 }
7013
7014 if (!isa<TypedefNameDecl>(Val: D)) {
7015 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
7016 << AL << AL.isRegularKeywordAttribute() << "typedefs";
7017 return;
7018 }
7019
7020 D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
7021}
7022
7023static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7024 if (!AL.isArgIdent(Arg: 0)) {
7025 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
7026 << AL << 1 << AANT_ArgumentIdentifier;
7027 return;
7028 }
7029
7030 SwiftAsyncAttr::Kind Kind;
7031 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->Ident;
7032 if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
7033 S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
7034 return;
7035 }
7036
7037 ParamIdx Idx;
7038 if (Kind == SwiftAsyncAttr::None) {
7039 // If this is 'none', then there shouldn't be any additional arguments.
7040 if (!AL.checkExactlyNumArgs(S, Num: 1))
7041 return;
7042 } else {
7043 // Non-none swift_async requires a completion handler index argument.
7044 if (!AL.checkExactlyNumArgs(S, Num: 2))
7045 return;
7046
7047 Expr *HandlerIdx = AL.getArgAsExpr(Arg: 1);
7048 if (!checkFunctionOrMethodParameterIndex(S, D, AI: AL, AttrArgNum: 2, IdxExpr: HandlerIdx, Idx))
7049 return;
7050
7051 const ParmVarDecl *CompletionBlock =
7052 getFunctionOrMethodParam(D, Idx: Idx.getASTIndex());
7053 QualType CompletionBlockType = CompletionBlock->getType();
7054 if (!CompletionBlockType->isBlockPointerType()) {
7055 S.Diag(CompletionBlock->getLocation(),
7056 diag::err_swift_async_bad_block_type)
7057 << CompletionBlock->getType();
7058 return;
7059 }
7060 QualType BlockTy =
7061 CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
7062 if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
7063 S.Diag(CompletionBlock->getLocation(),
7064 diag::err_swift_async_bad_block_type)
7065 << CompletionBlock->getType();
7066 return;
7067 }
7068 }
7069
7070 auto *AsyncAttr =
7071 ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx);
7072 D->addAttr(A: AsyncAttr);
7073
7074 if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
7075 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
7076}
7077
7078//===----------------------------------------------------------------------===//
7079// Microsoft specific attribute handlers.
7080//===----------------------------------------------------------------------===//
7081
7082UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
7083 StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
7084 if (const auto *UA = D->getAttr<UuidAttr>()) {
7085 if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
7086 return nullptr;
7087 if (!UA->getGuid().empty()) {
7088 Diag(UA->getLocation(), diag::err_mismatched_uuid);
7089 Diag(CI.getLoc(), diag::note_previous_uuid);
7090 D->dropAttr<UuidAttr>();
7091 }
7092 }
7093
7094 return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
7095}
7096
7097static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7098 if (!S.LangOpts.CPlusPlus) {
7099 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
7100 << AL << AttributeLangSupport::C;
7101 return;
7102 }
7103
7104 StringRef OrigStrRef;
7105 SourceLocation LiteralLoc;
7106 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: OrigStrRef, ArgLocation: &LiteralLoc))
7107 return;
7108
7109 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
7110 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
7111 StringRef StrRef = OrigStrRef;
7112 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
7113 StrRef = StrRef.drop_front().drop_back();
7114
7115 // Validate GUID length.
7116 if (StrRef.size() != 36) {
7117 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7118 return;
7119 }
7120
7121 for (unsigned i = 0; i < 36; ++i) {
7122 if (i == 8 || i == 13 || i == 18 || i == 23) {
7123 if (StrRef[i] != '-') {
7124 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7125 return;
7126 }
7127 } else if (!isHexDigit(c: StrRef[i])) {
7128 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
7129 return;
7130 }
7131 }
7132
7133 // Convert to our parsed format and canonicalize.
7134 MSGuidDecl::Parts Parsed;
7135 StrRef.substr(Start: 0, N: 8).getAsInteger(Radix: 16, Result&: Parsed.Part1);
7136 StrRef.substr(Start: 9, N: 4).getAsInteger(Radix: 16, Result&: Parsed.Part2);
7137 StrRef.substr(Start: 14, N: 4).getAsInteger(Radix: 16, Result&: Parsed.Part3);
7138 for (unsigned i = 0; i != 8; ++i)
7139 StrRef.substr(Start: 19 + 2 * i + (i >= 2 ? 1 : 0), N: 2)
7140 .getAsInteger(Radix: 16, Result&: Parsed.Part4And5[i]);
7141 MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
7142
7143 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
7144 // the only thing in the [] list, the [] too), and add an insertion of
7145 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
7146 // separating attributes nor of the [ and the ] are in the AST.
7147 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
7148 // on cfe-dev.
7149 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
7150 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
7151
7152 UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
7153 if (UA)
7154 D->addAttr(A: UA);
7155}
7156
7157static void handleHLSLNumThreadsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7158 llvm::VersionTuple SMVersion =
7159 S.Context.getTargetInfo().getTriple().getOSVersion();
7160 uint32_t ZMax = 1024;
7161 uint32_t ThreadMax = 1024;
7162 if (SMVersion.getMajor() <= 4) {
7163 ZMax = 1;
7164 ThreadMax = 768;
7165 } else if (SMVersion.getMajor() == 5) {
7166 ZMax = 64;
7167 ThreadMax = 1024;
7168 }
7169
7170 uint32_t X;
7171 if (!checkUInt32Argument(S, AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: X))
7172 return;
7173 if (X > 1024) {
7174 S.Diag(AL.getArgAsExpr(0)->getExprLoc(),
7175 diag::err_hlsl_numthreads_argument_oor) << 0 << 1024;
7176 return;
7177 }
7178 uint32_t Y;
7179 if (!checkUInt32Argument(S, AI: AL, Expr: AL.getArgAsExpr(Arg: 1), Val&: Y))
7180 return;
7181 if (Y > 1024) {
7182 S.Diag(AL.getArgAsExpr(1)->getExprLoc(),
7183 diag::err_hlsl_numthreads_argument_oor) << 1 << 1024;
7184 return;
7185 }
7186 uint32_t Z;
7187 if (!checkUInt32Argument(S, AI: AL, Expr: AL.getArgAsExpr(Arg: 2), Val&: Z))
7188 return;
7189 if (Z > ZMax) {
7190 S.Diag(AL.getArgAsExpr(2)->getExprLoc(),
7191 diag::err_hlsl_numthreads_argument_oor) << 2 << ZMax;
7192 return;
7193 }
7194
7195 if (X * Y * Z > ThreadMax) {
7196 S.Diag(AL.getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
7197 return;
7198 }
7199
7200 HLSLNumThreadsAttr *NewAttr = S.mergeHLSLNumThreadsAttr(D, AL, X, Y, Z);
7201 if (NewAttr)
7202 D->addAttr(A: NewAttr);
7203}
7204
7205HLSLNumThreadsAttr *Sema::mergeHLSLNumThreadsAttr(Decl *D,
7206 const AttributeCommonInfo &AL,
7207 int X, int Y, int Z) {
7208 if (HLSLNumThreadsAttr *NT = D->getAttr<HLSLNumThreadsAttr>()) {
7209 if (NT->getX() != X || NT->getY() != Y || NT->getZ() != Z) {
7210 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
7211 Diag(AL.getLoc(), diag::note_conflicting_attribute);
7212 }
7213 return nullptr;
7214 }
7215 return ::new (Context) HLSLNumThreadsAttr(Context, AL, X, Y, Z);
7216}
7217
7218static bool isLegalTypeForHLSLSV_DispatchThreadID(QualType T) {
7219 if (!T->hasUnsignedIntegerRepresentation())
7220 return false;
7221 if (const auto *VT = T->getAs<VectorType>())
7222 return VT->getNumElements() <= 3;
7223 return true;
7224}
7225
7226static void handleHLSLSV_DispatchThreadIDAttr(Sema &S, Decl *D,
7227 const ParsedAttr &AL) {
7228 // FIXME: support semantic on field.
7229 // See https://github.com/llvm/llvm-project/issues/57889.
7230 if (isa<FieldDecl>(Val: D)) {
7231 S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
7232 << AL << "parameter";
7233 return;
7234 }
7235
7236 auto *VD = cast<ValueDecl>(Val: D);
7237 if (!isLegalTypeForHLSLSV_DispatchThreadID(T: VD->getType())) {
7238 S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
7239 << AL << "uint/uint2/uint3";
7240 return;
7241 }
7242
7243 D->addAttr(::new (S.Context) HLSLSV_DispatchThreadIDAttr(S.Context, AL));
7244}
7245
7246static void handleHLSLShaderAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7247 StringRef Str;
7248 SourceLocation ArgLoc;
7249 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
7250 return;
7251
7252 HLSLShaderAttr::ShaderType ShaderType;
7253 if (!HLSLShaderAttr::ConvertStrToShaderType(Str, ShaderType)) {
7254 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
7255 << AL << Str << ArgLoc;
7256 return;
7257 }
7258
7259 // FIXME: check function match the shader stage.
7260
7261 HLSLShaderAttr *NewAttr = S.mergeHLSLShaderAttr(D, AL, ShaderType);
7262 if (NewAttr)
7263 D->addAttr(A: NewAttr);
7264}
7265
7266HLSLShaderAttr *
7267Sema::mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
7268 HLSLShaderAttr::ShaderType ShaderType) {
7269 if (HLSLShaderAttr *NT = D->getAttr<HLSLShaderAttr>()) {
7270 if (NT->getType() != ShaderType) {
7271 Diag(NT->getLocation(), diag::err_hlsl_attribute_param_mismatch) << AL;
7272 Diag(AL.getLoc(), diag::note_conflicting_attribute);
7273 }
7274 return nullptr;
7275 }
7276 return HLSLShaderAttr::Create(Context, ShaderType, AL);
7277}
7278
7279static void handleHLSLResourceBindingAttr(Sema &S, Decl *D,
7280 const ParsedAttr &AL) {
7281 StringRef Space = "space0";
7282 StringRef Slot = "";
7283
7284 if (!AL.isArgIdent(Arg: 0)) {
7285 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7286 << AL << AANT_ArgumentIdentifier;
7287 return;
7288 }
7289
7290 IdentifierLoc *Loc = AL.getArgAsIdent(Arg: 0);
7291 StringRef Str = Loc->Ident->getName();
7292 SourceLocation ArgLoc = Loc->Loc;
7293
7294 SourceLocation SpaceArgLoc;
7295 if (AL.getNumArgs() == 2) {
7296 Slot = Str;
7297 if (!AL.isArgIdent(Arg: 1)) {
7298 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7299 << AL << AANT_ArgumentIdentifier;
7300 return;
7301 }
7302
7303 IdentifierLoc *Loc = AL.getArgAsIdent(Arg: 1);
7304 Space = Loc->Ident->getName();
7305 SpaceArgLoc = Loc->Loc;
7306 } else {
7307 Slot = Str;
7308 }
7309
7310 // Validate.
7311 if (!Slot.empty()) {
7312 switch (Slot[0]) {
7313 case 'u':
7314 case 'b':
7315 case 's':
7316 case 't':
7317 break;
7318 default:
7319 S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_type)
7320 << Slot.substr(0, 1);
7321 return;
7322 }
7323
7324 StringRef SlotNum = Slot.substr(Start: 1);
7325 unsigned Num = 0;
7326 if (SlotNum.getAsInteger(Radix: 10, Result&: Num)) {
7327 S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_number);
7328 return;
7329 }
7330 }
7331
7332 if (!Space.starts_with(Prefix: "space")) {
7333 S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
7334 return;
7335 }
7336 StringRef SpaceNum = Space.substr(Start: 5);
7337 unsigned Num = 0;
7338 if (SpaceNum.getAsInteger(Radix: 10, Result&: Num)) {
7339 S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
7340 return;
7341 }
7342
7343 // FIXME: check reg type match decl. Issue
7344 // https://github.com/llvm/llvm-project/issues/57886.
7345 HLSLResourceBindingAttr *NewAttr =
7346 HLSLResourceBindingAttr::Create(S.getASTContext(), Slot, Space, AL);
7347 if (NewAttr)
7348 D->addAttr(A: NewAttr);
7349}
7350
7351static void handleHLSLParamModifierAttr(Sema &S, Decl *D,
7352 const ParsedAttr &AL) {
7353 HLSLParamModifierAttr *NewAttr = S.mergeHLSLParamModifierAttr(
7354 D, AL,
7355 static_cast<HLSLParamModifierAttr::Spelling>(AL.getSemanticSpelling()));
7356 if (NewAttr)
7357 D->addAttr(A: NewAttr);
7358}
7359
7360HLSLParamModifierAttr *
7361Sema::mergeHLSLParamModifierAttr(Decl *D, const AttributeCommonInfo &AL,
7362 HLSLParamModifierAttr::Spelling Spelling) {
7363 // We can only merge an `in` attribute with an `out` attribute. All other
7364 // combinations of duplicated attributes are ill-formed.
7365 if (HLSLParamModifierAttr *PA = D->getAttr<HLSLParamModifierAttr>()) {
7366 if ((PA->isIn() && Spelling == HLSLParamModifierAttr::Keyword_out) ||
7367 (PA->isOut() && Spelling == HLSLParamModifierAttr::Keyword_in)) {
7368 D->dropAttr<HLSLParamModifierAttr>();
7369 SourceRange AdjustedRange = {PA->getLocation(), AL.getRange().getEnd()};
7370 return HLSLParamModifierAttr::Create(
7371 Context, /*MergedSpelling=*/true, AdjustedRange,
7372 HLSLParamModifierAttr::Keyword_inout);
7373 }
7374 Diag(AL.getLoc(), diag::err_hlsl_duplicate_parameter_modifier) << AL;
7375 Diag(PA->getLocation(), diag::note_conflicting_attribute);
7376 return nullptr;
7377 }
7378 return HLSLParamModifierAttr::Create(Context, AL);
7379}
7380
7381static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7382 if (!S.LangOpts.CPlusPlus) {
7383 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
7384 << AL << AttributeLangSupport::C;
7385 return;
7386 }
7387 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
7388 D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
7389 if (IA) {
7390 D->addAttr(A: IA);
7391 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
7392 }
7393}
7394
7395static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7396 const auto *VD = cast<VarDecl>(Val: D);
7397 if (!S.Context.getTargetInfo().isTLSSupported()) {
7398 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
7399 return;
7400 }
7401 if (VD->getTSCSpec() != TSCS_unspecified) {
7402 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
7403 return;
7404 }
7405 if (VD->hasLocalStorage()) {
7406 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
7407 return;
7408 }
7409 D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
7410}
7411
7412static void handleMSConstexprAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7413 if (!S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2022_3)) {
7414 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7415 << AL << AL.getRange();
7416 return;
7417 }
7418 auto *FD = cast<FunctionDecl>(Val: D);
7419 if (FD->isConstexprSpecified() || FD->isConsteval()) {
7420 S.Diag(AL.getLoc(), diag::err_ms_constexpr_cannot_be_applied)
7421 << FD->isConsteval() << FD;
7422 return;
7423 }
7424 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
7425 if (!S.getLangOpts().CPlusPlus20 && MD->isVirtual()) {
7426 S.Diag(AL.getLoc(), diag::err_ms_constexpr_cannot_be_applied)
7427 << /*virtual*/ 2 << MD;
7428 return;
7429 }
7430 }
7431 D->addAttr(::new (S.Context) MSConstexprAttr(S.Context, AL));
7432}
7433
7434static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7435 SmallVector<StringRef, 4> Tags;
7436 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
7437 StringRef Tag;
7438 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: Tag))
7439 return;
7440 Tags.push_back(Elt: Tag);
7441 }
7442
7443 if (const auto *NS = dyn_cast<NamespaceDecl>(Val: D)) {
7444 if (!NS->isInline()) {
7445 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
7446 return;
7447 }
7448 if (NS->isAnonymousNamespace()) {
7449 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
7450 return;
7451 }
7452 if (AL.getNumArgs() == 0)
7453 Tags.push_back(Elt: NS->getName());
7454 } else if (!AL.checkAtLeastNumArgs(S, Num: 1))
7455 return;
7456
7457 // Store tags sorted and without duplicates.
7458 llvm::sort(C&: Tags);
7459 Tags.erase(CS: std::unique(first: Tags.begin(), last: Tags.end()), CE: Tags.end());
7460
7461 D->addAttr(::new (S.Context)
7462 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
7463}
7464
7465static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7466 // Check the attribute arguments.
7467 if (AL.getNumArgs() > 1) {
7468 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
7469 return;
7470 }
7471
7472 StringRef Str;
7473 SourceLocation ArgLoc;
7474
7475 if (AL.getNumArgs() == 0)
7476 Str = "";
7477 else if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
7478 return;
7479
7480 ARMInterruptAttr::InterruptType Kind;
7481 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7482 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
7483 << ArgLoc;
7484 return;
7485 }
7486
7487 D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
7488}
7489
7490static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7491 // MSP430 'interrupt' attribute is applied to
7492 // a function with no parameters and void return type.
7493 if (!isFunctionOrMethod(D)) {
7494 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7495 << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
7496 return;
7497 }
7498
7499 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7500 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7501 << /*MSP430*/ 1 << 0;
7502 return;
7503 }
7504
7505 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7506 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7507 << /*MSP430*/ 1 << 1;
7508 return;
7509 }
7510
7511 // The attribute takes one integer argument.
7512 if (!AL.checkExactlyNumArgs(S, Num: 1))
7513 return;
7514
7515 if (!AL.isArgExpr(Arg: 0)) {
7516 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7517 << AL << AANT_ArgumentIntegerConstant;
7518 return;
7519 }
7520
7521 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(Arg: 0));
7522 std::optional<llvm::APSInt> NumParams = llvm::APSInt(32);
7523 if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(Ctx: S.Context))) {
7524 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7525 << AL << AANT_ArgumentIntegerConstant
7526 << NumParamsExpr->getSourceRange();
7527 return;
7528 }
7529 // The argument should be in range 0..63.
7530 unsigned Num = NumParams->getLimitedValue(Limit: 255);
7531 if (Num > 63) {
7532 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7533 << AL << (int)NumParams->getSExtValue()
7534 << NumParamsExpr->getSourceRange();
7535 return;
7536 }
7537
7538 D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
7539 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7540}
7541
7542static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7543 // Only one optional argument permitted.
7544 if (AL.getNumArgs() > 1) {
7545 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
7546 return;
7547 }
7548
7549 StringRef Str;
7550 SourceLocation ArgLoc;
7551
7552 if (AL.getNumArgs() == 0)
7553 Str = "";
7554 else if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
7555 return;
7556
7557 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
7558 // a) Must be a function.
7559 // b) Must have no parameters.
7560 // c) Must have the 'void' return type.
7561 // d) Cannot have the 'mips16' attribute, as that instruction set
7562 // lacks the 'eret' instruction.
7563 // e) The attribute itself must either have no argument or one of the
7564 // valid interrupt types, see [MipsInterruptDocs].
7565
7566 if (!isFunctionOrMethod(D)) {
7567 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7568 << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
7569 return;
7570 }
7571
7572 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7573 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7574 << /*MIPS*/ 0 << 0;
7575 return;
7576 }
7577
7578 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7579 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7580 << /*MIPS*/ 0 << 1;
7581 return;
7582 }
7583
7584 // We still have to do this manually because the Interrupt attributes are
7585 // a bit special due to sharing their spellings across targets.
7586 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
7587 return;
7588
7589 MipsInterruptAttr::InterruptType Kind;
7590 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7591 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
7592 << AL << "'" + std::string(Str) + "'";
7593 return;
7594 }
7595
7596 D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
7597}
7598
7599static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7600 if (!AL.checkExactlyNumArgs(S, Num: 1))
7601 return;
7602
7603 if (!AL.isArgExpr(Arg: 0)) {
7604 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7605 << AL << AANT_ArgumentIntegerConstant;
7606 return;
7607 }
7608
7609 // FIXME: Check for decl - it should be void ()(void).
7610
7611 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(Arg: 0));
7612 auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(Ctx: S.Context);
7613 if (!MaybeNumParams) {
7614 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
7615 << AL << AANT_ArgumentIntegerConstant
7616 << NumParamsExpr->getSourceRange();
7617 return;
7618 }
7619
7620 unsigned Num = MaybeNumParams->getLimitedValue(Limit: 255);
7621 if ((Num & 1) || Num > 30) {
7622 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
7623 << AL << (int)MaybeNumParams->getSExtValue()
7624 << NumParamsExpr->getSourceRange();
7625 return;
7626 }
7627
7628 D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num));
7629 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7630}
7631
7632static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7633 // Semantic checks for a function with the 'interrupt' attribute.
7634 // a) Must be a function.
7635 // b) Must have the 'void' return type.
7636 // c) Must take 1 or 2 arguments.
7637 // d) The 1st argument must be a pointer.
7638 // e) The 2nd argument (if any) must be an unsigned integer.
7639 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
7640 CXXMethodDecl::isStaticOverloadedOperator(
7641 OOK: cast<NamedDecl>(Val: D)->getDeclName().getCXXOverloadedOperator())) {
7642 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
7643 << AL << AL.isRegularKeywordAttribute()
7644 << ExpectedFunctionWithProtoType;
7645 return;
7646 }
7647 // Interrupt handler must have void return type.
7648 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7649 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
7650 diag::err_anyx86_interrupt_attribute)
7651 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7652 ? 0
7653 : 1)
7654 << 0;
7655 return;
7656 }
7657 // Interrupt handler must have 1 or 2 parameters.
7658 unsigned NumParams = getFunctionOrMethodNumParams(D);
7659 if (NumParams < 1 || NumParams > 2) {
7660 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
7661 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7662 ? 0
7663 : 1)
7664 << 1;
7665 return;
7666 }
7667 // The first argument must be a pointer.
7668 if (!getFunctionOrMethodParamType(D, Idx: 0)->isPointerType()) {
7669 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
7670 diag::err_anyx86_interrupt_attribute)
7671 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7672 ? 0
7673 : 1)
7674 << 2;
7675 return;
7676 }
7677 // The second argument, if present, must be an unsigned integer.
7678 unsigned TypeSize =
7679 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
7680 ? 64
7681 : 32;
7682 if (NumParams == 2 &&
7683 (!getFunctionOrMethodParamType(D, Idx: 1)->isUnsignedIntegerType() ||
7684 S.Context.getTypeSize(T: getFunctionOrMethodParamType(D, Idx: 1)) != TypeSize)) {
7685 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
7686 diag::err_anyx86_interrupt_attribute)
7687 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
7688 ? 0
7689 : 1)
7690 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
7691 return;
7692 }
7693 D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
7694 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7695}
7696
7697static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7698 if (!isFunctionOrMethod(D)) {
7699 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7700 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7701 return;
7702 }
7703
7704 if (!AL.checkExactlyNumArgs(S, Num: 0))
7705 return;
7706
7707 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
7708}
7709
7710static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7711 if (!isFunctionOrMethod(D)) {
7712 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7713 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7714 return;
7715 }
7716
7717 if (!AL.checkExactlyNumArgs(S, Num: 0))
7718 return;
7719
7720 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
7721}
7722
7723static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
7724 // Add preserve_access_index attribute to all fields and inner records.
7725 for (auto *D : RD->decls()) {
7726 if (D->hasAttr<BPFPreserveAccessIndexAttr>())
7727 continue;
7728
7729 D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
7730 if (auto *Rec = dyn_cast<RecordDecl>(D))
7731 handleBPFPreserveAIRecord(S, Rec);
7732 }
7733}
7734
7735static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
7736 const ParsedAttr &AL) {
7737 auto *Rec = cast<RecordDecl>(Val: D);
7738 handleBPFPreserveAIRecord(S, RD: Rec);
7739 Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
7740}
7741
7742static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) {
7743 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
7744 if (I->getBTFDeclTag() == Tag)
7745 return true;
7746 }
7747 return false;
7748}
7749
7750static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7751 StringRef Str;
7752 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
7753 return;
7754 if (hasBTFDeclTagAttr(D, Tag: Str))
7755 return;
7756
7757 D->addAttr(::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str));
7758}
7759
7760BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) {
7761 if (hasBTFDeclTagAttr(D, AL.getBTFDeclTag()))
7762 return nullptr;
7763 return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag());
7764}
7765
7766static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D,
7767 const ParsedAttr &AL) {
7768 if (!isFunctionOrMethod(D)) {
7769 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7770 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7771 return;
7772 }
7773
7774 auto *FD = cast<FunctionDecl>(Val: D);
7775 if (FD->isThisDeclarationADefinition()) {
7776 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
7777 return;
7778 }
7779
7780 StringRef Str;
7781 SourceLocation ArgLoc;
7782 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
7783 return;
7784
7785 D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
7786 D->addAttr(UsedAttr::CreateImplicit(S.Context));
7787}
7788
7789WebAssemblyImportModuleAttr *
7790Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
7791 auto *FD = cast<FunctionDecl>(Val: D);
7792
7793 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
7794 if (ExistingAttr->getImportModule() == AL.getImportModule())
7795 return nullptr;
7796 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
7797 << ExistingAttr->getImportModule() << AL.getImportModule();
7798 Diag(AL.getLoc(), diag::note_previous_attribute);
7799 return nullptr;
7800 }
7801 if (FD->hasBody()) {
7802 Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
7803 return nullptr;
7804 }
7805 return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
7806 AL.getImportModule());
7807}
7808
7809WebAssemblyImportNameAttr *
7810Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
7811 auto *FD = cast<FunctionDecl>(Val: D);
7812
7813 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
7814 if (ExistingAttr->getImportName() == AL.getImportName())
7815 return nullptr;
7816 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
7817 << ExistingAttr->getImportName() << AL.getImportName();
7818 Diag(AL.getLoc(), diag::note_previous_attribute);
7819 return nullptr;
7820 }
7821 if (FD->hasBody()) {
7822 Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
7823 return nullptr;
7824 }
7825 return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
7826 AL.getImportName());
7827}
7828
7829static void
7830handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7831 auto *FD = cast<FunctionDecl>(Val: D);
7832
7833 StringRef Str;
7834 SourceLocation ArgLoc;
7835 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
7836 return;
7837 if (FD->hasBody()) {
7838 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
7839 return;
7840 }
7841
7842 FD->addAttr(::new (S.Context)
7843 WebAssemblyImportModuleAttr(S.Context, AL, Str));
7844}
7845
7846static void
7847handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7848 auto *FD = cast<FunctionDecl>(Val: D);
7849
7850 StringRef Str;
7851 SourceLocation ArgLoc;
7852 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
7853 return;
7854 if (FD->hasBody()) {
7855 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
7856 return;
7857 }
7858
7859 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
7860}
7861
7862static void handleRISCVInterruptAttr(Sema &S, Decl *D,
7863 const ParsedAttr &AL) {
7864 // Warn about repeated attributes.
7865 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
7866 S.Diag(AL.getRange().getBegin(),
7867 diag::warn_riscv_repeated_interrupt_attribute);
7868 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
7869 return;
7870 }
7871
7872 // Check the attribute argument. Argument is optional.
7873 if (!AL.checkAtMostNumArgs(S, Num: 1))
7874 return;
7875
7876 StringRef Str;
7877 SourceLocation ArgLoc;
7878
7879 // 'machine'is the default interrupt mode.
7880 if (AL.getNumArgs() == 0)
7881 Str = "machine";
7882 else if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &ArgLoc))
7883 return;
7884
7885 // Semantic checks for a function with the 'interrupt' attribute:
7886 // - Must be a function.
7887 // - Must have no parameters.
7888 // - Must have the 'void' return type.
7889 // - The attribute itself must either have no argument or one of the
7890 // valid interrupt types, see [RISCVInterruptDocs].
7891
7892 if (D->getFunctionType() == nullptr) {
7893 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
7894 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
7895 return;
7896 }
7897
7898 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
7899 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7900 << /*RISC-V*/ 2 << 0;
7901 return;
7902 }
7903
7904 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
7905 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
7906 << /*RISC-V*/ 2 << 1;
7907 return;
7908 }
7909
7910 RISCVInterruptAttr::InterruptType Kind;
7911 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
7912 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
7913 << ArgLoc;
7914 return;
7915 }
7916
7917 D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
7918}
7919
7920static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7921 // Dispatch the interrupt attribute based on the current target.
7922 switch (S.Context.getTargetInfo().getTriple().getArch()) {
7923 case llvm::Triple::msp430:
7924 handleMSP430InterruptAttr(S, D, AL);
7925 break;
7926 case llvm::Triple::mipsel:
7927 case llvm::Triple::mips:
7928 handleMipsInterruptAttr(S, D, AL);
7929 break;
7930 case llvm::Triple::m68k:
7931 handleM68kInterruptAttr(S, D, AL);
7932 break;
7933 case llvm::Triple::x86:
7934 case llvm::Triple::x86_64:
7935 handleAnyX86InterruptAttr(S, D, AL);
7936 break;
7937 case llvm::Triple::avr:
7938 handleAVRInterruptAttr(S, D, AL);
7939 break;
7940 case llvm::Triple::riscv32:
7941 case llvm::Triple::riscv64:
7942 handleRISCVInterruptAttr(S, D, AL);
7943 break;
7944 default:
7945 handleARMInterruptAttr(S, D, AL);
7946 break;
7947 }
7948}
7949
7950static bool
7951checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
7952 const AMDGPUFlatWorkGroupSizeAttr &Attr) {
7953 // Accept template arguments for now as they depend on something else.
7954 // We'll get to check them when they eventually get instantiated.
7955 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
7956 return false;
7957
7958 uint32_t Min = 0;
7959 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
7960 return true;
7961
7962 uint32_t Max = 0;
7963 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
7964 return true;
7965
7966 if (Min == 0 && Max != 0) {
7967 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7968 << &Attr << 0;
7969 return true;
7970 }
7971 if (Min > Max) {
7972 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
7973 << &Attr << 1;
7974 return true;
7975 }
7976
7977 return false;
7978}
7979
7980AMDGPUFlatWorkGroupSizeAttr *
7981Sema::CreateAMDGPUFlatWorkGroupSizeAttr(const AttributeCommonInfo &CI,
7982 Expr *MinExpr, Expr *MaxExpr) {
7983 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
7984
7985 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
7986 return nullptr;
7987 return ::new (Context)
7988 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr);
7989}
7990
7991void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
7992 const AttributeCommonInfo &CI,
7993 Expr *MinExpr, Expr *MaxExpr) {
7994 if (auto *Attr = CreateAMDGPUFlatWorkGroupSizeAttr(CI, MinExpr, MaxExpr))
7995 D->addAttr(A: Attr);
7996}
7997
7998static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
7999 const ParsedAttr &AL) {
8000 Expr *MinExpr = AL.getArgAsExpr(Arg: 0);
8001 Expr *MaxExpr = AL.getArgAsExpr(Arg: 1);
8002
8003 S.addAMDGPUFlatWorkGroupSizeAttr(D, CI: AL, MinExpr, MaxExpr);
8004}
8005
8006static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
8007 Expr *MaxExpr,
8008 const AMDGPUWavesPerEUAttr &Attr) {
8009 if (S.DiagnoseUnexpandedParameterPack(E: MinExpr) ||
8010 (MaxExpr && S.DiagnoseUnexpandedParameterPack(E: MaxExpr)))
8011 return true;
8012
8013 // Accept template arguments for now as they depend on something else.
8014 // We'll get to check them when they eventually get instantiated.
8015 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
8016 return false;
8017
8018 uint32_t Min = 0;
8019 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
8020 return true;
8021
8022 uint32_t Max = 0;
8023 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
8024 return true;
8025
8026 if (Min == 0 && Max != 0) {
8027 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
8028 << &Attr << 0;
8029 return true;
8030 }
8031 if (Max != 0 && Min > Max) {
8032 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
8033 << &Attr << 1;
8034 return true;
8035 }
8036
8037 return false;
8038}
8039
8040AMDGPUWavesPerEUAttr *
8041Sema::CreateAMDGPUWavesPerEUAttr(const AttributeCommonInfo &CI, Expr *MinExpr,
8042 Expr *MaxExpr) {
8043 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
8044
8045 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
8046 return nullptr;
8047
8048 return ::new (Context) AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr);
8049}
8050
8051void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
8052 Expr *MinExpr, Expr *MaxExpr) {
8053 if (auto *Attr = CreateAMDGPUWavesPerEUAttr(CI, MinExpr, MaxExpr))
8054 D->addAttr(A: Attr);
8055}
8056
8057static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8058 if (!AL.checkAtLeastNumArgs(S, Num: 1) || !AL.checkAtMostNumArgs(S, Num: 2))
8059 return;
8060
8061 Expr *MinExpr = AL.getArgAsExpr(Arg: 0);
8062 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(Arg: 1) : nullptr;
8063
8064 S.addAMDGPUWavesPerEUAttr(D, CI: AL, MinExpr, MaxExpr);
8065}
8066
8067static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8068 uint32_t NumSGPR = 0;
8069 Expr *NumSGPRExpr = AL.getArgAsExpr(Arg: 0);
8070 if (!checkUInt32Argument(S, AI: AL, Expr: NumSGPRExpr, Val&: NumSGPR))
8071 return;
8072
8073 D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
8074}
8075
8076static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8077 uint32_t NumVGPR = 0;
8078 Expr *NumVGPRExpr = AL.getArgAsExpr(Arg: 0);
8079 if (!checkUInt32Argument(S, AI: AL, Expr: NumVGPRExpr, Val&: NumVGPR))
8080 return;
8081
8082 D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
8083}
8084
8085static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
8086 const ParsedAttr &AL) {
8087 // If we try to apply it to a function pointer, don't warn, but don't
8088 // do anything, either. It doesn't matter anyway, because there's nothing
8089 // special about calling a force_align_arg_pointer function.
8090 const auto *VD = dyn_cast<ValueDecl>(Val: D);
8091 if (VD && VD->getType()->isFunctionPointerType())
8092 return;
8093 // Also don't warn on function pointer typedefs.
8094 const auto *TD = dyn_cast<TypedefNameDecl>(Val: D);
8095 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
8096 TD->getUnderlyingType()->isFunctionType()))
8097 return;
8098 // Attribute can only be applied to function types.
8099 if (!isa<FunctionDecl>(Val: D)) {
8100 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
8101 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
8102 return;
8103 }
8104
8105 D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
8106}
8107
8108static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
8109 uint32_t Version;
8110 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(Arg: 0));
8111 if (!checkUInt32Argument(S, AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Version))
8112 return;
8113
8114 // TODO: Investigate what happens with the next major version of MSVC.
8115 if (Version != LangOptions::MSVC2015 / 100) {
8116 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
8117 << AL << Version << VersionExpr->getSourceRange();
8118 return;
8119 }
8120
8121 // The attribute expects a "major" version number like 19, but new versions of
8122 // MSVC have moved to updating the "minor", or less significant numbers, so we
8123 // have to multiply by 100 now.
8124 Version *= 100;
8125
8126 D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
8127}
8128
8129DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
8130 const AttributeCommonInfo &CI) {
8131 if (D->hasAttr<DLLExportAttr>()) {
8132 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
8133 return nullptr;
8134 }
8135
8136 if (D->hasAttr<DLLImportAttr>())
8137 return nullptr;
8138
8139 return ::new (Context) DLLImportAttr(Context, CI);
8140}
8141
8142DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
8143 const AttributeCommonInfo &CI) {
8144 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
8145 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
8146 D->dropAttr<DLLImportAttr>();
8147 }
8148
8149 if (D->hasAttr<DLLExportAttr>())
8150 return nullptr;
8151
8152 return ::new (Context) DLLExportAttr(Context, CI);
8153}
8154
8155static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8156 if (isa<ClassTemplatePartialSpecializationDecl>(Val: D) &&
8157 (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
8158 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
8159 return;
8160 }
8161
8162 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
8163 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
8164 !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
8165 // MinGW doesn't allow dllimport on inline functions.
8166 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
8167 << A;
8168 return;
8169 }
8170 }
8171
8172 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
8173 if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
8174 MD->getParent()->isLambda()) {
8175 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
8176 return;
8177 }
8178 }
8179
8180 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
8181 ? (Attr *)S.mergeDLLExportAttr(D, A)
8182 : (Attr *)S.mergeDLLImportAttr(D, A);
8183 if (NewAttr)
8184 D->addAttr(A: NewAttr);
8185}
8186
8187MSInheritanceAttr *
8188Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
8189 bool BestCase,
8190 MSInheritanceModel Model) {
8191 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
8192 if (IA->getInheritanceModel() == Model)
8193 return nullptr;
8194 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
8195 << 1 /*previous declaration*/;
8196 Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
8197 D->dropAttr<MSInheritanceAttr>();
8198 }
8199
8200 auto *RD = cast<CXXRecordDecl>(Val: D);
8201 if (RD->hasDefinition()) {
8202 if (checkMSInheritanceAttrOnDefinition(RD, Range: CI.getRange(), BestCase,
8203 ExplicitModel: Model)) {
8204 return nullptr;
8205 }
8206 } else {
8207 if (isa<ClassTemplatePartialSpecializationDecl>(Val: RD)) {
8208 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
8209 << 1 /*partial specialization*/;
8210 return nullptr;
8211 }
8212 if (RD->getDescribedClassTemplate()) {
8213 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
8214 << 0 /*primary template*/;
8215 return nullptr;
8216 }
8217 }
8218
8219 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
8220}
8221
8222static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8223 // The capability attributes take a single string parameter for the name of
8224 // the capability they represent. The lockable attribute does not take any
8225 // parameters. However, semantically, both attributes represent the same
8226 // concept, and so they use the same semantic attribute. Eventually, the
8227 // lockable attribute will be removed.
8228 //
8229 // For backward compatibility, any capability which has no specified string
8230 // literal will be considered a "mutex."
8231 StringRef N("mutex");
8232 SourceLocation LiteralLoc;
8233 if (AL.getKind() == ParsedAttr::AT_Capability &&
8234 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
8235 return;
8236
8237 D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
8238}
8239
8240static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8241 SmallVector<Expr*, 1> Args;
8242 if (!checkLockFunAttrCommon(S, D, AL, Args))
8243 return;
8244
8245 D->addAttr(::new (S.Context)
8246 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
8247}
8248
8249static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
8250 const ParsedAttr &AL) {
8251 SmallVector<Expr*, 1> Args;
8252 if (!checkLockFunAttrCommon(S, D, AL, Args))
8253 return;
8254
8255 D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
8256 Args.size()));
8257}
8258
8259static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
8260 const ParsedAttr &AL) {
8261 SmallVector<Expr*, 2> Args;
8262 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
8263 return;
8264
8265 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
8266 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
8267}
8268
8269static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
8270 const ParsedAttr &AL) {
8271 // Check that all arguments are lockable objects.
8272 SmallVector<Expr *, 1> Args;
8273 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, Sidx: 0, ParamIdxOk: true);
8274
8275 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
8276 Args.size()));
8277}
8278
8279static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
8280 const ParsedAttr &AL) {
8281 if (!AL.checkAtLeastNumArgs(S, Num: 1))
8282 return;
8283
8284 // check that all arguments are lockable objects
8285 SmallVector<Expr*, 1> Args;
8286 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
8287 if (Args.empty())
8288 return;
8289
8290 RequiresCapabilityAttr *RCA = ::new (S.Context)
8291 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
8292
8293 D->addAttr(A: RCA);
8294}
8295
8296static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8297 if (const auto *NSD = dyn_cast<NamespaceDecl>(Val: D)) {
8298 if (NSD->isAnonymousNamespace()) {
8299 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
8300 // Do not want to attach the attribute to the namespace because that will
8301 // cause confusing diagnostic reports for uses of declarations within the
8302 // namespace.
8303 return;
8304 }
8305 } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl,
8306 UnresolvedUsingValueDecl>(Val: D)) {
8307 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
8308 << AL;
8309 return;
8310 }
8311
8312 // Handle the cases where the attribute has a text message.
8313 StringRef Str, Replacement;
8314 if (AL.isArgExpr(Arg: 0) && AL.getArgAsExpr(Arg: 0) &&
8315 !S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
8316 return;
8317
8318 // Support a single optional message only for Declspec and [[]] spellings.
8319 if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
8320 AL.checkAtMostNumArgs(S, Num: 1);
8321 else if (AL.isArgExpr(Arg: 1) && AL.getArgAsExpr(Arg: 1) &&
8322 !S.checkStringLiteralArgumentAttr(AL, ArgNum: 1, Str&: Replacement))
8323 return;
8324
8325 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
8326 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
8327
8328 D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
8329}
8330
8331static bool isGlobalVar(const Decl *D) {
8332 if (const auto *S = dyn_cast<VarDecl>(Val: D))
8333 return S->hasGlobalStorage();
8334 return false;
8335}
8336
8337static bool isSanitizerAttributeAllowedOnGlobals(StringRef Sanitizer) {
8338 return Sanitizer == "address" || Sanitizer == "hwaddress" ||
8339 Sanitizer == "memtag";
8340}
8341
8342static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8343 if (!AL.checkAtLeastNumArgs(S, Num: 1))
8344 return;
8345
8346 std::vector<StringRef> Sanitizers;
8347
8348 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
8349 StringRef SanitizerName;
8350 SourceLocation LiteralLoc;
8351
8352 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: SanitizerName, ArgLocation: &LiteralLoc))
8353 return;
8354
8355 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
8356 SanitizerMask() &&
8357 SanitizerName != "coverage")
8358 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
8359 else if (isGlobalVar(D) && !isSanitizerAttributeAllowedOnGlobals(SanitizerName))
8360 S.Diag(D->getLocation(), diag::warn_attribute_type_not_supported_global)
8361 << AL << SanitizerName;
8362 Sanitizers.push_back(x: SanitizerName);
8363 }
8364
8365 D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
8366 Sanitizers.size()));
8367}
8368
8369static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
8370 const ParsedAttr &AL) {
8371 StringRef AttrName = AL.getAttrName()->getName();
8372 normalizeName(AttrName);
8373 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
8374 .Case(S: "no_address_safety_analysis", Value: "address")
8375 .Case(S: "no_sanitize_address", Value: "address")
8376 .Case(S: "no_sanitize_thread", Value: "thread")
8377 .Case(S: "no_sanitize_memory", Value: "memory");
8378 if (isGlobalVar(D) && SanitizerName != "address")
8379 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
8380 << AL << AL.isRegularKeywordAttribute() << ExpectedFunction;
8381
8382 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
8383 // NoSanitizeAttr object; but we need to calculate the correct spelling list
8384 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
8385 // has the same spellings as the index for NoSanitizeAttr. We don't have a
8386 // general way to "translate" between the two, so this hack attempts to work
8387 // around the issue with hard-coded indices. This is critical for calling
8388 // getSpelling() or prettyPrint() on the resulting semantic attribute object
8389 // without failing assertions.
8390 unsigned TranslatedSpellingIndex = 0;
8391 if (AL.isStandardAttributeSyntax())
8392 TranslatedSpellingIndex = 1;
8393
8394 AttributeCommonInfo Info = AL;
8395 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
8396 D->addAttr(::new (S.Context)
8397 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
8398}
8399
8400static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8401 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
8402 D->addAttr(Internal);
8403}
8404
8405static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8406 if (S.LangOpts.getOpenCLCompatibleVersion() < 200)
8407 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
8408 << AL << "2.0" << 1;
8409 else
8410 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
8411 << AL << S.LangOpts.getOpenCLVersionString();
8412}
8413
8414static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8415 if (D->isInvalidDecl())
8416 return;
8417
8418 // Check if there is only one access qualifier.
8419 if (D->hasAttr<OpenCLAccessAttr>()) {
8420 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
8421 AL.getSemanticSpelling()) {
8422 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
8423 << AL.getAttrName()->getName() << AL.getRange();
8424 } else {
8425 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
8426 << D->getSourceRange();
8427 D->setInvalidDecl(true);
8428 return;
8429 }
8430 }
8431
8432 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
8433 // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
8434 // cannot read from and write to the same pipe object. Using the read_write
8435 // (or __read_write) qualifier with the pipe qualifier is a compilation error.
8436 // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
8437 // __opencl_c_read_write_images feature, image objects specified as arguments
8438 // to a kernel can additionally be declared to be read-write.
8439 // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0.
8440 // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
8441 if (const auto *PDecl = dyn_cast<ParmVarDecl>(Val: D)) {
8442 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
8443 if (AL.getAttrName()->getName().contains(Other: "read_write")) {
8444 bool ReadWriteImagesUnsupported =
8445 (S.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
8446 (S.getLangOpts().getOpenCLCompatibleVersion() == 300 &&
8447 !S.getOpenCLOptions().isSupported(Ext: "__opencl_c_read_write_images",
8448 LO: S.getLangOpts()));
8449 if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) {
8450 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
8451 << AL << PDecl->getType() << DeclTy->isImageType();
8452 D->setInvalidDecl(true);
8453 return;
8454 }
8455 }
8456 }
8457
8458 D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
8459}
8460
8461static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8462 // Check that the argument is a string literal.
8463 StringRef KindStr;
8464 SourceLocation LiteralLoc;
8465 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: KindStr, ArgLocation: &LiteralLoc))
8466 return;
8467
8468 ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind;
8469 if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(KindStr, Kind)) {
8470 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
8471 << AL << KindStr;
8472 return;
8473 }
8474
8475 D->dropAttr<ZeroCallUsedRegsAttr>();
8476 D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL));
8477}
8478
8479static void handleCountedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8480 if (!AL.isArgIdent(Arg: 0)) {
8481 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
8482 << AL << AANT_ArgumentIdentifier;
8483 return;
8484 }
8485
8486 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
8487 CountedByAttr *CBA =
8488 ::new (S.Context) CountedByAttr(S.Context, AL, IL->Ident);
8489 CBA->setCountedByFieldLoc(IL->Loc);
8490 D->addAttr(A: CBA);
8491}
8492
8493static const FieldDecl *
8494FindFieldInTopLevelOrAnonymousStruct(const RecordDecl *RD,
8495 const IdentifierInfo *FieldName) {
8496 for (const Decl *D : RD->decls()) {
8497 if (const auto *FD = dyn_cast<FieldDecl>(D))
8498 if (FD->getName() == FieldName->getName())
8499 return FD;
8500
8501 if (const auto *R = dyn_cast<RecordDecl>(D))
8502 if (const FieldDecl *FD =
8503 FindFieldInTopLevelOrAnonymousStruct(R, FieldName))
8504 return FD;
8505 }
8506
8507 return nullptr;
8508}
8509
8510bool Sema::CheckCountedByAttr(Scope *S, const FieldDecl *FD) {
8511 LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
8512 LangOptions::StrictFlexArraysLevelKind::IncompleteOnly;
8513 if (!Decl::isFlexibleArrayMemberLike(Context, D: FD, Ty: FD->getType(),
8514 StrictFlexArraysLevel, IgnoreTemplateOrMacroSubstitution: true)) {
8515 // The "counted_by" attribute must be on a flexible array member.
8516 SourceRange SR = FD->getLocation();
8517 Diag(SR.getBegin(), diag::err_counted_by_attr_not_on_flexible_array_member)
8518 << SR;
8519 return true;
8520 }
8521
8522 const auto *CBA = FD->getAttr<CountedByAttr>();
8523 const IdentifierInfo *FieldName = CBA->getCountedByField();
8524
8525 auto GetNonAnonStructOrUnion = [](const RecordDecl *RD) {
8526 while (RD && !RD->getDeclName())
8527 if (const auto *R = dyn_cast<RecordDecl>(RD->getDeclContext()))
8528 RD = R;
8529 else
8530 break;
8531
8532 return RD;
8533 };
8534
8535 const RecordDecl *EnclosingRD = GetNonAnonStructOrUnion(FD->getParent());
8536 const FieldDecl *CountFD =
8537 FindFieldInTopLevelOrAnonymousStruct(RD: EnclosingRD, FieldName);
8538
8539 if (!CountFD) {
8540 DeclarationNameInfo NameInfo(FieldName,
8541 CBA->getCountedByFieldLoc().getBegin());
8542 LookupResult MemResult(*this, NameInfo, Sema::LookupMemberName);
8543 LookupName(R&: MemResult, S);
8544
8545 if (!MemResult.empty()) {
8546 SourceRange SR = CBA->getCountedByFieldLoc();
8547 Diag(SR.getBegin(), diag::err_flexible_array_count_not_in_same_struct)
8548 << CBA->getCountedByField() << SR;
8549
8550 if (auto *ND = MemResult.getAsSingle<NamedDecl>()) {
8551 SR = ND->getLocation();
8552 Diag(SR.getBegin(), diag::note_flexible_array_counted_by_attr_field)
8553 << ND << SR;
8554 }
8555
8556 return true;
8557 } else {
8558 // The "counted_by" field needs to exist in the struct.
8559 LookupResult OrdResult(*this, NameInfo, Sema::LookupOrdinaryName);
8560 LookupName(R&: OrdResult, S);
8561
8562 if (!OrdResult.empty()) {
8563 SourceRange SR = FD->getLocation();
8564 Diag(SR.getBegin(), diag::err_counted_by_must_be_in_structure)
8565 << FieldName << SR;
8566
8567 if (auto *ND = OrdResult.getAsSingle<NamedDecl>()) {
8568 SR = ND->getLocation();
8569 Diag(SR.getBegin(), diag::note_flexible_array_counted_by_attr_field)
8570 << ND << SR;
8571 }
8572
8573 return true;
8574 }
8575 }
8576
8577 CXXScopeSpec SS;
8578 DeclFilterCCC<FieldDecl> Filter(FieldName);
8579 return DiagnoseEmptyLookup(S, SS, R&: MemResult, CCC&: Filter, ExplicitTemplateArgs: nullptr, Args: std::nullopt,
8580 LookupCtx: const_cast<DeclContext *>(FD->getDeclContext()));
8581 }
8582
8583 if (CountFD->hasAttr<CountedByAttr>()) {
8584 // The "counted_by" field can't point to the flexible array member.
8585 SourceRange SR = CBA->getCountedByFieldLoc();
8586 Diag(SR.getBegin(), diag::err_counted_by_attr_refers_to_flexible_array)
8587 << CBA->getCountedByField() << SR;
8588 return true;
8589 }
8590
8591 if (!CountFD->getType()->isIntegerType() ||
8592 CountFD->getType()->isBooleanType()) {
8593 // The "counted_by" field must have an integer type.
8594 SourceRange SR = CBA->getCountedByFieldLoc();
8595 Diag(SR.getBegin(),
8596 diag::err_flexible_array_counted_by_attr_field_not_integer)
8597 << CBA->getCountedByField() << SR;
8598
8599 SR = CountFD->getLocation();
8600 Diag(SR.getBegin(), diag::note_flexible_array_counted_by_attr_field)
8601 << CountFD << SR;
8602 return true;
8603 }
8604
8605 return false;
8606}
8607
8608static void handleFunctionReturnThunksAttr(Sema &S, Decl *D,
8609 const ParsedAttr &AL) {
8610 StringRef KindStr;
8611 SourceLocation LiteralLoc;
8612 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: KindStr, ArgLocation: &LiteralLoc))
8613 return;
8614
8615 FunctionReturnThunksAttr::Kind Kind;
8616 if (!FunctionReturnThunksAttr::ConvertStrToKind(KindStr, Kind)) {
8617 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
8618 << AL << KindStr;
8619 return;
8620 }
8621 // FIXME: it would be good to better handle attribute merging rather than
8622 // silently replacing the existing attribute, so long as it does not break
8623 // the expected codegen tests.
8624 D->dropAttr<FunctionReturnThunksAttr>();
8625 D->addAttr(FunctionReturnThunksAttr::Create(S.Context, Kind, AL));
8626}
8627
8628static void handleAvailableOnlyInDefaultEvalMethod(Sema &S, Decl *D,
8629 const ParsedAttr &AL) {
8630 assert(isa<TypedefNameDecl>(D) && "This attribute only applies to a typedef");
8631 handleSimpleAttribute<AvailableOnlyInDefaultEvalMethodAttr>(S, D, AL);
8632}
8633
8634static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8635 auto *VDecl = dyn_cast<VarDecl>(Val: D);
8636 if (VDecl && !VDecl->isFunctionPointerType()) {
8637 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_non_function_pointer)
8638 << AL << VDecl;
8639 return;
8640 }
8641 D->addAttr(NoMergeAttr::Create(S.Context, AL));
8642}
8643
8644static void handleNoUniqueAddressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8645 D->addAttr(NoUniqueAddressAttr::Create(S.Context, AL));
8646}
8647
8648static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8649 // The 'sycl_kernel' attribute applies only to function templates.
8650 const auto *FD = cast<FunctionDecl>(Val: D);
8651 const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
8652 assert(FT && "Function template is expected");
8653
8654 // Function template must have at least two template parameters.
8655 const TemplateParameterList *TL = FT->getTemplateParameters();
8656 if (TL->size() < 2) {
8657 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
8658 return;
8659 }
8660
8661 // Template parameters must be typenames.
8662 for (unsigned I = 0; I < 2; ++I) {
8663 const NamedDecl *TParam = TL->getParam(Idx: I);
8664 if (isa<NonTypeTemplateParmDecl>(Val: TParam)) {
8665 S.Diag(FT->getLocation(),
8666 diag::warn_sycl_kernel_invalid_template_param_type);
8667 return;
8668 }
8669 }
8670
8671 // Function must have at least one argument.
8672 if (getFunctionOrMethodNumParams(D) != 1) {
8673 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
8674 return;
8675 }
8676
8677 // Function must return void.
8678 QualType RetTy = getFunctionOrMethodResultType(D);
8679 if (!RetTy->isVoidType()) {
8680 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
8681 return;
8682 }
8683
8684 handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
8685}
8686
8687static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8688 if (!cast<VarDecl>(Val: D)->hasGlobalStorage()) {
8689 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
8690 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
8691 return;
8692 }
8693
8694 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
8695 handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A);
8696 else
8697 handleSimpleAttribute<NoDestroyAttr>(S, D, A);
8698}
8699
8700static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8701 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
8702 "uninitialized is only valid on automatic duration variables");
8703 D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
8704}
8705
8706static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
8707 bool DiagnoseFailure) {
8708 QualType Ty = VD->getType();
8709 if (!Ty->isObjCRetainableType()) {
8710 if (DiagnoseFailure) {
8711 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8712 << 0;
8713 }
8714 return false;
8715 }
8716
8717 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
8718
8719 // Sema::inferObjCARCLifetime must run after processing decl attributes
8720 // (because __block lowers to an attribute), so if the lifetime hasn't been
8721 // explicitly specified, infer it locally now.
8722 if (LifetimeQual == Qualifiers::OCL_None)
8723 LifetimeQual = Ty->getObjCARCImplicitLifetime();
8724
8725 // The attributes only really makes sense for __strong variables; ignore any
8726 // attempts to annotate a parameter with any other lifetime qualifier.
8727 if (LifetimeQual != Qualifiers::OCL_Strong) {
8728 if (DiagnoseFailure) {
8729 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8730 << 1;
8731 }
8732 return false;
8733 }
8734
8735 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
8736 // to ensure that the variable is 'const' so that we can error on
8737 // modification, which can otherwise over-release.
8738 VD->setType(Ty.withConst());
8739 VD->setARCPseudoStrong(true);
8740 return true;
8741}
8742
8743static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
8744 const ParsedAttr &AL) {
8745 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
8746 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
8747 if (!VD->hasLocalStorage()) {
8748 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
8749 << 0;
8750 return;
8751 }
8752
8753 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
8754 return;
8755
8756 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
8757 return;
8758 }
8759
8760 // If D is a function-like declaration (method, block, or function), then we
8761 // make every parameter psuedo-strong.
8762 unsigned NumParams =
8763 hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0;
8764 for (unsigned I = 0; I != NumParams; ++I) {
8765 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, Idx: I));
8766 QualType Ty = PVD->getType();
8767
8768 // If a user wrote a parameter with __strong explicitly, then assume they
8769 // want "real" strong semantics for that parameter. This works because if
8770 // the parameter was written with __strong, then the strong qualifier will
8771 // be non-local.
8772 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
8773 Qualifiers::OCL_Strong)
8774 continue;
8775
8776 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
8777 }
8778 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
8779}
8780
8781static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8782 // Check that the return type is a `typedef int kern_return_t` or a typedef
8783 // around it, because otherwise MIG convention checks make no sense.
8784 // BlockDecl doesn't store a return type, so it's annoying to check,
8785 // so let's skip it for now.
8786 if (!isa<BlockDecl>(Val: D)) {
8787 QualType T = getFunctionOrMethodResultType(D);
8788 bool IsKernReturnT = false;
8789 while (const auto *TT = T->getAs<TypedefType>()) {
8790 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
8791 T = TT->desugar();
8792 }
8793 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
8794 S.Diag(D->getBeginLoc(),
8795 diag::warn_mig_server_routine_does_not_return_kern_return_t);
8796 return;
8797 }
8798 }
8799
8800 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
8801}
8802
8803static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8804 // Warn if the return type is not a pointer or reference type.
8805 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
8806 QualType RetTy = FD->getReturnType();
8807 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
8808 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
8809 << AL.getRange() << RetTy;
8810 return;
8811 }
8812 }
8813
8814 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
8815}
8816
8817static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8818 if (AL.isUsedAsTypeAttr())
8819 return;
8820 // Warn if the parameter is definitely not an output parameter.
8821 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: D)) {
8822 if (PVD->getType()->isIntegerType()) {
8823 S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
8824 << AL.getRange();
8825 return;
8826 }
8827 }
8828 StringRef Argument;
8829 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Argument))
8830 return;
8831 D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
8832}
8833
8834template<typename Attr>
8835static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8836 StringRef Argument;
8837 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Argument))
8838 return;
8839 D->addAttr(A: Attr::Create(S.Context, Argument, AL));
8840}
8841
8842template<typename Attr>
8843static void handleUnsafeBufferUsage(Sema &S, Decl *D, const ParsedAttr &AL) {
8844 D->addAttr(A: Attr::Create(S.Context, AL));
8845}
8846
8847static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8848 // The guard attribute takes a single identifier argument.
8849
8850 if (!AL.isArgIdent(Arg: 0)) {
8851 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
8852 << AL << AANT_ArgumentIdentifier;
8853 return;
8854 }
8855
8856 CFGuardAttr::GuardArg Arg;
8857 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->Ident;
8858 if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
8859 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
8860 return;
8861 }
8862
8863 D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
8864}
8865
8866
8867template <typename AttrTy>
8868static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
8869 auto Attrs = D->specific_attrs<AttrTy>();
8870 auto I = llvm::find_if(Attrs,
8871 [Name](const AttrTy *A) {
8872 return A->getTCBName() == Name;
8873 });
8874 return I == Attrs.end() ? nullptr : *I;
8875}
8876
8877template <typename AttrTy, typename ConflictingAttrTy>
8878static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8879 StringRef Argument;
8880 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Argument))
8881 return;
8882
8883 // A function cannot be have both regular and leaf membership in the same TCB.
8884 if (const ConflictingAttrTy *ConflictingAttr =
8885 findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
8886 // We could attach a note to the other attribute but in this case
8887 // there's no need given how the two are very close to each other.
8888 S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
8889 << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
8890 << Argument;
8891
8892 // Error recovery: drop the non-leaf attribute so that to suppress
8893 // all future warnings caused by erroneous attributes. The leaf attribute
8894 // needs to be kept because it can only suppresses warnings, not cause them.
8895 D->dropAttr<EnforceTCBAttr>();
8896 return;
8897 }
8898
8899 D->addAttr(A: AttrTy::Create(S.Context, Argument, AL));
8900}
8901
8902template <typename AttrTy, typename ConflictingAttrTy>
8903static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
8904 // Check if the new redeclaration has different leaf-ness in the same TCB.
8905 StringRef TCBName = AL.getTCBName();
8906 if (const ConflictingAttrTy *ConflictingAttr =
8907 findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
8908 S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
8909 << ConflictingAttr->getAttrName()->getName()
8910 << AL.getAttrName()->getName() << TCBName;
8911
8912 // Add a note so that the user could easily find the conflicting attribute.
8913 S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
8914
8915 // More error recovery.
8916 D->dropAttr<EnforceTCBAttr>();
8917 return nullptr;
8918 }
8919
8920 ASTContext &Context = S.getASTContext();
8921 return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
8922}
8923
8924EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
8925 return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
8926 *this, D, AL);
8927}
8928
8929EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
8930 Decl *D, const EnforceTCBLeafAttr &AL) {
8931 return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
8932 *this, D, AL);
8933}
8934
8935//===----------------------------------------------------------------------===//
8936// Top Level Sema Entry Points
8937//===----------------------------------------------------------------------===//
8938
8939// Returns true if the attribute must delay setting its arguments until after
8940// template instantiation, and false otherwise.
8941static bool MustDelayAttributeArguments(const ParsedAttr &AL) {
8942 // Only attributes that accept expression parameter packs can delay arguments.
8943 if (!AL.acceptsExprPack())
8944 return false;
8945
8946 bool AttrHasVariadicArg = AL.hasVariadicArg();
8947 unsigned AttrNumArgs = AL.getNumArgMembers();
8948 for (size_t I = 0; I < std::min(a: AL.getNumArgs(), b: AttrNumArgs); ++I) {
8949 bool IsLastAttrArg = I == (AttrNumArgs - 1);
8950 // If the argument is the last argument and it is variadic it can contain
8951 // any expression.
8952 if (IsLastAttrArg && AttrHasVariadicArg)
8953 return false;
8954 Expr *E = AL.getArgAsExpr(Arg: I);
8955 bool ArgMemberCanHoldExpr = AL.isParamExpr(N: I);
8956 // If the expression is a pack expansion then arguments must be delayed
8957 // unless the argument is an expression and it is the last argument of the
8958 // attribute.
8959 if (isa<PackExpansionExpr>(Val: E))
8960 return !(IsLastAttrArg && ArgMemberCanHoldExpr);
8961 // Last case is if the expression is value dependent then it must delay
8962 // arguments unless the corresponding argument is able to hold the
8963 // expression.
8964 if (E->isValueDependent() && !ArgMemberCanHoldExpr)
8965 return true;
8966 }
8967 return false;
8968}
8969
8970static bool checkArmNewAttrMutualExclusion(
8971 Sema &S, const ParsedAttr &AL, const FunctionProtoType *FPT,
8972 FunctionType::ArmStateValue CurrentState, StringRef StateName) {
8973 auto CheckForIncompatibleAttr =
8974 [&](FunctionType::ArmStateValue IncompatibleState,
8975 StringRef IncompatibleStateName) {
8976 if (CurrentState == IncompatibleState) {
8977 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
8978 << (std::string("'__arm_new(\"") + StateName.str() + "\")'")
8979 << (std::string("'") + IncompatibleStateName.str() + "(\"" +
8980 StateName.str() + "\")'")
8981 << true;
8982 AL.setInvalid();
8983 }
8984 };
8985
8986 CheckForIncompatibleAttr(FunctionType::ARM_In, "__arm_in");
8987 CheckForIncompatibleAttr(FunctionType::ARM_Out, "__arm_out");
8988 CheckForIncompatibleAttr(FunctionType::ARM_InOut, "__arm_inout");
8989 CheckForIncompatibleAttr(FunctionType::ARM_Preserves, "__arm_preserves");
8990 return AL.isInvalid();
8991}
8992
8993static void handleArmNewAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8994 if (!AL.getNumArgs()) {
8995 S.Diag(AL.getLoc(), diag::err_missing_arm_state) << AL;
8996 AL.setInvalid();
8997 return;
8998 }
8999
9000 std::vector<StringRef> NewState;
9001 if (const auto *ExistingAttr = D->getAttr<ArmNewAttr>()) {
9002 for (StringRef S : ExistingAttr->newArgs())
9003 NewState.push_back(S);
9004 }
9005
9006 bool HasZA = false;
9007 bool HasZT0 = false;
9008 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
9009 StringRef StateName;
9010 SourceLocation LiteralLoc;
9011 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: StateName, ArgLocation: &LiteralLoc))
9012 return;
9013
9014 if (StateName == "za")
9015 HasZA = true;
9016 else if (StateName == "zt0")
9017 HasZT0 = true;
9018 else {
9019 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
9020 AL.setInvalid();
9021 return;
9022 }
9023
9024 if (!llvm::is_contained(Range&: NewState, Element: StateName)) // Avoid adding duplicates.
9025 NewState.push_back(x: StateName);
9026 }
9027
9028 if (auto *FPT = dyn_cast<FunctionProtoType>(Val: D->getFunctionType())) {
9029 FunctionType::ArmStateValue ZAState =
9030 FunctionType::getArmZAState(AttrBits: FPT->getAArch64SMEAttributes());
9031 if (HasZA && ZAState != FunctionType::ARM_None &&
9032 checkArmNewAttrMutualExclusion(S, AL, FPT, CurrentState: ZAState, StateName: "za"))
9033 return;
9034 FunctionType::ArmStateValue ZT0State =
9035 FunctionType::getArmZT0State(AttrBits: FPT->getAArch64SMEAttributes());
9036 if (HasZT0 && ZT0State != FunctionType::ARM_None &&
9037 checkArmNewAttrMutualExclusion(S, AL, FPT, CurrentState: ZT0State, StateName: "zt0"))
9038 return;
9039 }
9040
9041 D->dropAttr<ArmNewAttr>();
9042 D->addAttr(::new (S.Context)
9043 ArmNewAttr(S.Context, AL, NewState.data(), NewState.size()));
9044}
9045
9046/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
9047/// the attribute applies to decls. If the attribute is a type attribute, just
9048/// silently ignore it if a GNU attribute.
9049static void
9050ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL,
9051 const Sema::ProcessDeclAttributeOptions &Options) {
9052 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
9053 return;
9054
9055 // Ignore C++11 attributes on declarator chunks: they appertain to the type
9056 // instead.
9057 if (AL.isCXX11Attribute() && !Options.IncludeCXX11Attributes)
9058 return;
9059
9060 // Unknown attributes are automatically warned on. Target-specific attributes
9061 // which do not apply to the current target architecture are treated as
9062 // though they were unknown attributes.
9063 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
9064 !AL.existsInTarget(Target: S.Context.getTargetInfo())) {
9065 S.Diag(AL.getLoc(),
9066 AL.isRegularKeywordAttribute()
9067 ? (unsigned)diag::err_keyword_not_supported_on_target
9068 : AL.isDeclspecAttribute()
9069 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
9070 : (unsigned)diag::warn_unknown_attribute_ignored)
9071 << AL << AL.getRange();
9072 return;
9073 }
9074
9075 // Check if argument population must delayed to after template instantiation.
9076 bool MustDelayArgs = MustDelayAttributeArguments(AL);
9077
9078 // Argument number check must be skipped if arguments are delayed.
9079 if (S.checkCommonAttributeFeatures(D, A: AL, SkipArgCountCheck: MustDelayArgs))
9080 return;
9081
9082 if (MustDelayArgs) {
9083 AL.handleAttrWithDelayedArgs(S, D);
9084 return;
9085 }
9086
9087 switch (AL.getKind()) {
9088 default:
9089 if (AL.getInfo().handleDeclAttribute(S, D, Attr: AL) != ParsedAttrInfo::NotHandled)
9090 break;
9091 if (!AL.isStmtAttr()) {
9092 assert(AL.isTypeAttr() && "Non-type attribute not handled");
9093 }
9094 if (AL.isTypeAttr()) {
9095 if (Options.IgnoreTypeAttributes)
9096 break;
9097 if (!AL.isStandardAttributeSyntax() && !AL.isRegularKeywordAttribute()) {
9098 // Non-[[]] type attributes are handled in processTypeAttrs(); silently
9099 // move on.
9100 break;
9101 }
9102
9103 // According to the C and C++ standards, we should never see a
9104 // [[]] type attribute on a declaration. However, we have in the past
9105 // allowed some type attributes to "slide" to the `DeclSpec`, so we need
9106 // to continue to support this legacy behavior. We only do this, however,
9107 // if
9108 // - we actually have a `DeclSpec`, i.e. if we're looking at a
9109 // `DeclaratorDecl`, or
9110 // - we are looking at an alias-declaration, where historically we have
9111 // allowed type attributes after the identifier to slide to the type.
9112 if (AL.slidesFromDeclToDeclSpecLegacyBehavior() &&
9113 isa<DeclaratorDecl, TypeAliasDecl>(Val: D)) {
9114 // Suggest moving the attribute to the type instead, but only for our
9115 // own vendor attributes; moving other vendors' attributes might hurt
9116 // portability.
9117 if (AL.isClangScope()) {
9118 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
9119 << AL << D->getLocation();
9120 }
9121
9122 // Allow this type attribute to be handled in processTypeAttrs();
9123 // silently move on.
9124 break;
9125 }
9126
9127 if (AL.getKind() == ParsedAttr::AT_Regparm) {
9128 // `regparm` is a special case: It's a type attribute but we still want
9129 // to treat it as if it had been written on the declaration because that
9130 // way we'll be able to handle it directly in `processTypeAttr()`.
9131 // If we treated `regparm` it as if it had been written on the
9132 // `DeclSpec`, the logic in `distributeFunctionTypeAttrFromDeclSepc()`
9133 // would try to move it to the declarator, but that doesn't work: We
9134 // can't remove the attribute from the list of declaration attributes
9135 // because it might be needed by other declarators in the same
9136 // declaration.
9137 break;
9138 }
9139
9140 if (AL.getKind() == ParsedAttr::AT_VectorSize) {
9141 // `vector_size` is a special case: It's a type attribute semantically,
9142 // but GCC expects the [[]] syntax to be written on the declaration (and
9143 // warns that the attribute has no effect if it is placed on the
9144 // decl-specifier-seq).
9145 // Silently move on and allow the attribute to be handled in
9146 // processTypeAttr().
9147 break;
9148 }
9149
9150 if (AL.getKind() == ParsedAttr::AT_NoDeref) {
9151 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9152 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9153 // We allow processTypeAttrs() to emit a warning and silently move on.
9154 break;
9155 }
9156 }
9157 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
9158 // statement attribute is not written on a declaration, but this code is
9159 // needed for type attributes as well as statement attributes in Attr.td
9160 // that do not list any subjects.
9161 S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)
9162 << AL << AL.isRegularKeywordAttribute() << D->getLocation();
9163 break;
9164 case ParsedAttr::AT_Interrupt:
9165 handleInterruptAttr(S, D, AL);
9166 break;
9167 case ParsedAttr::AT_X86ForceAlignArgPointer:
9168 handleX86ForceAlignArgPointerAttr(S, D, AL);
9169 break;
9170 case ParsedAttr::AT_ReadOnlyPlacement:
9171 handleSimpleAttribute<ReadOnlyPlacementAttr>(S, D, AL);
9172 break;
9173 case ParsedAttr::AT_DLLExport:
9174 case ParsedAttr::AT_DLLImport:
9175 handleDLLAttr(S, D, A: AL);
9176 break;
9177 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
9178 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
9179 break;
9180 case ParsedAttr::AT_AMDGPUWavesPerEU:
9181 handleAMDGPUWavesPerEUAttr(S, D, AL);
9182 break;
9183 case ParsedAttr::AT_AMDGPUNumSGPR:
9184 handleAMDGPUNumSGPRAttr(S, D, AL);
9185 break;
9186 case ParsedAttr::AT_AMDGPUNumVGPR:
9187 handleAMDGPUNumVGPRAttr(S, D, AL);
9188 break;
9189 case ParsedAttr::AT_AVRSignal:
9190 handleAVRSignalAttr(S, D, AL);
9191 break;
9192 case ParsedAttr::AT_BPFPreserveAccessIndex:
9193 handleBPFPreserveAccessIndexAttr(S, D, AL);
9194 break;
9195 case ParsedAttr::AT_BPFPreserveStaticOffset:
9196 handleSimpleAttribute<BPFPreserveStaticOffsetAttr>(S, D, AL);
9197 break;
9198 case ParsedAttr::AT_BTFDeclTag:
9199 handleBTFDeclTagAttr(S, D, AL);
9200 break;
9201 case ParsedAttr::AT_WebAssemblyExportName:
9202 handleWebAssemblyExportNameAttr(S, D, AL);
9203 break;
9204 case ParsedAttr::AT_WebAssemblyImportModule:
9205 handleWebAssemblyImportModuleAttr(S, D, AL);
9206 break;
9207 case ParsedAttr::AT_WebAssemblyImportName:
9208 handleWebAssemblyImportNameAttr(S, D, AL);
9209 break;
9210 case ParsedAttr::AT_IBOutlet:
9211 handleIBOutlet(S, D, AL);
9212 break;
9213 case ParsedAttr::AT_IBOutletCollection:
9214 handleIBOutletCollection(S, D, AL);
9215 break;
9216 case ParsedAttr::AT_IFunc:
9217 handleIFuncAttr(S, D, AL);
9218 break;
9219 case ParsedAttr::AT_Alias:
9220 handleAliasAttr(S, D, AL);
9221 break;
9222 case ParsedAttr::AT_Aligned:
9223 handleAlignedAttr(S, D, AL);
9224 break;
9225 case ParsedAttr::AT_AlignValue:
9226 handleAlignValueAttr(S, D, AL);
9227 break;
9228 case ParsedAttr::AT_AllocSize:
9229 handleAllocSizeAttr(S, D, AL);
9230 break;
9231 case ParsedAttr::AT_AlwaysInline:
9232 handleAlwaysInlineAttr(S, D, AL);
9233 break;
9234 case ParsedAttr::AT_AnalyzerNoReturn:
9235 handleAnalyzerNoReturnAttr(S, D, AL);
9236 break;
9237 case ParsedAttr::AT_TLSModel:
9238 handleTLSModelAttr(S, D, AL);
9239 break;
9240 case ParsedAttr::AT_Annotate:
9241 handleAnnotateAttr(S, D, AL);
9242 break;
9243 case ParsedAttr::AT_Availability:
9244 handleAvailabilityAttr(S, D, AL);
9245 break;
9246 case ParsedAttr::AT_CarriesDependency:
9247 handleDependencyAttr(S, Scope: scope, D, AL);
9248 break;
9249 case ParsedAttr::AT_CPUDispatch:
9250 case ParsedAttr::AT_CPUSpecific:
9251 handleCPUSpecificAttr(S, D, AL);
9252 break;
9253 case ParsedAttr::AT_Common:
9254 handleCommonAttr(S, D, AL);
9255 break;
9256 case ParsedAttr::AT_CUDAConstant:
9257 handleConstantAttr(S, D, AL);
9258 break;
9259 case ParsedAttr::AT_PassObjectSize:
9260 handlePassObjectSizeAttr(S, D, AL);
9261 break;
9262 case ParsedAttr::AT_Constructor:
9263 handleConstructorAttr(S, D, AL);
9264 break;
9265 case ParsedAttr::AT_Deprecated:
9266 handleDeprecatedAttr(S, D, AL);
9267 break;
9268 case ParsedAttr::AT_Destructor:
9269 handleDestructorAttr(S, D, AL);
9270 break;
9271 case ParsedAttr::AT_EnableIf:
9272 handleEnableIfAttr(S, D, AL);
9273 break;
9274 case ParsedAttr::AT_Error:
9275 handleErrorAttr(S, D, AL);
9276 break;
9277 case ParsedAttr::AT_DiagnoseIf:
9278 handleDiagnoseIfAttr(S, D, AL);
9279 break;
9280 case ParsedAttr::AT_DiagnoseAsBuiltin:
9281 handleDiagnoseAsBuiltinAttr(S, D, AL);
9282 break;
9283 case ParsedAttr::AT_NoBuiltin:
9284 handleNoBuiltinAttr(S, D, AL);
9285 break;
9286 case ParsedAttr::AT_ExtVectorType:
9287 handleExtVectorTypeAttr(S, D, AL);
9288 break;
9289 case ParsedAttr::AT_ExternalSourceSymbol:
9290 handleExternalSourceSymbolAttr(S, D, AL);
9291 break;
9292 case ParsedAttr::AT_MinSize:
9293 handleMinSizeAttr(S, D, AL);
9294 break;
9295 case ParsedAttr::AT_OptimizeNone:
9296 handleOptimizeNoneAttr(S, D, AL);
9297 break;
9298 case ParsedAttr::AT_EnumExtensibility:
9299 handleEnumExtensibilityAttr(S, D, AL);
9300 break;
9301 case ParsedAttr::AT_SYCLKernel:
9302 handleSYCLKernelAttr(S, D, AL);
9303 break;
9304 case ParsedAttr::AT_SYCLSpecialClass:
9305 handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, AL);
9306 break;
9307 case ParsedAttr::AT_Format:
9308 handleFormatAttr(S, D, AL);
9309 break;
9310 case ParsedAttr::AT_FormatArg:
9311 handleFormatArgAttr(S, D, AL);
9312 break;
9313 case ParsedAttr::AT_Callback:
9314 handleCallbackAttr(S, D, AL);
9315 break;
9316 case ParsedAttr::AT_CalledOnce:
9317 handleCalledOnceAttr(S, D, AL);
9318 break;
9319 case ParsedAttr::AT_NVPTXKernel:
9320 case ParsedAttr::AT_CUDAGlobal:
9321 handleGlobalAttr(S, D, AL);
9322 break;
9323 case ParsedAttr::AT_CUDADevice:
9324 handleDeviceAttr(S, D, AL);
9325 break;
9326 case ParsedAttr::AT_HIPManaged:
9327 handleManagedAttr(S, D, AL);
9328 break;
9329 case ParsedAttr::AT_GNUInline:
9330 handleGNUInlineAttr(S, D, AL);
9331 break;
9332 case ParsedAttr::AT_CUDALaunchBounds:
9333 handleLaunchBoundsAttr(S, D, AL);
9334 break;
9335 case ParsedAttr::AT_Restrict:
9336 handleRestrictAttr(S, D, AL);
9337 break;
9338 case ParsedAttr::AT_Mode:
9339 handleModeAttr(S, D, AL);
9340 break;
9341 case ParsedAttr::AT_NonNull:
9342 if (auto *PVD = dyn_cast<ParmVarDecl>(Val: D))
9343 handleNonNullAttrParameter(S, D: PVD, AL);
9344 else
9345 handleNonNullAttr(S, D, AL);
9346 break;
9347 case ParsedAttr::AT_ReturnsNonNull:
9348 handleReturnsNonNullAttr(S, D, AL);
9349 break;
9350 case ParsedAttr::AT_NoEscape:
9351 handleNoEscapeAttr(S, D, AL);
9352 break;
9353 case ParsedAttr::AT_MaybeUndef:
9354 handleSimpleAttribute<MaybeUndefAttr>(S, D, AL);
9355 break;
9356 case ParsedAttr::AT_AssumeAligned:
9357 handleAssumeAlignedAttr(S, D, AL);
9358 break;
9359 case ParsedAttr::AT_AllocAlign:
9360 handleAllocAlignAttr(S, D, AL);
9361 break;
9362 case ParsedAttr::AT_Ownership:
9363 handleOwnershipAttr(S, D, AL);
9364 break;
9365 case ParsedAttr::AT_Naked:
9366 handleNakedAttr(S, D, AL);
9367 break;
9368 case ParsedAttr::AT_NoReturn:
9369 handleNoReturnAttr(S, D, Attrs: AL);
9370 break;
9371 case ParsedAttr::AT_CXX11NoReturn:
9372 handleStandardNoReturnAttr(S, D, A: AL);
9373 break;
9374 case ParsedAttr::AT_AnyX86NoCfCheck:
9375 handleNoCfCheckAttr(S, D, Attrs: AL);
9376 break;
9377 case ParsedAttr::AT_NoThrow:
9378 if (!AL.isUsedAsTypeAttr())
9379 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
9380 break;
9381 case ParsedAttr::AT_CUDAShared:
9382 handleSharedAttr(S, D, AL);
9383 break;
9384 case ParsedAttr::AT_VecReturn:
9385 handleVecReturnAttr(S, D, AL);
9386 break;
9387 case ParsedAttr::AT_ObjCOwnership:
9388 handleObjCOwnershipAttr(S, D, AL);
9389 break;
9390 case ParsedAttr::AT_ObjCPreciseLifetime:
9391 handleObjCPreciseLifetimeAttr(S, D, AL);
9392 break;
9393 case ParsedAttr::AT_ObjCReturnsInnerPointer:
9394 handleObjCReturnsInnerPointerAttr(S, D, Attrs: AL);
9395 break;
9396 case ParsedAttr::AT_ObjCRequiresSuper:
9397 handleObjCRequiresSuperAttr(S, D, Attrs: AL);
9398 break;
9399 case ParsedAttr::AT_ObjCBridge:
9400 handleObjCBridgeAttr(S, D, AL);
9401 break;
9402 case ParsedAttr::AT_ObjCBridgeMutable:
9403 handleObjCBridgeMutableAttr(S, D, AL);
9404 break;
9405 case ParsedAttr::AT_ObjCBridgeRelated:
9406 handleObjCBridgeRelatedAttr(S, D, AL);
9407 break;
9408 case ParsedAttr::AT_ObjCDesignatedInitializer:
9409 handleObjCDesignatedInitializer(S, D, AL);
9410 break;
9411 case ParsedAttr::AT_ObjCRuntimeName:
9412 handleObjCRuntimeName(S, D, AL);
9413 break;
9414 case ParsedAttr::AT_ObjCBoxable:
9415 handleObjCBoxable(S, D, AL);
9416 break;
9417 case ParsedAttr::AT_NSErrorDomain:
9418 handleNSErrorDomain(S, D, Attr: AL);
9419 break;
9420 case ParsedAttr::AT_CFConsumed:
9421 case ParsedAttr::AT_NSConsumed:
9422 case ParsedAttr::AT_OSConsumed:
9423 S.AddXConsumedAttr(D, CI: AL, K: parsedAttrToRetainOwnershipKind(AL),
9424 /*IsTemplateInstantiation=*/false);
9425 break;
9426 case ParsedAttr::AT_OSReturnsRetainedOnZero:
9427 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
9428 S, D, AL, isValidOSObjectOutParameter(D),
9429 diag::warn_ns_attribute_wrong_parameter_type,
9430 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
9431 break;
9432 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
9433 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
9434 S, D, AL, isValidOSObjectOutParameter(D),
9435 diag::warn_ns_attribute_wrong_parameter_type,
9436 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
9437 break;
9438 case ParsedAttr::AT_NSReturnsAutoreleased:
9439 case ParsedAttr::AT_NSReturnsNotRetained:
9440 case ParsedAttr::AT_NSReturnsRetained:
9441 case ParsedAttr::AT_CFReturnsNotRetained:
9442 case ParsedAttr::AT_CFReturnsRetained:
9443 case ParsedAttr::AT_OSReturnsNotRetained:
9444 case ParsedAttr::AT_OSReturnsRetained:
9445 handleXReturnsXRetainedAttr(S, D, AL);
9446 break;
9447 case ParsedAttr::AT_WorkGroupSizeHint:
9448 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
9449 break;
9450 case ParsedAttr::AT_ReqdWorkGroupSize:
9451 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
9452 break;
9453 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
9454 handleSubGroupSize(S, D, AL);
9455 break;
9456 case ParsedAttr::AT_VecTypeHint:
9457 handleVecTypeHint(S, D, AL);
9458 break;
9459 case ParsedAttr::AT_InitPriority:
9460 handleInitPriorityAttr(S, D, AL);
9461 break;
9462 case ParsedAttr::AT_Packed:
9463 handlePackedAttr(S, D, AL);
9464 break;
9465 case ParsedAttr::AT_PreferredName:
9466 handlePreferredName(S, D, AL);
9467 break;
9468 case ParsedAttr::AT_Section:
9469 handleSectionAttr(S, D, AL);
9470 break;
9471 case ParsedAttr::AT_CodeModel:
9472 handleCodeModelAttr(S, D, AL);
9473 break;
9474 case ParsedAttr::AT_RandomizeLayout:
9475 handleRandomizeLayoutAttr(S, D, AL);
9476 break;
9477 case ParsedAttr::AT_NoRandomizeLayout:
9478 handleNoRandomizeLayoutAttr(S, D, AL);
9479 break;
9480 case ParsedAttr::AT_CodeSeg:
9481 handleCodeSegAttr(S, D, AL);
9482 break;
9483 case ParsedAttr::AT_Target:
9484 handleTargetAttr(S, D, AL);
9485 break;
9486 case ParsedAttr::AT_TargetVersion:
9487 handleTargetVersionAttr(S, D, AL);
9488 break;
9489 case ParsedAttr::AT_TargetClones:
9490 handleTargetClonesAttr(S, D, AL);
9491 break;
9492 case ParsedAttr::AT_MinVectorWidth:
9493 handleMinVectorWidthAttr(S, D, AL);
9494 break;
9495 case ParsedAttr::AT_Unavailable:
9496 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
9497 break;
9498 case ParsedAttr::AT_Assumption:
9499 handleAssumumptionAttr(S, D, AL);
9500 break;
9501 case ParsedAttr::AT_ObjCDirect:
9502 handleObjCDirectAttr(S, D, AL);
9503 break;
9504 case ParsedAttr::AT_ObjCDirectMembers:
9505 handleObjCDirectMembersAttr(S, D, AL);
9506 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
9507 break;
9508 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
9509 handleObjCSuppresProtocolAttr(S, D, AL);
9510 break;
9511 case ParsedAttr::AT_Unused:
9512 handleUnusedAttr(S, D, AL);
9513 break;
9514 case ParsedAttr::AT_Visibility:
9515 handleVisibilityAttr(S, D, AL, isTypeVisibility: false);
9516 break;
9517 case ParsedAttr::AT_TypeVisibility:
9518 handleVisibilityAttr(S, D, AL, isTypeVisibility: true);
9519 break;
9520 case ParsedAttr::AT_WarnUnusedResult:
9521 handleWarnUnusedResult(S, D, AL);
9522 break;
9523 case ParsedAttr::AT_WeakRef:
9524 handleWeakRefAttr(S, D, AL);
9525 break;
9526 case ParsedAttr::AT_WeakImport:
9527 handleWeakImportAttr(S, D, AL);
9528 break;
9529 case ParsedAttr::AT_TransparentUnion:
9530 handleTransparentUnionAttr(S, D, AL);
9531 break;
9532 case ParsedAttr::AT_ObjCMethodFamily:
9533 handleObjCMethodFamilyAttr(S, D, AL);
9534 break;
9535 case ParsedAttr::AT_ObjCNSObject:
9536 handleObjCNSObject(S, D, AL);
9537 break;
9538 case ParsedAttr::AT_ObjCIndependentClass:
9539 handleObjCIndependentClass(S, D, AL);
9540 break;
9541 case ParsedAttr::AT_Blocks:
9542 handleBlocksAttr(S, D, AL);
9543 break;
9544 case ParsedAttr::AT_Sentinel:
9545 handleSentinelAttr(S, D, AL);
9546 break;
9547 case ParsedAttr::AT_Cleanup:
9548 handleCleanupAttr(S, D, AL);
9549 break;
9550 case ParsedAttr::AT_NoDebug:
9551 handleNoDebugAttr(S, D, AL);
9552 break;
9553 case ParsedAttr::AT_CmseNSEntry:
9554 handleCmseNSEntryAttr(S, D, AL);
9555 break;
9556 case ParsedAttr::AT_StdCall:
9557 case ParsedAttr::AT_CDecl:
9558 case ParsedAttr::AT_FastCall:
9559 case ParsedAttr::AT_ThisCall:
9560 case ParsedAttr::AT_Pascal:
9561 case ParsedAttr::AT_RegCall:
9562 case ParsedAttr::AT_SwiftCall:
9563 case ParsedAttr::AT_SwiftAsyncCall:
9564 case ParsedAttr::AT_VectorCall:
9565 case ParsedAttr::AT_MSABI:
9566 case ParsedAttr::AT_SysVABI:
9567 case ParsedAttr::AT_Pcs:
9568 case ParsedAttr::AT_IntelOclBicc:
9569 case ParsedAttr::AT_PreserveMost:
9570 case ParsedAttr::AT_PreserveAll:
9571 case ParsedAttr::AT_AArch64VectorPcs:
9572 case ParsedAttr::AT_AArch64SVEPcs:
9573 case ParsedAttr::AT_AMDGPUKernelCall:
9574 case ParsedAttr::AT_M68kRTD:
9575 case ParsedAttr::AT_PreserveNone:
9576 handleCallConvAttr(S, D, AL);
9577 break;
9578 case ParsedAttr::AT_Suppress:
9579 handleSuppressAttr(S, D, AL);
9580 break;
9581 case ParsedAttr::AT_Owner:
9582 case ParsedAttr::AT_Pointer:
9583 handleLifetimeCategoryAttr(S, D, AL);
9584 break;
9585 case ParsedAttr::AT_OpenCLAccess:
9586 handleOpenCLAccessAttr(S, D, AL);
9587 break;
9588 case ParsedAttr::AT_OpenCLNoSVM:
9589 handleOpenCLNoSVMAttr(S, D, AL);
9590 break;
9591 case ParsedAttr::AT_SwiftContext:
9592 S.AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftContext);
9593 break;
9594 case ParsedAttr::AT_SwiftAsyncContext:
9595 S.AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftAsyncContext);
9596 break;
9597 case ParsedAttr::AT_SwiftErrorResult:
9598 S.AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftErrorResult);
9599 break;
9600 case ParsedAttr::AT_SwiftIndirectResult:
9601 S.AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftIndirectResult);
9602 break;
9603 case ParsedAttr::AT_InternalLinkage:
9604 handleInternalLinkageAttr(S, D, AL);
9605 break;
9606 case ParsedAttr::AT_ZeroCallUsedRegs:
9607 handleZeroCallUsedRegsAttr(S, D, AL);
9608 break;
9609 case ParsedAttr::AT_FunctionReturnThunks:
9610 handleFunctionReturnThunksAttr(S, D, AL);
9611 break;
9612 case ParsedAttr::AT_NoMerge:
9613 handleNoMergeAttr(S, D, AL);
9614 break;
9615 case ParsedAttr::AT_NoUniqueAddress:
9616 handleNoUniqueAddressAttr(S, D, AL);
9617 break;
9618
9619 case ParsedAttr::AT_AvailableOnlyInDefaultEvalMethod:
9620 handleAvailableOnlyInDefaultEvalMethod(S, D, AL);
9621 break;
9622
9623 case ParsedAttr::AT_CountedBy:
9624 handleCountedByAttr(S, D, AL);
9625 break;
9626
9627 // Microsoft attributes:
9628 case ParsedAttr::AT_LayoutVersion:
9629 handleLayoutVersion(S, D, AL);
9630 break;
9631 case ParsedAttr::AT_Uuid:
9632 handleUuidAttr(S, D, AL);
9633 break;
9634 case ParsedAttr::AT_MSInheritance:
9635 handleMSInheritanceAttr(S, D, AL);
9636 break;
9637 case ParsedAttr::AT_Thread:
9638 handleDeclspecThreadAttr(S, D, AL);
9639 break;
9640 case ParsedAttr::AT_MSConstexpr:
9641 handleMSConstexprAttr(S, D, AL);
9642 break;
9643
9644 // HLSL attributes:
9645 case ParsedAttr::AT_HLSLNumThreads:
9646 handleHLSLNumThreadsAttr(S, D, AL);
9647 break;
9648 case ParsedAttr::AT_HLSLSV_GroupIndex:
9649 handleSimpleAttribute<HLSLSV_GroupIndexAttr>(S, D, AL);
9650 break;
9651 case ParsedAttr::AT_HLSLSV_DispatchThreadID:
9652 handleHLSLSV_DispatchThreadIDAttr(S, D, AL);
9653 break;
9654 case ParsedAttr::AT_HLSLShader:
9655 handleHLSLShaderAttr(S, D, AL);
9656 break;
9657 case ParsedAttr::AT_HLSLResourceBinding:
9658 handleHLSLResourceBindingAttr(S, D, AL);
9659 break;
9660 case ParsedAttr::AT_HLSLParamModifier:
9661 handleHLSLParamModifierAttr(S, D, AL);
9662 break;
9663
9664 case ParsedAttr::AT_AbiTag:
9665 handleAbiTagAttr(S, D, AL);
9666 break;
9667 case ParsedAttr::AT_CFGuard:
9668 handleCFGuardAttr(S, D, AL);
9669 break;
9670
9671 // Thread safety attributes:
9672 case ParsedAttr::AT_AssertExclusiveLock:
9673 handleAssertExclusiveLockAttr(S, D, AL);
9674 break;
9675 case ParsedAttr::AT_AssertSharedLock:
9676 handleAssertSharedLockAttr(S, D, AL);
9677 break;
9678 case ParsedAttr::AT_PtGuardedVar:
9679 handlePtGuardedVarAttr(S, D, AL);
9680 break;
9681 case ParsedAttr::AT_NoSanitize:
9682 handleNoSanitizeAttr(S, D, AL);
9683 break;
9684 case ParsedAttr::AT_NoSanitizeSpecific:
9685 handleNoSanitizeSpecificAttr(S, D, AL);
9686 break;
9687 case ParsedAttr::AT_GuardedBy:
9688 handleGuardedByAttr(S, D, AL);
9689 break;
9690 case ParsedAttr::AT_PtGuardedBy:
9691 handlePtGuardedByAttr(S, D, AL);
9692 break;
9693 case ParsedAttr::AT_ExclusiveTrylockFunction:
9694 handleExclusiveTrylockFunctionAttr(S, D, AL);
9695 break;
9696 case ParsedAttr::AT_LockReturned:
9697 handleLockReturnedAttr(S, D, AL);
9698 break;
9699 case ParsedAttr::AT_LocksExcluded:
9700 handleLocksExcludedAttr(S, D, AL);
9701 break;
9702 case ParsedAttr::AT_SharedTrylockFunction:
9703 handleSharedTrylockFunctionAttr(S, D, AL);
9704 break;
9705 case ParsedAttr::AT_AcquiredBefore:
9706 handleAcquiredBeforeAttr(S, D, AL);
9707 break;
9708 case ParsedAttr::AT_AcquiredAfter:
9709 handleAcquiredAfterAttr(S, D, AL);
9710 break;
9711
9712 // Capability analysis attributes.
9713 case ParsedAttr::AT_Capability:
9714 case ParsedAttr::AT_Lockable:
9715 handleCapabilityAttr(S, D, AL);
9716 break;
9717 case ParsedAttr::AT_RequiresCapability:
9718 handleRequiresCapabilityAttr(S, D, AL);
9719 break;
9720
9721 case ParsedAttr::AT_AssertCapability:
9722 handleAssertCapabilityAttr(S, D, AL);
9723 break;
9724 case ParsedAttr::AT_AcquireCapability:
9725 handleAcquireCapabilityAttr(S, D, AL);
9726 break;
9727 case ParsedAttr::AT_ReleaseCapability:
9728 handleReleaseCapabilityAttr(S, D, AL);
9729 break;
9730 case ParsedAttr::AT_TryAcquireCapability:
9731 handleTryAcquireCapabilityAttr(S, D, AL);
9732 break;
9733
9734 // Consumed analysis attributes.
9735 case ParsedAttr::AT_Consumable:
9736 handleConsumableAttr(S, D, AL);
9737 break;
9738 case ParsedAttr::AT_CallableWhen:
9739 handleCallableWhenAttr(S, D, AL);
9740 break;
9741 case ParsedAttr::AT_ParamTypestate:
9742 handleParamTypestateAttr(S, D, AL);
9743 break;
9744 case ParsedAttr::AT_ReturnTypestate:
9745 handleReturnTypestateAttr(S, D, AL);
9746 break;
9747 case ParsedAttr::AT_SetTypestate:
9748 handleSetTypestateAttr(S, D, AL);
9749 break;
9750 case ParsedAttr::AT_TestTypestate:
9751 handleTestTypestateAttr(S, D, AL);
9752 break;
9753
9754 // Type safety attributes.
9755 case ParsedAttr::AT_ArgumentWithTypeTag:
9756 handleArgumentWithTypeTagAttr(S, D, AL);
9757 break;
9758 case ParsedAttr::AT_TypeTagForDatatype:
9759 handleTypeTagForDatatypeAttr(S, D, AL);
9760 break;
9761
9762 // Swift attributes.
9763 case ParsedAttr::AT_SwiftAsyncName:
9764 handleSwiftAsyncName(S, D, AL);
9765 break;
9766 case ParsedAttr::AT_SwiftAttr:
9767 handleSwiftAttrAttr(S, D, AL);
9768 break;
9769 case ParsedAttr::AT_SwiftBridge:
9770 handleSwiftBridge(S, D, AL);
9771 break;
9772 case ParsedAttr::AT_SwiftError:
9773 handleSwiftError(S, D, AL);
9774 break;
9775 case ParsedAttr::AT_SwiftName:
9776 handleSwiftName(S, D, AL);
9777 break;
9778 case ParsedAttr::AT_SwiftNewType:
9779 handleSwiftNewType(S, D, AL);
9780 break;
9781 case ParsedAttr::AT_SwiftAsync:
9782 handleSwiftAsyncAttr(S, D, AL);
9783 break;
9784 case ParsedAttr::AT_SwiftAsyncError:
9785 handleSwiftAsyncError(S, D, AL);
9786 break;
9787
9788 // XRay attributes.
9789 case ParsedAttr::AT_XRayLogArgs:
9790 handleXRayLogArgsAttr(S, D, AL);
9791 break;
9792
9793 case ParsedAttr::AT_PatchableFunctionEntry:
9794 handlePatchableFunctionEntryAttr(S, D, AL);
9795 break;
9796
9797 case ParsedAttr::AT_AlwaysDestroy:
9798 case ParsedAttr::AT_NoDestroy:
9799 handleDestroyAttr(S, D, A: AL);
9800 break;
9801
9802 case ParsedAttr::AT_Uninitialized:
9803 handleUninitializedAttr(S, D, AL);
9804 break;
9805
9806 case ParsedAttr::AT_ObjCExternallyRetained:
9807 handleObjCExternallyRetainedAttr(S, D, AL);
9808 break;
9809
9810 case ParsedAttr::AT_MIGServerRoutine:
9811 handleMIGServerRoutineAttr(S, D, AL);
9812 break;
9813
9814 case ParsedAttr::AT_MSAllocator:
9815 handleMSAllocatorAttr(S, D, AL);
9816 break;
9817
9818 case ParsedAttr::AT_ArmBuiltinAlias:
9819 handleArmBuiltinAliasAttr(S, D, AL);
9820 break;
9821
9822 case ParsedAttr::AT_ArmLocallyStreaming:
9823 handleSimpleAttribute<ArmLocallyStreamingAttr>(S, D, AL);
9824 break;
9825
9826 case ParsedAttr::AT_ArmNew:
9827 handleArmNewAttr(S, D, AL);
9828 break;
9829
9830 case ParsedAttr::AT_AcquireHandle:
9831 handleAcquireHandleAttr(S, D, AL);
9832 break;
9833
9834 case ParsedAttr::AT_ReleaseHandle:
9835 handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
9836 break;
9837
9838 case ParsedAttr::AT_UnsafeBufferUsage:
9839 handleUnsafeBufferUsage<UnsafeBufferUsageAttr>(S, D, AL);
9840 break;
9841
9842 case ParsedAttr::AT_UseHandle:
9843 handleHandleAttr<UseHandleAttr>(S, D, AL);
9844 break;
9845
9846 case ParsedAttr::AT_EnforceTCB:
9847 handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
9848 break;
9849
9850 case ParsedAttr::AT_EnforceTCBLeaf:
9851 handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
9852 break;
9853
9854 case ParsedAttr::AT_BuiltinAlias:
9855 handleBuiltinAliasAttr(S, D, AL);
9856 break;
9857
9858 case ParsedAttr::AT_PreferredType:
9859 handlePreferredTypeAttr(S, D, AL);
9860 break;
9861
9862 case ParsedAttr::AT_UsingIfExists:
9863 handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
9864 break;
9865 }
9866}
9867
9868/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
9869/// attribute list to the specified decl, ignoring any type attributes.
9870void Sema::ProcessDeclAttributeList(
9871 Scope *S, Decl *D, const ParsedAttributesView &AttrList,
9872 const ProcessDeclAttributeOptions &Options) {
9873 if (AttrList.empty())
9874 return;
9875
9876 for (const ParsedAttr &AL : AttrList)
9877 ProcessDeclAttribute(S&: *this, scope: S, D, AL, Options);
9878
9879 // FIXME: We should be able to handle these cases in TableGen.
9880 // GCC accepts
9881 // static int a9 __attribute__((weakref));
9882 // but that looks really pointless. We reject it.
9883 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
9884 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
9885 << cast<NamedDecl>(D);
9886 D->dropAttr<WeakRefAttr>();
9887 return;
9888 }
9889
9890 // FIXME: We should be able to handle this in TableGen as well. It would be
9891 // good to have a way to specify "these attributes must appear as a group",
9892 // for these. Additionally, it would be good to have a way to specify "these
9893 // attribute must never appear as a group" for attributes like cold and hot.
9894 if (!D->hasAttr<OpenCLKernelAttr>()) {
9895 // These attributes cannot be applied to a non-kernel function.
9896 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
9897 // FIXME: This emits a different error message than
9898 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
9899 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9900 D->setInvalidDecl();
9901 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
9902 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9903 D->setInvalidDecl();
9904 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
9905 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9906 D->setInvalidDecl();
9907 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
9908 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
9909 D->setInvalidDecl();
9910 } else if (!D->hasAttr<CUDAGlobalAttr>()) {
9911 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
9912 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9913 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9914 D->setInvalidDecl();
9915 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
9916 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9917 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9918 D->setInvalidDecl();
9919 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
9920 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9921 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9922 D->setInvalidDecl();
9923 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
9924 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
9925 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
9926 D->setInvalidDecl();
9927 }
9928 }
9929 }
9930
9931 // Do this check after processing D's attributes because the attribute
9932 // objc_method_family can change whether the given method is in the init
9933 // family, and it can be applied after objc_designated_initializer. This is a
9934 // bit of a hack, but we need it to be compatible with versions of clang that
9935 // processed the attribute list in the wrong order.
9936 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
9937 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
9938 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
9939 D->dropAttr<ObjCDesignatedInitializerAttr>();
9940 }
9941}
9942
9943// Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
9944// attribute.
9945void Sema::ProcessDeclAttributeDelayed(Decl *D,
9946 const ParsedAttributesView &AttrList) {
9947 for (const ParsedAttr &AL : AttrList)
9948 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
9949 handleTransparentUnionAttr(S&: *this, D, AL);
9950 break;
9951 }
9952
9953 // For BPFPreserveAccessIndexAttr, we want to populate the attributes
9954 // to fields and inner records as well.
9955 if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
9956 handleBPFPreserveAIRecord(S&: *this, RD: cast<RecordDecl>(Val: D));
9957}
9958
9959// Annotation attributes are the only attributes allowed after an access
9960// specifier.
9961bool Sema::ProcessAccessDeclAttributeList(
9962 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
9963 for (const ParsedAttr &AL : AttrList) {
9964 if (AL.getKind() == ParsedAttr::AT_Annotate) {
9965 ProcessDeclAttribute(*this, nullptr, ASDecl, AL,
9966 ProcessDeclAttributeOptions());
9967 } else {
9968 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
9969 return true;
9970 }
9971 }
9972 return false;
9973}
9974
9975/// checkUnusedDeclAttributes - Check a list of attributes to see if it
9976/// contains any decl attributes that we should warn about.
9977static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
9978 for (const ParsedAttr &AL : A) {
9979 // Only warn if the attribute is an unignored, non-type attribute.
9980 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
9981 continue;
9982 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
9983 continue;
9984
9985 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
9986 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
9987 << AL << AL.getRange();
9988 } else {
9989 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
9990 << AL.getRange();
9991 }
9992 }
9993}
9994
9995/// checkUnusedDeclAttributes - Given a declarator which is not being
9996/// used to build a declaration, complain about any decl attributes
9997/// which might be lying around on it.
9998void Sema::checkUnusedDeclAttributes(Declarator &D) {
9999 ::checkUnusedDeclAttributes(S&: *this, A: D.getDeclarationAttributes());
10000 ::checkUnusedDeclAttributes(S&: *this, A: D.getDeclSpec().getAttributes());
10001 ::checkUnusedDeclAttributes(S&: *this, A: D.getAttributes());
10002 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
10003 ::checkUnusedDeclAttributes(S&: *this, A: D.getTypeObject(i).getAttrs());
10004}
10005
10006/// DeclClonePragmaWeak - clone existing decl (maybe definition),
10007/// \#pragma weak needs a non-definition decl and source may not have one.
10008NamedDecl *Sema::DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10009 SourceLocation Loc) {
10010 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
10011 NamedDecl *NewD = nullptr;
10012 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
10013 FunctionDecl *NewFD;
10014 // FIXME: Missing call to CheckFunctionDeclaration().
10015 // FIXME: Mangling?
10016 // FIXME: Is the qualifier info correct?
10017 // FIXME: Is the DeclContext correct?
10018 NewFD = FunctionDecl::Create(
10019 FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
10020 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
10021 getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/,
10022 FD->hasPrototype(), ConstexprSpecKind::Unspecified,
10023 FD->getTrailingRequiresClause());
10024 NewD = NewFD;
10025
10026 if (FD->getQualifier())
10027 NewFD->setQualifierInfo(FD->getQualifierLoc());
10028
10029 // Fake up parameter variables; they are declared as if this were
10030 // a typedef.
10031 QualType FDTy = FD->getType();
10032 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
10033 SmallVector<ParmVarDecl*, 16> Params;
10034 for (const auto &AI : FT->param_types()) {
10035 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
10036 Param->setScopeInfo(0, Params.size());
10037 Params.push_back(Param);
10038 }
10039 NewFD->setParams(Params);
10040 }
10041 } else if (auto *VD = dyn_cast<VarDecl>(Val: ND)) {
10042 NewD = VarDecl::Create(C&: VD->getASTContext(), DC: VD->getDeclContext(),
10043 StartLoc: VD->getInnerLocStart(), IdLoc: VD->getLocation(), Id: II,
10044 T: VD->getType(), TInfo: VD->getTypeSourceInfo(),
10045 S: VD->getStorageClass());
10046 if (VD->getQualifier())
10047 cast<VarDecl>(Val: NewD)->setQualifierInfo(VD->getQualifierLoc());
10048 }
10049 return NewD;
10050}
10051
10052/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
10053/// applied to it, possibly with an alias.
10054void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W) {
10055 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
10056 IdentifierInfo *NDId = ND->getIdentifier();
10057 NamedDecl *NewD = DeclClonePragmaWeak(ND, II: W.getAlias(), Loc: W.getLocation());
10058 NewD->addAttr(
10059 AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
10060 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
10061 WeakTopLevelDecl.push_back(NewD);
10062 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
10063 // to insert Decl at TU scope, sorry.
10064 DeclContext *SavedContext = CurContext;
10065 CurContext = Context.getTranslationUnitDecl();
10066 NewD->setDeclContext(CurContext);
10067 NewD->setLexicalDeclContext(CurContext);
10068 PushOnScopeChains(D: NewD, S);
10069 CurContext = SavedContext;
10070 } else { // just add weak to existing
10071 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
10072 }
10073}
10074
10075void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
10076 // It's valid to "forward-declare" #pragma weak, in which case we
10077 // have to do this.
10078 LoadExternalWeakUndeclaredIdentifiers();
10079 if (WeakUndeclaredIdentifiers.empty())
10080 return;
10081 NamedDecl *ND = nullptr;
10082 if (auto *VD = dyn_cast<VarDecl>(Val: D))
10083 if (VD->isExternC())
10084 ND = VD;
10085 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
10086 if (FD->isExternC())
10087 ND = FD;
10088 if (!ND)
10089 return;
10090 if (IdentifierInfo *Id = ND->getIdentifier()) {
10091 auto I = WeakUndeclaredIdentifiers.find(Key: Id);
10092 if (I != WeakUndeclaredIdentifiers.end()) {
10093 auto &WeakInfos = I->second;
10094 for (const auto &W : WeakInfos)
10095 DeclApplyPragmaWeak(S, ND, W);
10096 std::remove_reference_t<decltype(WeakInfos)> EmptyWeakInfos;
10097 WeakInfos.swap(RHS&: EmptyWeakInfos);
10098 }
10099 }
10100}
10101
10102/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
10103/// it, apply them to D. This is a bit tricky because PD can have attributes
10104/// specified in many different places, and we need to find and apply them all.
10105void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
10106 // Ordering of attributes can be important, so we take care to process
10107 // attributes in the order in which they appeared in the source code.
10108
10109 // First, process attributes that appeared on the declaration itself (but
10110 // only if they don't have the legacy behavior of "sliding" to the DeclSepc).
10111 ParsedAttributesView NonSlidingAttrs;
10112 for (ParsedAttr &AL : PD.getDeclarationAttributes()) {
10113 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
10114 // Skip processing the attribute, but do check if it appertains to the
10115 // declaration. This is needed for the `MatrixType` attribute, which,
10116 // despite being a type attribute, defines a `SubjectList` that only
10117 // allows it to be used on typedef declarations.
10118 AL.diagnoseAppertainsTo(S&: *this, D);
10119 } else {
10120 NonSlidingAttrs.addAtEnd(newAttr: &AL);
10121 }
10122 }
10123 ProcessDeclAttributeList(S, D, AttrList: NonSlidingAttrs);
10124
10125 // Apply decl attributes from the DeclSpec if present.
10126 if (!PD.getDeclSpec().getAttributes().empty()) {
10127 ProcessDeclAttributeList(S, D, AttrList: PD.getDeclSpec().getAttributes(),
10128 Options: ProcessDeclAttributeOptions()
10129 .WithIncludeCXX11Attributes(Val: false)
10130 .WithIgnoreTypeAttributes(Val: true));
10131 }
10132
10133 // Walk the declarator structure, applying decl attributes that were in a type
10134 // position to the decl itself. This handles cases like:
10135 // int *__attr__(x)** D;
10136 // when X is a decl attribute.
10137 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) {
10138 ProcessDeclAttributeList(S, D, AttrList: PD.getTypeObject(i).getAttrs(),
10139 Options: ProcessDeclAttributeOptions()
10140 .WithIncludeCXX11Attributes(Val: false)
10141 .WithIgnoreTypeAttributes(Val: true));
10142 }
10143
10144 // Finally, apply any attributes on the decl itself.
10145 ProcessDeclAttributeList(S, D, AttrList: PD.getAttributes());
10146
10147 // Apply additional attributes specified by '#pragma clang attribute'.
10148 AddPragmaAttributes(S, D);
10149}
10150
10151/// Is the given declaration allowed to use a forbidden type?
10152/// If so, it'll still be annotated with an attribute that makes it
10153/// illegal to actually use.
10154static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
10155 const DelayedDiagnostic &diag,
10156 UnavailableAttr::ImplicitReason &reason) {
10157 // Private ivars are always okay. Unfortunately, people don't
10158 // always properly make their ivars private, even in system headers.
10159 // Plus we need to make fields okay, too.
10160 if (!isa<FieldDecl>(Val: D) && !isa<ObjCPropertyDecl>(Val: D) &&
10161 !isa<FunctionDecl>(Val: D))
10162 return false;
10163
10164 // Silently accept unsupported uses of __weak in both user and system
10165 // declarations when it's been disabled, for ease of integration with
10166 // -fno-objc-arc files. We do have to take some care against attempts
10167 // to define such things; for now, we've only done that for ivars
10168 // and properties.
10169 if ((isa<ObjCIvarDecl>(Val: D) || isa<ObjCPropertyDecl>(Val: D))) {
10170 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
10171 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
10172 reason = UnavailableAttr::IR_ForbiddenWeak;
10173 return true;
10174 }
10175 }
10176
10177 // Allow all sorts of things in system headers.
10178 if (S.Context.getSourceManager().isInSystemHeader(Loc: D->getLocation())) {
10179 // Currently, all the failures dealt with this way are due to ARC
10180 // restrictions.
10181 reason = UnavailableAttr::IR_ARCForbiddenType;
10182 return true;
10183 }
10184
10185 return false;
10186}
10187
10188/// Handle a delayed forbidden-type diagnostic.
10189static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
10190 Decl *D) {
10191 auto Reason = UnavailableAttr::IR_None;
10192 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
10193 assert(Reason && "didn't set reason?");
10194 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
10195 return;
10196 }
10197 if (S.getLangOpts().ObjCAutoRefCount)
10198 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
10199 // FIXME: we may want to suppress diagnostics for all
10200 // kind of forbidden type messages on unavailable functions.
10201 if (FD->hasAttr<UnavailableAttr>() &&
10202 DD.getForbiddenTypeDiagnostic() ==
10203 diag::err_arc_array_param_no_ownership) {
10204 DD.Triggered = true;
10205 return;
10206 }
10207 }
10208
10209 S.Diag(Loc: DD.Loc, DiagID: DD.getForbiddenTypeDiagnostic())
10210 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
10211 DD.Triggered = true;
10212}
10213
10214
10215void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
10216 assert(DelayedDiagnostics.getCurrentPool());
10217 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
10218 DelayedDiagnostics.popWithoutEmitting(state);
10219
10220 // When delaying diagnostics to run in the context of a parsed
10221 // declaration, we only want to actually emit anything if parsing
10222 // succeeds.
10223 if (!decl) return;
10224
10225 // We emit all the active diagnostics in this pool or any of its
10226 // parents. In general, we'll get one pool for the decl spec
10227 // and a child pool for each declarator; in a decl group like:
10228 // deprecated_typedef foo, *bar, baz();
10229 // only the declarator pops will be passed decls. This is correct;
10230 // we really do need to consider delayed diagnostics from the decl spec
10231 // for each of the different declarations.
10232 const DelayedDiagnosticPool *pool = &poppedPool;
10233 do {
10234 bool AnyAccessFailures = false;
10235 for (DelayedDiagnosticPool::pool_iterator
10236 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
10237 // This const_cast is a bit lame. Really, Triggered should be mutable.
10238 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
10239 if (diag.Triggered)
10240 continue;
10241
10242 switch (diag.Kind) {
10243 case DelayedDiagnostic::Availability:
10244 // Don't bother giving deprecation/unavailable diagnostics if
10245 // the decl is invalid.
10246 if (!decl->isInvalidDecl())
10247 handleDelayedAvailabilityCheck(DD&: diag, Ctx: decl);
10248 break;
10249
10250 case DelayedDiagnostic::Access:
10251 // Only produce one access control diagnostic for a structured binding
10252 // declaration: we don't need to tell the user that all the fields are
10253 // inaccessible one at a time.
10254 if (AnyAccessFailures && isa<DecompositionDecl>(Val: decl))
10255 continue;
10256 HandleDelayedAccessCheck(DD&: diag, Ctx: decl);
10257 if (diag.Triggered)
10258 AnyAccessFailures = true;
10259 break;
10260
10261 case DelayedDiagnostic::ForbiddenType:
10262 handleDelayedForbiddenType(S&: *this, DD&: diag, D: decl);
10263 break;
10264 }
10265 }
10266 } while ((pool = pool->getParent()));
10267}
10268
10269/// Given a set of delayed diagnostics, re-emit them as if they had
10270/// been delayed in the current context instead of in the given pool.
10271/// Essentially, this just moves them to the current pool.
10272void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
10273 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
10274 assert(curPool && "re-emitting in undelayed context not supported");
10275 curPool->steal(pool);
10276}
10277

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