1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements decl-related attribute processing.
11 //===----------------------------------------------------------------------===//
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/Basic/CharInfo.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/MathExtras.h"
39 using namespace clang;
42 namespace AttributeLangSupport {
48 } // end namespace AttributeLangSupport
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 /// isFunctionOrMethod - Return true if the given decl has function
55 /// type (function or function-typed variable) or an Objective-C
57 static bool isFunctionOrMethod(const Decl *D) {
58 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
61 /// Return true if the given decl has function type (function or
62 /// function-typed variable) or an Objective-C method or a block.
63 static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
67 /// Return true if the given decl has a declarator that should have
68 /// been processed by Sema::GetTypeForDeclarator.
69 static bool hasDeclarator(const Decl *D) {
70 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
71 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
75 /// hasFunctionProto - Return true if the given decl has a argument
76 /// information. This decl should have already passed
77 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
78 static bool hasFunctionProto(const Decl *D) {
79 if (const FunctionType *FnTy = D->getFunctionType())
80 return isa<FunctionProtoType>(FnTy);
81 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
84 /// getFunctionOrMethodNumParams - Return number of function or method
85 /// parameters. It is an error to call this on a K&R function (use
86 /// hasFunctionProto first).
87 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
88 if (const FunctionType *FnTy = D->getFunctionType())
89 return cast<FunctionProtoType>(FnTy)->getNumParams();
90 if (const auto *BD = dyn_cast<BlockDecl>(D))
91 return BD->getNumParams();
92 return cast<ObjCMethodDecl>(D)->param_size();
95 static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
97 if (const auto *FD = dyn_cast<FunctionDecl>(D))
98 return FD->getParamDecl(Idx);
99 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
100 return MD->getParamDecl(Idx);
101 if (const auto *BD = dyn_cast<BlockDecl>(D))
102 return BD->getParamDecl(Idx);
106 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
107 if (const FunctionType *FnTy = D->getFunctionType())
108 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
109 if (const auto *BD = dyn_cast<BlockDecl>(D))
110 return BD->getParamDecl(Idx)->getType();
112 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
115 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
116 if (auto *PVD = getFunctionOrMethodParam(D, Idx))
117 return PVD->getSourceRange();
118 return SourceRange();
121 static QualType getFunctionOrMethodResultType(const Decl *D) {
122 if (const FunctionType *FnTy = D->getFunctionType())
123 return FnTy->getReturnType();
124 return cast<ObjCMethodDecl>(D)->getReturnType();
127 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
128 if (const auto *FD = dyn_cast<FunctionDecl>(D))
129 return FD->getReturnTypeSourceRange();
130 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
131 return MD->getReturnTypeSourceRange();
132 return SourceRange();
135 static bool isFunctionOrMethodVariadic(const Decl *D) {
136 if (const FunctionType *FnTy = D->getFunctionType())
137 return cast<FunctionProtoType>(FnTy)->isVariadic();
138 if (const auto *BD = dyn_cast<BlockDecl>(D))
139 return BD->isVariadic();
140 return cast<ObjCMethodDecl>(D)->isVariadic();
143 static bool isInstanceMethod(const Decl *D) {
144 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
145 return MethodDecl->isInstance();
149 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
150 const auto *PT = T->getAs<ObjCObjectPointerType>();
154 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
158 IdentifierInfo* ClsName = Cls->getIdentifier();
160 // FIXME: Should we walk the chain of classes?
161 return ClsName == &Ctx.Idents.get("NSString") ||
162 ClsName == &Ctx.Idents.get("NSMutableString");
165 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
166 const auto *PT = T->getAs<PointerType>();
170 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
174 const RecordDecl *RD = RT->getDecl();
175 if (RD->getTagKind() != TTK_Struct)
178 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
181 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
182 // FIXME: Include the type in the argument list.
183 return AL.getNumArgs() + AL.hasParsedType();
186 template <typename Compare>
187 static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
188 unsigned Num, unsigned Diag,
190 if (Comp(getNumAttributeArgs(AL), Num)) {
191 S.Diag(AL.getLoc(), Diag) << AL << Num;
198 /// Check if the attribute has exactly as many args as Num. May
200 static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
201 return checkAttributeNumArgsImpl(S, AL, Num,
202 diag::err_attribute_wrong_number_arguments,
203 std::not_equal_to<unsigned>());
206 /// Check if the attribute has at least as many args as Num. May
208 static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
210 return checkAttributeNumArgsImpl(S, AL, Num,
211 diag::err_attribute_too_few_arguments,
212 std::less<unsigned>());
215 /// Check if the attribute has at most as many args as Num. May
217 static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
219 return checkAttributeNumArgsImpl(S, AL, Num,
220 diag::err_attribute_too_many_arguments,
221 std::greater<unsigned>());
224 /// A helper function to provide Attribute Location for the Attr types
225 /// AND the ParsedAttr.
226 template <typename AttrInfo>
227 static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
228 SourceLocation>::type
229 getAttrLoc(const AttrInfo &AL) {
230 return AL.getLocation();
232 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
234 /// If Expr is a valid integer constant, get the value of the integer
235 /// expression and return success or failure. May output an error.
237 /// Negative argument is implicitly converted to unsigned, unless
238 /// \p StrictlyUnsigned is true.
239 template <typename AttrInfo>
240 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
241 uint32_t &Val, unsigned Idx = UINT_MAX,
242 bool StrictlyUnsigned = false) {
244 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
245 !Expr->isIntegerConstantExpr(I, S.Context)) {
247 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
248 << &AI << Idx << AANT_ArgumentIntegerConstant
249 << Expr->getSourceRange();
251 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
252 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
257 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
258 << I.toString(10, false) << 32 << /* Unsigned */ 1;
262 if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
263 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
264 << &AI << /*non-negative*/ 1;
268 Val = (uint32_t)I.getZExtValue();
272 /// Wrapper around checkUInt32Argument, with an extra check to be sure
273 /// that the result will fit into a regular (signed) int. All args have the same
274 /// purpose as they do in checkUInt32Argument.
275 template <typename AttrInfo>
276 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
277 int &Val, unsigned Idx = UINT_MAX) {
279 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
282 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
283 llvm::APSInt I(32); // for toString
285 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
286 << I.toString(10, false) << 32 << /* Unsigned */ 0;
294 /// Diagnose mutually exclusive attributes when present on a given
295 /// declaration. Returns true if diagnosed.
296 template <typename AttrTy>
297 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
298 if (const auto *A = D->getAttr<AttrTy>()) {
299 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
300 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
306 template <typename AttrTy>
307 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
308 if (const auto *A = D->getAttr<AttrTy>()) {
309 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
311 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
317 /// Check if IdxExpr is a valid parameter index for a function or
318 /// instance method D. May output an error.
320 /// \returns true if IdxExpr is a valid index.
321 template <typename AttrInfo>
322 static bool checkFunctionOrMethodParameterIndex(
323 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
324 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
325 assert(isFunctionOrMethodOrBlock(D));
327 // In C++ the implicit 'this' function parameter also counts.
328 // Parameters are counted from one.
329 bool HP = hasFunctionProto(D);
330 bool HasImplicitThisParam = isInstanceMethod(D);
331 bool IV = HP && isFunctionOrMethodVariadic(D);
333 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
336 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
337 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
338 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
339 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
340 << IdxExpr->getSourceRange();
344 unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX);
345 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
346 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
347 << &AI << AttrArgNum << IdxExpr->getSourceRange();
350 if (HasImplicitThisParam && !CanIndexImplicitThis) {
351 if (IdxSource == 1) {
352 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
353 << &AI << IdxExpr->getSourceRange();
358 Idx = ParamIdx(IdxSource, D);
362 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
363 /// If not emit an error and return false. If the argument is an identifier it
364 /// will emit an error with a fixit hint and treat it as if it was a string
366 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
368 SourceLocation *ArgLocation) {
369 // Look for identifiers. If we have one emit a hint to fix it to a literal.
370 if (AL.isArgIdent(ArgNum)) {
371 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
372 Diag(Loc->Loc, diag::err_attribute_argument_type)
373 << AL << AANT_ArgumentString
374 << FixItHint::CreateInsertion(Loc->Loc, "\"")
375 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
376 Str = Loc->Ident->getName();
378 *ArgLocation = Loc->Loc;
382 // Now check for an actual string literal.
383 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
384 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
386 *ArgLocation = ArgExpr->getBeginLoc();
388 if (!Literal || !Literal->isAscii()) {
389 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
390 << AL << AANT_ArgumentString;
394 Str = Literal->getString();
398 /// Applies the given attribute to the Decl without performing any
399 /// additional semantic checking.
400 template <typename AttrType>
401 static void handleSimpleAttribute(Sema &S, Decl *D, SourceRange SR,
402 unsigned SpellingIndex) {
403 D->addAttr(::new (S.Context) AttrType(SR, S.Context, SpellingIndex));
406 template <typename AttrType>
407 static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) {
408 handleSimpleAttribute<AttrType>(S, D, AL.getRange(),
409 AL.getAttributeSpellingListIndex());
413 template <typename... DiagnosticArgs>
414 static const Sema::SemaDiagnosticBuilder&
415 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
419 template <typename T, typename... DiagnosticArgs>
420 static const Sema::SemaDiagnosticBuilder&
421 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
422 DiagnosticArgs &&... ExtraArgs) {
423 return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
424 std::forward<DiagnosticArgs>(ExtraArgs)...);
427 /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
428 /// {@code PassesCheck} is true.
429 /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
430 /// specified in {@code ExtraArgs}.
431 template <typename AttrType, typename... DiagnosticArgs>
433 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR,
434 unsigned SpellingIndex,
436 unsigned DiagID, DiagnosticArgs&&... ExtraArgs) {
438 Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
439 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
442 handleSimpleAttribute<AttrType>(S, D, SR, SpellingIndex);
445 template <typename AttrType, typename... DiagnosticArgs>
447 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL,
450 DiagnosticArgs&&... ExtraArgs) {
451 return handleSimpleAttributeOrDiagnose<AttrType>(
452 S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck,
453 DiagID, std::forward<DiagnosticArgs>(ExtraArgs)...);
456 template <typename AttrType>
457 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
458 const ParsedAttr &AL) {
459 handleSimpleAttribute<AttrType>(S, D, AL);
462 /// Applies the given attribute to the Decl so long as the Decl doesn't
463 /// already have one of the given incompatible attributes.
464 template <typename AttrType, typename IncompatibleAttrType,
465 typename... IncompatibleAttrTypes>
466 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
467 const ParsedAttr &AL) {
468 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
470 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
474 /// Check if the passed-in expression is of type int or bool.
475 static bool isIntOrBool(Expr *Exp) {
476 QualType QT = Exp->getType();
477 return QT->isBooleanType() || QT->isIntegerType();
481 // Check to see if the type is a smart pointer of some kind. We assume
482 // it's a smart pointer if it defines both operator-> and operator*.
483 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
484 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
485 OverloadedOperatorKind Op) {
486 DeclContextLookupResult Result =
487 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
488 return !Result.empty();
491 const RecordDecl *Record = RT->getDecl();
492 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
493 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
494 if (foundStarOperator && foundArrowOperator)
497 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
501 for (auto BaseSpecifier : CXXRecord->bases()) {
502 if (!foundStarOperator)
503 foundStarOperator = IsOverloadedOperatorPresent(
504 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
505 if (!foundArrowOperator)
506 foundArrowOperator = IsOverloadedOperatorPresent(
507 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
510 if (foundStarOperator && foundArrowOperator)
516 /// Check if passed in Decl is a pointer type.
517 /// Note that this function may produce an error message.
518 /// \return true if the Decl is a pointer type; false otherwise
519 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
520 const ParsedAttr &AL) {
521 const auto *VD = cast<ValueDecl>(D);
522 QualType QT = VD->getType();
523 if (QT->isAnyPointerType())
526 if (const auto *RT = QT->getAs<RecordType>()) {
527 // If it's an incomplete type, it could be a smart pointer; skip it.
528 // (We don't want to force template instantiation if we can avoid it,
529 // since that would alter the order in which templates are instantiated.)
530 if (RT->isIncompleteType())
533 if (threadSafetyCheckIsSmartPointer(S, RT))
537 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
541 /// Checks that the passed in QualType either is of RecordType or points
542 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
543 static const RecordType *getRecordType(QualType QT) {
544 if (const auto *RT = QT->getAs<RecordType>())
547 // Now check if we point to record type.
548 if (const auto *PT = QT->getAs<PointerType>())
549 return PT->getPointeeType()->getAs<RecordType>();
554 template <typename AttrType>
555 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
556 // Check if the record itself has the attribute.
557 if (RD->hasAttr<AttrType>())
560 // Else check if any base classes have the attribute.
561 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
562 CXXBasePaths BPaths(false, false);
563 if (CRD->lookupInBases(
564 [](const CXXBaseSpecifier *BS, CXXBasePath &) {
565 const auto &Ty = *BS->getType();
566 // If it's type-dependent, we assume it could have the attribute.
567 if (Ty.isDependentType())
569 return Ty.getAs<RecordType>()->getDecl()->hasAttr<AttrType>();
577 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
578 const RecordType *RT = getRecordType(Ty);
583 // Don't check for the capability if the class hasn't been defined yet.
584 if (RT->isIncompleteType())
587 // Allow smart pointers to be used as capability objects.
588 // FIXME -- Check the type that the smart pointer points to.
589 if (threadSafetyCheckIsSmartPointer(S, RT))
592 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
595 static bool checkTypedefTypeForCapability(QualType Ty) {
596 const auto *TD = Ty->getAs<TypedefType>();
600 TypedefNameDecl *TN = TD->getDecl();
604 return TN->hasAttr<CapabilityAttr>();
607 static bool typeHasCapability(Sema &S, QualType Ty) {
608 if (checkTypedefTypeForCapability(Ty))
611 if (checkRecordTypeForCapability(S, Ty))
617 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
618 // Capability expressions are simple expressions involving the boolean logic
619 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
620 // a DeclRefExpr is found, its type should be checked to determine whether it
621 // is a capability or not.
623 if (const auto *E = dyn_cast<CastExpr>(Ex))
624 return isCapabilityExpr(S, E->getSubExpr());
625 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
626 return isCapabilityExpr(S, E->getSubExpr());
627 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
628 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
629 E->getOpcode() == UO_Deref)
630 return isCapabilityExpr(S, E->getSubExpr());
632 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
633 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
634 return isCapabilityExpr(S, E->getLHS()) &&
635 isCapabilityExpr(S, E->getRHS());
639 return typeHasCapability(S, Ex->getType());
642 /// Checks that all attribute arguments, starting from Sidx, resolve to
643 /// a capability object.
644 /// \param Sidx The attribute argument index to start checking with.
645 /// \param ParamIdxOk Whether an argument can be indexing into a function
647 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
648 const ParsedAttr &AL,
649 SmallVectorImpl<Expr *> &Args,
651 bool ParamIdxOk = false) {
652 if (Sidx == AL.getNumArgs()) {
653 // If we don't have any capability arguments, the attribute implicitly
654 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
655 // a non-static method, and that the class is a (scoped) capability.
656 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
657 if (MD && !MD->isStatic()) {
658 const CXXRecordDecl *RD = MD->getParent();
659 // FIXME -- need to check this again on template instantiation
660 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
661 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
663 diag::warn_thread_attribute_not_on_capability_member)
664 << AL << MD->getParent();
666 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
671 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
672 Expr *ArgExp = AL.getArgAsExpr(Idx);
674 if (ArgExp->isTypeDependent()) {
675 // FIXME -- need to check this again on template instantiation
676 Args.push_back(ArgExp);
680 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
681 if (StrLit->getLength() == 0 ||
682 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
683 // Pass empty strings to the analyzer without warnings.
684 // Treat "*" as the universal lock.
685 Args.push_back(ArgExp);
689 // We allow constant strings to be used as a placeholder for expressions
690 // that are not valid C++ syntax, but warn that they are ignored.
691 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
692 Args.push_back(ArgExp);
696 QualType ArgTy = ArgExp->getType();
698 // A pointer to member expression of the form &MyClass::mu is treated
699 // specially -- we need to look at the type of the member.
700 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
701 if (UOp->getOpcode() == UO_AddrOf)
702 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
703 if (DRE->getDecl()->isCXXInstanceMember())
704 ArgTy = DRE->getDecl()->getType();
706 // First see if we can just cast to record type, or pointer to record type.
707 const RecordType *RT = getRecordType(ArgTy);
709 // Now check if we index into a record type function param.
710 if(!RT && ParamIdxOk) {
711 const auto *FD = dyn_cast<FunctionDecl>(D);
712 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
714 unsigned int NumParams = FD->getNumParams();
715 llvm::APInt ArgValue = IL->getValue();
716 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
717 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
718 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
720 diag::err_attribute_argument_out_of_bounds_extra_info)
721 << AL << Idx + 1 << NumParams;
724 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
728 // If the type does not have a capability, see if the components of the
729 // expression have capabilities. This allows for writing C code where the
730 // capability may be on the type, and the expression is a capability
731 // boolean logic expression. Eg) requires_capability(A || B && !C)
732 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
733 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
736 Args.push_back(ArgExp);
740 //===----------------------------------------------------------------------===//
741 // Attribute Implementations
742 //===----------------------------------------------------------------------===//
744 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
745 if (!threadSafetyCheckIsPointer(S, D, AL))
748 D->addAttr(::new (S.Context)
749 PtGuardedVarAttr(AL.getRange(), S.Context,
750 AL.getAttributeSpellingListIndex()));
753 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
755 SmallVector<Expr *, 1> Args;
756 // check that all arguments are lockable objects
757 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
758 unsigned Size = Args.size();
767 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
769 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
772 D->addAttr(::new (S.Context) GuardedByAttr(
773 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
776 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
778 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
781 if (!threadSafetyCheckIsPointer(S, D, AL))
784 D->addAttr(::new (S.Context) PtGuardedByAttr(
785 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
788 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
789 SmallVectorImpl<Expr *> &Args) {
790 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
793 // Check that this attribute only applies to lockable types.
794 QualType QT = cast<ValueDecl>(D)->getType();
795 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
796 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
800 // Check that all arguments are lockable objects.
801 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
808 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
809 SmallVector<Expr *, 1> Args;
810 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
813 Expr **StartArg = &Args[0];
814 D->addAttr(::new (S.Context) AcquiredAfterAttr(
815 AL.getRange(), S.Context, StartArg, Args.size(),
816 AL.getAttributeSpellingListIndex()));
819 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
820 SmallVector<Expr *, 1> Args;
821 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
824 Expr **StartArg = &Args[0];
825 D->addAttr(::new (S.Context) AcquiredBeforeAttr(
826 AL.getRange(), S.Context, StartArg, Args.size(),
827 AL.getAttributeSpellingListIndex()));
830 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
831 SmallVectorImpl<Expr *> &Args) {
832 // zero or more arguments ok
833 // check that all arguments are lockable objects
834 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
839 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
840 SmallVector<Expr *, 1> Args;
841 if (!checkLockFunAttrCommon(S, D, AL, Args))
844 unsigned Size = Args.size();
845 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
846 D->addAttr(::new (S.Context)
847 AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size,
848 AL.getAttributeSpellingListIndex()));
851 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
852 const ParsedAttr &AL) {
853 SmallVector<Expr *, 1> Args;
854 if (!checkLockFunAttrCommon(S, D, AL, Args))
857 unsigned Size = Args.size();
858 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
859 D->addAttr(::new (S.Context) AssertExclusiveLockAttr(
860 AL.getRange(), S.Context, StartArg, Size,
861 AL.getAttributeSpellingListIndex()));
864 /// Checks to be sure that the given parameter number is in bounds, and
865 /// is an integral type. Will emit appropriate diagnostics if this returns
868 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
869 template <typename AttrInfo>
870 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
871 const AttrInfo &AI, unsigned AttrArgNo) {
872 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
873 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
875 if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
879 const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
880 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
881 SourceLocation SrcLoc = AttrArg->getBeginLoc();
882 S.Diag(SrcLoc, diag::err_attribute_integers_only)
883 << AI << Param->getSourceRange();
889 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
890 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
891 !checkAttributeAtMostNumArgs(S, AL, 2))
894 const auto *FD = cast<FunctionDecl>(D);
895 if (!FD->getReturnType()->isPointerType()) {
896 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
900 const Expr *SizeExpr = AL.getArgAsExpr(0);
902 // Parameter indices are 1-indexed, hence Index=1
903 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
905 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
907 ParamIdx SizeArgNo(SizeArgNoVal, D);
909 ParamIdx NumberArgNo;
910 if (AL.getNumArgs() == 2) {
911 const Expr *NumberExpr = AL.getArgAsExpr(1);
913 // Parameter indices are 1-based, hence Index=2
914 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
916 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
918 NumberArgNo = ParamIdx(Val, D);
921 D->addAttr(::new (S.Context)
922 AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo,
923 AL.getAttributeSpellingListIndex()));
926 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
927 SmallVectorImpl<Expr *> &Args) {
928 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
931 if (!isIntOrBool(AL.getArgAsExpr(0))) {
932 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
933 << AL << 1 << AANT_ArgumentIntOrBool;
937 // check that all arguments are lockable objects
938 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
943 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
944 const ParsedAttr &AL) {
945 SmallVector<Expr*, 2> Args;
946 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
949 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
950 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(),
951 AL.getAttributeSpellingListIndex()));
954 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
955 const ParsedAttr &AL) {
956 SmallVector<Expr*, 2> Args;
957 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
960 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
961 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(),
962 Args.size(), AL.getAttributeSpellingListIndex()));
965 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
966 // check that the argument is lockable object
967 SmallVector<Expr*, 1> Args;
968 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
969 unsigned Size = Args.size();
973 D->addAttr(::new (S.Context)
974 LockReturnedAttr(AL.getRange(), S.Context, Args[0],
975 AL.getAttributeSpellingListIndex()));
978 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
979 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
982 // check that all arguments are lockable objects
983 SmallVector<Expr*, 1> Args;
984 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
985 unsigned Size = Args.size();
988 Expr **StartArg = &Args[0];
990 D->addAttr(::new (S.Context)
991 LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size,
992 AL.getAttributeSpellingListIndex()));
995 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
996 Expr *&Cond, StringRef &Msg) {
997 Cond = AL.getArgAsExpr(0);
998 if (!Cond->isTypeDependent()) {
999 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
1000 if (Converted.isInvalid())
1002 Cond = Converted.get();
1005 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
1009 Msg = "<no message provided>";
1011 SmallVector<PartialDiagnosticAt, 8> Diags;
1012 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
1013 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
1015 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
1016 for (const PartialDiagnosticAt &PDiag : Diags)
1017 S.Diag(PDiag.first, PDiag.second);
1023 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1024 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
1028 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1029 D->addAttr(::new (S.Context)
1030 EnableIfAttr(AL.getRange(), S.Context, Cond, Msg,
1031 AL.getAttributeSpellingListIndex()));
1035 /// Determines if a given Expr references any of the given function's
1036 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1037 class ArgumentDependenceChecker
1038 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1040 const CXXRecordDecl *ClassType;
1042 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1046 ArgumentDependenceChecker(const FunctionDecl *FD) {
1048 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1049 ClassType = MD->getParent();
1051 ClassType = nullptr;
1053 Parms.insert(FD->param_begin(), FD->param_end());
1056 bool referencesArgs(Expr *E) {
1062 bool VisitCXXThisExpr(CXXThisExpr *E) {
1063 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1064 "`this` doesn't refer to the enclosing class?");
1069 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1070 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1071 if (Parms.count(PVD)) {
1080 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1081 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1085 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1088 StringRef DiagTypeStr;
1089 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1092 DiagnoseIfAttr::DiagnosticType DiagType;
1093 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1094 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1095 diag::err_diagnose_if_invalid_diagnostic_type);
1099 bool ArgDependent = false;
1100 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1101 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1102 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1103 AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent,
1104 cast<NamedDecl>(D), AL.getAttributeSpellingListIndex()));
1107 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1108 if (D->hasAttr<PassObjectSizeAttr>()) {
1109 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1113 Expr *E = AL.getArgAsExpr(0);
1115 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1118 // pass_object_size's argument is passed in as the second argument of
1119 // __builtin_object_size. So, it has the same constraints as that second
1120 // argument; namely, it must be in the range [0, 3].
1122 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1123 << AL << 0 << 3 << E->getSourceRange();
1127 // pass_object_size is only supported on constant pointer parameters; as a
1128 // kindness to users, we allow the parameter to be non-const for declarations.
1129 // At this point, we have no clue if `D` belongs to a function declaration or
1130 // definition, so we defer the constness check until later.
1131 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1132 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1136 D->addAttr(::new (S.Context) PassObjectSizeAttr(
1137 AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex()));
1140 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1141 ConsumableAttr::ConsumedState DefaultState;
1143 if (AL.isArgIdent(0)) {
1144 IdentifierLoc *IL = AL.getArgAsIdent(0);
1145 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1147 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1152 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1153 << AL << AANT_ArgumentIdentifier;
1157 D->addAttr(::new (S.Context)
1158 ConsumableAttr(AL.getRange(), S.Context, DefaultState,
1159 AL.getAttributeSpellingListIndex()));
1162 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1163 const ParsedAttr &AL) {
1164 QualType ThisType = MD->getThisType()->getPointeeType();
1166 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1167 if (!RD->hasAttr<ConsumableAttr>()) {
1168 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1169 RD->getNameAsString();
1178 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1179 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1182 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1185 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1186 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1187 CallableWhenAttr::ConsumedState CallableState;
1189 StringRef StateString;
1191 if (AL.isArgIdent(ArgIndex)) {
1192 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1193 StateString = Ident->Ident->getName();
1196 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1200 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1202 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1206 States.push_back(CallableState);
1209 D->addAttr(::new (S.Context)
1210 CallableWhenAttr(AL.getRange(), S.Context, States.data(),
1211 States.size(), AL.getAttributeSpellingListIndex()));
1214 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1215 ParamTypestateAttr::ConsumedState ParamState;
1217 if (AL.isArgIdent(0)) {
1218 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1219 StringRef StateString = Ident->Ident->getName();
1221 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1223 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1224 << AL << StateString;
1228 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1229 << AL << AANT_ArgumentIdentifier;
1233 // FIXME: This check is currently being done in the analysis. It can be
1234 // enabled here only after the parser propagates attributes at
1235 // template specialization definition, not declaration.
1236 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1237 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1239 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1240 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1241 // ReturnType.getAsString();
1245 D->addAttr(::new (S.Context)
1246 ParamTypestateAttr(AL.getRange(), S.Context, ParamState,
1247 AL.getAttributeSpellingListIndex()));
1250 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1251 ReturnTypestateAttr::ConsumedState ReturnState;
1253 if (AL.isArgIdent(0)) {
1254 IdentifierLoc *IL = AL.getArgAsIdent(0);
1255 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1257 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1262 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1263 << AL << AANT_ArgumentIdentifier;
1267 // FIXME: This check is currently being done in the analysis. It can be
1268 // enabled here only after the parser propagates attributes at
1269 // template specialization definition, not declaration.
1270 //QualType ReturnType;
1272 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1273 // ReturnType = Param->getType();
1275 //} else if (const CXXConstructorDecl *Constructor =
1276 // dyn_cast<CXXConstructorDecl>(D)) {
1277 // ReturnType = Constructor->getThisType()->getPointeeType();
1281 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1284 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1286 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1287 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1288 // ReturnType.getAsString();
1292 D->addAttr(::new (S.Context)
1293 ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState,
1294 AL.getAttributeSpellingListIndex()));
1297 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1298 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1301 SetTypestateAttr::ConsumedState NewState;
1302 if (AL.isArgIdent(0)) {
1303 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1304 StringRef Param = Ident->Ident->getName();
1305 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1306 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1311 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1312 << AL << AANT_ArgumentIdentifier;
1316 D->addAttr(::new (S.Context)
1317 SetTypestateAttr(AL.getRange(), S.Context, NewState,
1318 AL.getAttributeSpellingListIndex()));
1321 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1322 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1325 TestTypestateAttr::ConsumedState TestState;
1326 if (AL.isArgIdent(0)) {
1327 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1328 StringRef Param = Ident->Ident->getName();
1329 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1330 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1335 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1336 << AL << AANT_ArgumentIdentifier;
1340 D->addAttr(::new (S.Context)
1341 TestTypestateAttr(AL.getRange(), S.Context, TestState,
1342 AL.getAttributeSpellingListIndex()));
1345 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1346 // Remember this typedef decl, we will need it later for diagnostics.
1347 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1350 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1351 if (auto *TD = dyn_cast<TagDecl>(D))
1352 TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context,
1353 AL.getAttributeSpellingListIndex()));
1354 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1355 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1356 !FD->getType()->isIncompleteType() &&
1358 S.Context.getTypeAlign(FD->getType()) <= 8);
1360 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1361 if (BitfieldByteAligned)
1362 // The PS4 target needs to maintain ABI backwards compatibility.
1363 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1364 << AL << FD->getType();
1366 FD->addAttr(::new (S.Context) PackedAttr(
1367 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1369 // Report warning about changed offset in the newer compiler versions.
1370 if (BitfieldByteAligned)
1371 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1373 FD->addAttr(::new (S.Context) PackedAttr(
1374 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1378 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1381 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1382 // The IBOutlet/IBOutletCollection attributes only apply to instance
1383 // variables or properties of Objective-C classes. The outlet must also
1384 // have an object reference type.
1385 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1386 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1387 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1388 << AL << VD->getType() << 0;
1392 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1393 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1394 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1395 << AL << PD->getType() << 1;
1400 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1407 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1408 if (!checkIBOutletCommon(S, D, AL))
1411 D->addAttr(::new (S.Context)
1412 IBOutletAttr(AL.getRange(), S.Context,
1413 AL.getAttributeSpellingListIndex()));
1416 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1418 // The iboutletcollection attribute can have zero or one arguments.
1419 if (AL.getNumArgs() > 1) {
1420 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1424 if (!checkIBOutletCommon(S, D, AL))
1429 if (AL.hasParsedType())
1430 PT = AL.getTypeArg();
1432 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1433 S.getScopeForContext(D->getDeclContext()->getParent()));
1435 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1440 TypeSourceInfo *QTLoc = nullptr;
1441 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1443 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1445 // Diagnose use of non-object type in iboutletcollection attribute.
1446 // FIXME. Gnu attribute extension ignores use of builtin types in
1447 // attributes. So, __attribute__((iboutletcollection(char))) will be
1448 // treated as __attribute__((iboutletcollection())).
1449 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1451 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1452 : diag::err_iboutletcollection_type) << QT;
1456 D->addAttr(::new (S.Context)
1457 IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc,
1458 AL.getAttributeSpellingListIndex()));
1461 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1463 if (T->isReferenceType())
1466 T = T.getNonReferenceType();
1469 // The nonnull attribute, and other similar attributes, can be applied to a
1470 // transparent union that contains a pointer type.
1471 if (const RecordType *UT = T->getAsUnionType()) {
1472 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1473 RecordDecl *UD = UT->getDecl();
1474 for (const auto *I : UD->fields()) {
1475 QualType QT = I->getType();
1476 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1482 return T->isAnyPointerType() || T->isBlockPointerType();
1485 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1486 SourceRange AttrParmRange,
1487 SourceRange TypeRange,
1488 bool isReturnValue = false) {
1489 if (!S.isValidPointerAttrType(T)) {
1491 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1492 << AL << AttrParmRange << TypeRange;
1494 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1495 << AL << AttrParmRange << TypeRange << 0;
1501 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1502 SmallVector<ParamIdx, 8> NonNullArgs;
1503 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1504 Expr *Ex = AL.getArgAsExpr(I);
1506 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1509 // Is the function argument a pointer type?
1510 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1511 !attrNonNullArgCheck(
1512 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1513 Ex->getSourceRange(),
1514 getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1517 NonNullArgs.push_back(Idx);
1520 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1521 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1522 // check if the attribute came from a macro expansion or a template
1524 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1525 !S.inTemplateInstantiation()) {
1526 bool AnyPointers = isFunctionOrMethodVariadic(D);
1527 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1528 I != E && !AnyPointers; ++I) {
1529 QualType T = getFunctionOrMethodParamType(D, I);
1530 if (T->isDependentType() || S.isValidPointerAttrType(T))
1535 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1538 ParamIdx *Start = NonNullArgs.data();
1539 unsigned Size = NonNullArgs.size();
1540 llvm::array_pod_sort(Start, Start + Size);
1541 D->addAttr(::new (S.Context)
1542 NonNullAttr(AL.getRange(), S.Context, Start, Size,
1543 AL.getAttributeSpellingListIndex()));
1546 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1547 const ParsedAttr &AL) {
1548 if (AL.getNumArgs() > 0) {
1549 if (D->getFunctionType()) {
1550 handleNonNullAttr(S, D, AL);
1552 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1553 << D->getSourceRange();
1558 // Is the argument a pointer type?
1559 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1560 D->getSourceRange()))
1563 D->addAttr(::new (S.Context)
1564 NonNullAttr(AL.getRange(), S.Context, nullptr, 0,
1565 AL.getAttributeSpellingListIndex()));
1568 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1569 QualType ResultType = getFunctionOrMethodResultType(D);
1570 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1571 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1572 /* isReturnValue */ true))
1575 D->addAttr(::new (S.Context)
1576 ReturnsNonNullAttr(AL.getRange(), S.Context,
1577 AL.getAttributeSpellingListIndex()));
1580 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1581 if (D->isInvalidDecl())
1584 // noescape only applies to pointer types.
1585 QualType T = cast<ParmVarDecl>(D)->getType();
1586 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1587 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1588 << AL << AL.getRange() << 0;
1592 D->addAttr(::new (S.Context) NoEscapeAttr(
1593 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1596 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1597 Expr *E = AL.getArgAsExpr(0),
1598 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1599 S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE,
1600 AL.getAttributeSpellingListIndex());
1603 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1604 S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0),
1605 AL.getAttributeSpellingListIndex());
1608 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1609 Expr *OE, unsigned SpellingListIndex) {
1610 QualType ResultType = getFunctionOrMethodResultType(D);
1611 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1613 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1614 SourceLocation AttrLoc = AttrRange.getBegin();
1616 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1617 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1618 << &TmpAttr << AttrRange << SR;
1622 if (!E->isValueDependent()) {
1624 if (!E->isIntegerConstantExpr(I, Context)) {
1626 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1627 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1628 << E->getSourceRange();
1630 Diag(AttrLoc, diag::err_attribute_argument_type)
1631 << &TmpAttr << AANT_ArgumentIntegerConstant
1632 << E->getSourceRange();
1636 if (!I.isPowerOf2()) {
1637 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1638 << E->getSourceRange();
1644 if (!OE->isValueDependent()) {
1646 if (!OE->isIntegerConstantExpr(I, Context)) {
1647 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1648 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1649 << OE->getSourceRange();
1655 D->addAttr(::new (Context)
1656 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1659 void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1660 unsigned SpellingListIndex) {
1661 QualType ResultType = getFunctionOrMethodResultType(D);
1663 AllocAlignAttr TmpAttr(AttrRange, Context, ParamIdx(), SpellingListIndex);
1664 SourceLocation AttrLoc = AttrRange.getBegin();
1666 if (!ResultType->isDependentType() &&
1667 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1668 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1669 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1674 const auto *FuncDecl = cast<FunctionDecl>(D);
1675 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1676 /*AttrArgNum=*/1, ParamExpr, Idx))
1679 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1680 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1681 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1683 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1687 D->addAttr(::new (Context)
1688 AllocAlignAttr(AttrRange, Context, Idx, SpellingListIndex));
1691 /// Normalize the attribute, __foo__ becomes foo.
1692 /// Returns true if normalization was applied.
1693 static bool normalizeName(StringRef &AttrName) {
1694 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1695 AttrName.endswith("__")) {
1696 AttrName = AttrName.drop_front(2).drop_back(2);
1702 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1703 // This attribute must be applied to a function declaration. The first
1704 // argument to the attribute must be an identifier, the name of the resource,
1705 // for example: malloc. The following arguments must be argument indexes, the
1706 // arguments must be of integer type for Returns, otherwise of pointer type.
1707 // The difference between Holds and Takes is that a pointer may still be used
1708 // after being held. free() should be __attribute((ownership_takes)), whereas
1709 // a list append function may well be __attribute((ownership_holds)).
1711 if (!AL.isArgIdent(0)) {
1712 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1713 << AL << 1 << AANT_ArgumentIdentifier;
1717 // Figure out our Kind.
1718 OwnershipAttr::OwnershipKind K =
1719 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1720 AL.getAttributeSpellingListIndex()).getOwnKind();
1724 case OwnershipAttr::Takes:
1725 case OwnershipAttr::Holds:
1726 if (AL.getNumArgs() < 2) {
1727 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1731 case OwnershipAttr::Returns:
1732 if (AL.getNumArgs() > 2) {
1733 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1739 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1741 StringRef ModuleName = Module->getName();
1742 if (normalizeName(ModuleName)) {
1743 Module = &S.PP.getIdentifierTable().get(ModuleName);
1746 SmallVector<ParamIdx, 8> OwnershipArgs;
1747 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1748 Expr *Ex = AL.getArgAsExpr(i);
1750 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1753 // Is the function argument a pointer type?
1754 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1755 int Err = -1; // No error
1757 case OwnershipAttr::Takes:
1758 case OwnershipAttr::Holds:
1759 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1762 case OwnershipAttr::Returns:
1763 if (!T->isIntegerType())
1768 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1769 << Ex->getSourceRange();
1773 // Check we don't have a conflict with another ownership attribute.
1774 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1775 // Cannot have two ownership attributes of different kinds for the same
1777 if (I->getOwnKind() != K && I->args_end() !=
1778 std::find(I->args_begin(), I->args_end(), Idx)) {
1779 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1781 } else if (K == OwnershipAttr::Returns &&
1782 I->getOwnKind() == OwnershipAttr::Returns) {
1783 // A returns attribute conflicts with any other returns attribute using
1784 // a different index.
1785 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1786 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1787 << I->args_begin()->getSourceIndex();
1789 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1790 << Idx.getSourceIndex() << Ex->getSourceRange();
1795 OwnershipArgs.push_back(Idx);
1798 ParamIdx *Start = OwnershipArgs.data();
1799 unsigned Size = OwnershipArgs.size();
1800 llvm::array_pod_sort(Start, Start + Size);
1801 D->addAttr(::new (S.Context)
1802 OwnershipAttr(AL.getLoc(), S.Context, Module, Start, Size,
1803 AL.getAttributeSpellingListIndex()));
1806 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1807 // Check the attribute arguments.
1808 if (AL.getNumArgs() > 1) {
1809 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1815 // static int a __attribute__((weakref ("v2")));
1816 // static int b() __attribute__((weakref ("f3")));
1818 // and ignores the attributes of
1820 // static int a __attribute__((weakref ("v2")));
1823 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1824 if (!Ctx->isFileContext()) {
1825 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1826 << cast<NamedDecl>(D);
1830 // The GCC manual says
1832 // At present, a declaration to which `weakref' is attached can only
1837 // Without a TARGET,
1838 // given as an argument to `weakref' or to `alias', `weakref' is
1839 // equivalent to `weak'.
1841 // gcc 4.4.1 will accept
1842 // int a7 __attribute__((weakref));
1844 // int a7 __attribute__((weak));
1845 // This looks like a bug in gcc. We reject that for now. We should revisit
1846 // it if this behaviour is actually used.
1849 // static ((alias ("y"), weakref)).
1850 // Should we? How to check that weakref is before or after alias?
1852 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1853 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1854 // StringRef parameter it was given anyway.
1856 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1857 // GCC will accept anything as the argument of weakref. Should we
1858 // check for an existing decl?
1859 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1860 AL.getAttributeSpellingListIndex()));
1862 D->addAttr(::new (S.Context)
1863 WeakRefAttr(AL.getRange(), S.Context,
1864 AL.getAttributeSpellingListIndex()));
1867 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1869 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1872 // Aliases should be on declarations, not definitions.
1873 const auto *FD = cast<FunctionDecl>(D);
1874 if (FD->isThisDeclarationADefinition()) {
1875 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1879 D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str,
1880 AL.getAttributeSpellingListIndex()));
1883 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1885 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1888 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1889 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1892 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1893 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1896 // Aliases should be on declarations, not definitions.
1897 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1898 if (FD->isThisDeclarationADefinition()) {
1899 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1903 const auto *VD = cast<VarDecl>(D);
1904 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1905 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1910 // Mark target used to prevent unneeded-internal-declaration warnings.
1911 if (!S.LangOpts.CPlusPlus) {
1912 // FIXME: demangle Str for C++, as the attribute refers to the mangled
1913 // linkage name, not the pre-mangled identifier.
1914 const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1915 LookupResult LR(S, target, Sema::LookupOrdinaryName);
1916 if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
1917 for (NamedDecl *ND : LR)
1918 ND->markUsed(S.Context);
1921 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1922 AL.getAttributeSpellingListIndex()));
1925 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1927 SourceLocation LiteralLoc;
1928 // Check that it is a string.
1929 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1932 // Check that the value.
1933 if (Model != "global-dynamic" && Model != "local-dynamic"
1934 && Model != "initial-exec" && Model != "local-exec") {
1935 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1939 D->addAttr(::new (S.Context)
1940 TLSModelAttr(AL.getRange(), S.Context, Model,
1941 AL.getAttributeSpellingListIndex()));
1944 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1945 QualType ResultType = getFunctionOrMethodResultType(D);
1946 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1947 D->addAttr(::new (S.Context) RestrictAttr(
1948 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1952 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1953 << AL << getFunctionOrMethodResultSourceRange(D);
1956 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1957 FunctionDecl *FD = cast<FunctionDecl>(D);
1959 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1960 if (MD->getParent()->isLambda()) {
1961 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1966 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1969 SmallVector<IdentifierInfo *, 8> CPUs;
1970 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1971 if (!AL.isArgIdent(ArgNo)) {
1972 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1973 << AL << AANT_ArgumentIdentifier;
1977 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1978 StringRef CPUName = CPUArg->Ident->getName().trim();
1980 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
1981 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1982 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1986 const TargetInfo &Target = S.Context.getTargetInfo();
1987 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1988 return Target.CPUSpecificManglingCharacter(CPUName) ==
1989 Target.CPUSpecificManglingCharacter(Cur->getName());
1991 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1994 CPUs.push_back(CPUArg->Ident);
1997 FD->setIsMultiVersion(true);
1998 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1999 D->addAttr(::new (S.Context) CPUSpecificAttr(
2000 AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2001 AL.getAttributeSpellingListIndex()));
2003 D->addAttr(::new (S.Context) CPUDispatchAttr(
2004 AL.getRange(), S.Context, CPUs.data(), CPUs.size(),
2005 AL.getAttributeSpellingListIndex()));
2008 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2009 if (S.LangOpts.CPlusPlus) {
2010 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2011 << AL << AttributeLangSupport::Cpp;
2015 if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
2019 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2020 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
2023 if (AL.isDeclspecAttribute()) {
2024 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2025 const auto &Arch = Triple.getArch();
2026 if (Arch != llvm::Triple::x86 &&
2027 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2028 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2029 << AL << Triple.getArchName();
2034 D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context,
2035 AL.getAttributeSpellingListIndex()));
2038 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2039 if (hasDeclarator(D)) return;
2041 if (!isa<ObjCMethodDecl>(D)) {
2042 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2043 << Attrs << ExpectedFunctionOrMethod;
2047 D->addAttr(::new (S.Context) NoReturnAttr(
2048 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
2051 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2052 if (!S.getLangOpts().CFProtectionBranch)
2053 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2055 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2058 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2059 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
2067 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2068 // Check whether the attribute is valid on the current target.
2069 if (!AL.existsInTarget(Context.getTargetInfo())) {
2070 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
2078 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2080 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2081 // because 'analyzer_noreturn' does not impact the type.
2082 if (!isFunctionOrMethodOrBlock(D)) {
2083 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2084 if (!VD || (!VD->getType()->isBlockPointerType() &&
2085 !VD->getType()->isFunctionPointerType())) {
2086 S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2087 ? diag::err_attribute_wrong_decl_type
2088 : diag::warn_attribute_wrong_decl_type)
2089 << AL << ExpectedFunctionMethodOrBlock;
2094 D->addAttr(::new (S.Context)
2095 AnalyzerNoReturnAttr(AL.getRange(), S.Context,
2096 AL.getAttributeSpellingListIndex()));
2099 // PS3 PPU-specific.
2100 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2102 Returning a Vector Class in Registers
2104 According to the PPU ABI specifications, a class with a single member of
2105 vector type is returned in memory when used as the return value of a
2107 This results in inefficient code when implementing vector classes. To return
2108 the value in a single vector register, add the vecreturn attribute to the
2109 class definition. This attribute is also applicable to struct types.
2115 __vector float xyzw;
2116 } __attribute__((vecreturn));
2118 Vector Add(Vector lhs, Vector rhs)
2121 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2122 return result; // This will be returned in a register
2125 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2126 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2130 const auto *R = cast<RecordDecl>(D);
2133 if (!isa<CXXRecordDecl>(R)) {
2134 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2138 if (!cast<CXXRecordDecl>(R)->isPOD()) {
2139 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2143 for (const auto *I : R->fields()) {
2144 if ((count == 1) || !I->getType()->isVectorType()) {
2145 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2151 D->addAttr(::new (S.Context) VecReturnAttr(
2152 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
2155 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2156 const ParsedAttr &AL) {
2157 if (isa<ParmVarDecl>(D)) {
2158 // [[carries_dependency]] can only be applied to a parameter if it is a
2159 // parameter of a function declaration or lambda.
2160 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2162 diag::err_carries_dependency_param_not_function_decl);
2167 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2168 AL.getRange(), S.Context,
2169 AL.getAttributeSpellingListIndex()));
2172 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2173 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2175 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2176 // about using it as an extension.
2177 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2178 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2180 D->addAttr(::new (S.Context) UnusedAttr(
2181 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
2184 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2185 uint32_t priority = ConstructorAttr::DefaultPriority;
2186 if (AL.getNumArgs() &&
2187 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2190 D->addAttr(::new (S.Context)
2191 ConstructorAttr(AL.getRange(), S.Context, priority,
2192 AL.getAttributeSpellingListIndex()));
2195 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2196 uint32_t priority = DestructorAttr::DefaultPriority;
2197 if (AL.getNumArgs() &&
2198 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2201 D->addAttr(::new (S.Context)
2202 DestructorAttr(AL.getRange(), S.Context, priority,
2203 AL.getAttributeSpellingListIndex()));
2206 template <typename AttrTy>
2207 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2208 // Handle the case where the attribute has a text message.
2210 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2213 D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str,
2214 AL.getAttributeSpellingListIndex()));
2217 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2218 const ParsedAttr &AL) {
2219 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2220 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2221 << AL << AL.getRange();
2225 D->addAttr(::new (S.Context)
2226 ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context,
2227 AL.getAttributeSpellingListIndex()));
2230 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2231 IdentifierInfo *Platform,
2232 VersionTuple Introduced,
2233 VersionTuple Deprecated,
2234 VersionTuple Obsoleted) {
2235 StringRef PlatformName
2236 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2237 if (PlatformName.empty())
2238 PlatformName = Platform->getName();
2240 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2241 // of these steps are needed).
2242 if (!Introduced.empty() && !Deprecated.empty() &&
2243 !(Introduced <= Deprecated)) {
2244 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2245 << 1 << PlatformName << Deprecated.getAsString()
2246 << 0 << Introduced.getAsString();
2250 if (!Introduced.empty() && !Obsoleted.empty() &&
2251 !(Introduced <= Obsoleted)) {
2252 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2253 << 2 << PlatformName << Obsoleted.getAsString()
2254 << 0 << Introduced.getAsString();
2258 if (!Deprecated.empty() && !Obsoleted.empty() &&
2259 !(Deprecated <= Obsoleted)) {
2260 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2261 << 2 << PlatformName << Obsoleted.getAsString()
2262 << 1 << Deprecated.getAsString();
2269 /// Check whether the two versions match.
2271 /// If either version tuple is empty, then they are assumed to match. If
2272 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2273 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2274 bool BeforeIsOkay) {
2275 if (X.empty() || Y.empty())
2281 if (BeforeIsOkay && X < Y)
2287 AvailabilityAttr *Sema::mergeAvailabilityAttr(
2288 NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit,
2289 VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted,
2290 bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement,
2291 AvailabilityMergeKind AMK, int Priority, unsigned AttrSpellingListIndex) {
2292 VersionTuple MergedIntroduced = Introduced;
2293 VersionTuple MergedDeprecated = Deprecated;
2294 VersionTuple MergedObsoleted = Obsoleted;
2295 bool FoundAny = false;
2296 bool OverrideOrImpl = false;
2299 case AMK_Redeclaration:
2300 OverrideOrImpl = false;
2304 case AMK_ProtocolImplementation:
2305 OverrideOrImpl = true;
2309 if (D->hasAttrs()) {
2310 AttrVec &Attrs = D->getAttrs();
2311 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2312 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2318 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2319 if (OldPlatform != Platform) {
2324 // If there is an existing availability attribute for this platform that
2325 // has a lower priority use the existing one and discard the new
2327 if (OldAA->getPriority() < Priority)
2330 // If there is an existing attribute for this platform that has a higher
2331 // priority than the new attribute then erase the old one and continue
2332 // processing the attributes.
2333 if (OldAA->getPriority() > Priority) {
2334 Attrs.erase(Attrs.begin() + i);
2340 VersionTuple OldIntroduced = OldAA->getIntroduced();
2341 VersionTuple OldDeprecated = OldAA->getDeprecated();
2342 VersionTuple OldObsoleted = OldAA->getObsoleted();
2343 bool OldIsUnavailable = OldAA->getUnavailable();
2345 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2346 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2347 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2348 !(OldIsUnavailable == IsUnavailable ||
2349 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2350 if (OverrideOrImpl) {
2352 VersionTuple FirstVersion;
2353 VersionTuple SecondVersion;
2354 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2356 FirstVersion = OldIntroduced;
2357 SecondVersion = Introduced;
2358 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2360 FirstVersion = Deprecated;
2361 SecondVersion = OldDeprecated;
2362 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2364 FirstVersion = Obsoleted;
2365 SecondVersion = OldObsoleted;
2369 Diag(OldAA->getLocation(),
2370 diag::warn_mismatched_availability_override_unavail)
2371 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2372 << (AMK == AMK_Override);
2374 Diag(OldAA->getLocation(),
2375 diag::warn_mismatched_availability_override)
2377 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2378 << FirstVersion.getAsString() << SecondVersion.getAsString()
2379 << (AMK == AMK_Override);
2381 if (AMK == AMK_Override)
2382 Diag(Range.getBegin(), diag::note_overridden_method);
2384 Diag(Range.getBegin(), diag::note_protocol_method);
2386 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2387 Diag(Range.getBegin(), diag::note_previous_attribute);
2390 Attrs.erase(Attrs.begin() + i);
2395 VersionTuple MergedIntroduced2 = MergedIntroduced;
2396 VersionTuple MergedDeprecated2 = MergedDeprecated;
2397 VersionTuple MergedObsoleted2 = MergedObsoleted;
2399 if (MergedIntroduced2.empty())
2400 MergedIntroduced2 = OldIntroduced;
2401 if (MergedDeprecated2.empty())
2402 MergedDeprecated2 = OldDeprecated;
2403 if (MergedObsoleted2.empty())
2404 MergedObsoleted2 = OldObsoleted;
2406 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2407 MergedIntroduced2, MergedDeprecated2,
2408 MergedObsoleted2)) {
2409 Attrs.erase(Attrs.begin() + i);
2414 MergedIntroduced = MergedIntroduced2;
2415 MergedDeprecated = MergedDeprecated2;
2416 MergedObsoleted = MergedObsoleted2;
2422 MergedIntroduced == Introduced &&
2423 MergedDeprecated == Deprecated &&
2424 MergedObsoleted == Obsoleted)
2427 // Only create a new attribute if !OverrideOrImpl, but we want to do
2429 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2430 MergedDeprecated, MergedObsoleted) &&
2432 auto *Avail = ::new (Context)
2433 AvailabilityAttr(Range, Context, Platform, Introduced, Deprecated,
2434 Obsoleted, IsUnavailable, Message, IsStrict,
2435 Replacement, Priority, AttrSpellingListIndex);
2436 Avail->setImplicit(Implicit);
2442 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2443 if (!checkAttributeNumArgs(S, AL, 1))
2445 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2446 unsigned Index = AL.getAttributeSpellingListIndex();
2448 IdentifierInfo *II = Platform->Ident;
2449 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2450 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2453 auto *ND = dyn_cast<NamedDecl>(D);
2454 if (!ND) // We warned about this already, so just return.
2457 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2458 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2459 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2460 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2461 bool IsStrict = AL.getStrictLoc().isValid();
2463 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2464 Str = SE->getString();
2465 StringRef Replacement;
2466 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2467 Replacement = SE->getString();
2469 if (II->isStr("swift")) {
2470 if (Introduced.isValid() || Obsoleted.isValid() ||
2471 (!IsUnavailable && !Deprecated.isValid())) {
2473 diag::warn_availability_swift_unavailable_deprecated_only);
2478 int PriorityModifier = AL.isPragmaClangAttribute()
2479 ? Sema::AP_PragmaClangAttribute
2480 : Sema::AP_Explicit;
2481 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2482 ND, AL.getRange(), II, false /*Implicit*/, Introduced.Version,
2483 Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2484 Replacement, Sema::AMK_None, PriorityModifier, Index);
2486 D->addAttr(NewAttr);
2488 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2489 // matches before the start of the watchOS platform.
2490 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2491 IdentifierInfo *NewII = nullptr;
2492 if (II->getName() == "ios")
2493 NewII = &S.Context.Idents.get("watchos");
2494 else if (II->getName() == "ios_app_extension")
2495 NewII = &S.Context.Idents.get("watchos_app_extension");
2498 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2499 if (Version.empty())
2501 auto Major = Version.getMajor();
2502 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2503 if (NewMajor >= 2) {
2504 if (Version.getMinor().hasValue()) {
2505 if (Version.getSubminor().hasValue())
2506 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2507 Version.getSubminor().getValue());
2509 return VersionTuple(NewMajor, Version.getMinor().getValue());
2511 return VersionTuple(NewMajor);
2514 return VersionTuple(2, 0);
2517 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2518 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2519 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2521 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2522 ND, AL.getRange(), NewII, true /*Implicit*/, NewIntroduced,
2523 NewDeprecated, NewObsoleted, IsUnavailable, Str, IsStrict,
2524 Replacement, Sema::AMK_None,
2525 PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index);
2527 D->addAttr(NewAttr);
2529 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2530 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2531 // matches before the start of the tvOS platform.
2532 IdentifierInfo *NewII = nullptr;
2533 if (II->getName() == "ios")
2534 NewII = &S.Context.Idents.get("tvos");
2535 else if (II->getName() == "ios_app_extension")
2536 NewII = &S.Context.Idents.get("tvos_app_extension");
2539 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2540 ND, AL.getRange(), NewII, true /*Implicit*/, Introduced.Version,
2541 Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2542 Replacement, Sema::AMK_None,
2543 PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index);
2545 D->addAttr(NewAttr);
2550 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2551 const ParsedAttr &AL) {
2552 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2554 assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2555 "Invalid number of arguments in an external_source_symbol attribute");
2558 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2559 Language = SE->getString();
2560 StringRef DefinedIn;
2561 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2562 DefinedIn = SE->getString();
2563 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2565 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2566 AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2567 AL.getAttributeSpellingListIndex()));
2571 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2572 typename T::VisibilityType value,
2573 unsigned attrSpellingListIndex) {
2574 T *existingAttr = D->getAttr<T>();
2576 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2577 if (existingValue == value)
2579 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2580 S.Diag(range.getBegin(), diag::note_previous_attribute);
2583 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2586 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2587 VisibilityAttr::VisibilityType Vis,
2588 unsigned AttrSpellingListIndex) {
2589 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2590 AttrSpellingListIndex);
2593 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2594 TypeVisibilityAttr::VisibilityType Vis,
2595 unsigned AttrSpellingListIndex) {
2596 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2597 AttrSpellingListIndex);
2600 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2601 bool isTypeVisibility) {
2602 // Visibility attributes don't mean anything on a typedef.
2603 if (isa<TypedefNameDecl>(D)) {
2604 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2608 // 'type_visibility' can only go on a type or namespace.
2609 if (isTypeVisibility &&
2610 !(isa<TagDecl>(D) ||
2611 isa<ObjCInterfaceDecl>(D) ||
2612 isa<NamespaceDecl>(D))) {
2613 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2614 << AL << ExpectedTypeOrNamespace;
2618 // Check that the argument is a string literal.
2620 SourceLocation LiteralLoc;
2621 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2624 VisibilityAttr::VisibilityType type;
2625 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2626 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2631 // Complain about attempts to use protected visibility on targets
2632 // (like Darwin) that don't support it.
2633 if (type == VisibilityAttr::Protected &&
2634 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2635 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2636 type = VisibilityAttr::Default;
2639 unsigned Index = AL.getAttributeSpellingListIndex();
2641 if (isTypeVisibility) {
2642 newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(),
2643 (TypeVisibilityAttr::VisibilityType) type,
2646 newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index);
2649 D->addAttr(newAttr);
2652 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2653 const auto *M = cast<ObjCMethodDecl>(D);
2654 if (!AL.isArgIdent(0)) {
2655 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2656 << AL << 1 << AANT_ArgumentIdentifier;
2660 IdentifierLoc *IL = AL.getArgAsIdent(0);
2661 ObjCMethodFamilyAttr::FamilyKind F;
2662 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2663 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2667 if (F == ObjCMethodFamilyAttr::OMF_init &&
2668 !M->getReturnType()->isObjCObjectPointerType()) {
2669 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2670 << M->getReturnType();
2671 // Ignore the attribute.
2675 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(
2676 AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex()));
2679 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2680 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2681 QualType T = TD->getUnderlyingType();
2682 if (!T->isCARCBridgableType()) {
2683 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2687 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2688 QualType T = PD->getType();
2689 if (!T->isCARCBridgableType()) {
2690 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2695 // It is okay to include this attribute on properties, e.g.:
2697 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2699 // In this case it follows tradition and suppresses an error in the above
2701 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2703 D->addAttr(::new (S.Context)
2704 ObjCNSObjectAttr(AL.getRange(), S.Context,
2705 AL.getAttributeSpellingListIndex()));
2708 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2709 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2710 QualType T = TD->getUnderlyingType();
2711 if (!T->isObjCObjectPointerType()) {
2712 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2716 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2719 D->addAttr(::new (S.Context)
2720 ObjCIndependentClassAttr(AL.getRange(), S.Context,
2721 AL.getAttributeSpellingListIndex()));
2724 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2725 if (!AL.isArgIdent(0)) {
2726 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2727 << AL << 1 << AANT_ArgumentIdentifier;
2731 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2732 BlocksAttr::BlockType type;
2733 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2734 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2738 D->addAttr(::new (S.Context)
2739 BlocksAttr(AL.getRange(), S.Context, type,
2740 AL.getAttributeSpellingListIndex()));
2743 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2744 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2745 if (AL.getNumArgs() > 0) {
2746 Expr *E = AL.getArgAsExpr(0);
2747 llvm::APSInt Idx(32);
2748 if (E->isTypeDependent() || E->isValueDependent() ||
2749 !E->isIntegerConstantExpr(Idx, S.Context)) {
2750 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2751 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2755 if (Idx.isSigned() && Idx.isNegative()) {
2756 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2757 << E->getSourceRange();
2761 sentinel = Idx.getZExtValue();
2764 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2765 if (AL.getNumArgs() > 1) {
2766 Expr *E = AL.getArgAsExpr(1);
2767 llvm::APSInt Idx(32);
2768 if (E->isTypeDependent() || E->isValueDependent() ||
2769 !E->isIntegerConstantExpr(Idx, S.Context)) {
2770 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2771 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2774 nullPos = Idx.getZExtValue();
2776 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2777 // FIXME: This error message could be improved, it would be nice
2778 // to say what the bounds actually are.
2779 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2780 << E->getSourceRange();
2785 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2786 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2787 if (isa<FunctionNoProtoType>(FT)) {
2788 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2792 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2793 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2796 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2797 if (!MD->isVariadic()) {
2798 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2801 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2802 if (!BD->isVariadic()) {
2803 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2806 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2807 QualType Ty = V->getType();
2808 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2809 const FunctionType *FT = Ty->isFunctionPointerType()
2810 ? D->getFunctionType()
2811 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2812 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2813 int m = Ty->isFunctionPointerType() ? 0 : 1;
2814 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2818 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2819 << AL << ExpectedFunctionMethodOrBlock;
2823 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2824 << AL << ExpectedFunctionMethodOrBlock;
2827 D->addAttr(::new (S.Context)
2828 SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos,
2829 AL.getAttributeSpellingListIndex()));
2832 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2833 if (D->getFunctionType() &&
2834 D->getFunctionType()->getReturnType()->isVoidType()) {
2835 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2838 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2839 if (MD->getReturnType()->isVoidType()) {
2840 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2844 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2845 // about using it as an extension.
2846 if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() &&
2848 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2850 D->addAttr(::new (S.Context)
2851 WarnUnusedResultAttr(AL.getRange(), S.Context,
2852 AL.getAttributeSpellingListIndex()));
2855 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2856 // weak_import only applies to variable & function declarations.
2858 if (!D->canBeWeakImported(isDef)) {
2860 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2862 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2863 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2864 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2865 // Nothing to warn about here.
2867 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2868 << AL << ExpectedVariableOrFunction;
2873 D->addAttr(::new (S.Context)
2874 WeakImportAttr(AL.getRange(), S.Context,
2875 AL.getAttributeSpellingListIndex()));
2878 // Handles reqd_work_group_size and work_group_size_hint.
2879 template <typename WorkGroupAttr>
2880 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2882 for (unsigned i = 0; i < 3; ++i) {
2883 const Expr *E = AL.getArgAsExpr(i);
2884 if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2885 /*StrictlyUnsigned=*/true))
2887 if (WGSize[i] == 0) {
2888 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2889 << AL << E->getSourceRange();
2894 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2895 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2896 Existing->getYDim() == WGSize[1] &&
2897 Existing->getZDim() == WGSize[2]))
2898 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2900 D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context,
2901 WGSize[0], WGSize[1], WGSize[2],
2902 AL.getAttributeSpellingListIndex()));
2905 // Handles intel_reqd_sub_group_size.
2906 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2908 const Expr *E = AL.getArgAsExpr(0);
2909 if (!checkUInt32Argument(S, AL, E, SGSize))
2912 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2913 << AL << E->getSourceRange();
2917 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2918 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2919 if (Existing && Existing->getSubGroupSize() != SGSize)
2920 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2922 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2923 AL.getRange(), S.Context, SGSize,
2924 AL.getAttributeSpellingListIndex()));
2927 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2928 if (!AL.hasParsedType()) {
2929 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2933 TypeSourceInfo *ParmTSI = nullptr;
2934 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2935 assert(ParmTSI && "no type source info for attribute argument");
2937 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2938 (ParmType->isBooleanType() ||
2939 !ParmType->isIntegralType(S.getASTContext()))) {
2940 S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint)
2945 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2946 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2947 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2952 D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context,
2954 AL.getAttributeSpellingListIndex()));
2957 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2959 unsigned AttrSpellingListIndex) {
2960 // Explicit or partial specializations do not inherit
2961 // the section attribute from the primary template.
2962 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2963 if (AttrSpellingListIndex == SectionAttr::Declspec_allocate &&
2964 FD->isFunctionTemplateSpecialization())
2967 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2968 if (ExistingAttr->getName() == Name)
2970 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2972 Diag(Range.getBegin(), diag::note_previous_attribute);
2975 return ::new (Context) SectionAttr(Range, Context, Name,
2976 AttrSpellingListIndex);
2979 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2980 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2981 if (!Error.empty()) {
2982 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
2989 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2990 // Make sure that there is a string literal as the sections's single
2993 SourceLocation LiteralLoc;
2994 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2997 if (!S.checkSectionName(LiteralLoc, Str))
3000 // If the target wants to validate the section specifier, make it happen.
3001 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3002 if (!Error.empty()) {
3003 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3008 unsigned Index = AL.getAttributeSpellingListIndex();
3009 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index);
3011 D->addAttr(NewAttr);
3014 // This is used for `__declspec(code_seg("segname"))` on a decl.
3015 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3016 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3017 StringRef CodeSegName) {
3019 S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
3020 if (!Error.empty()) {
3021 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3022 << Error << 0 /*'code-seg'*/;
3029 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range,
3031 unsigned AttrSpellingListIndex) {
3032 // Explicit or partial specializations do not inherit
3033 // the code_seg attribute from the primary template.
3034 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3035 if (FD->isFunctionTemplateSpecialization())
3038 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3039 if (ExistingAttr->getName() == Name)
3041 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3043 Diag(Range.getBegin(), diag::note_previous_attribute);
3046 return ::new (Context) CodeSegAttr(Range, Context, Name,
3047 AttrSpellingListIndex);
3050 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3052 SourceLocation LiteralLoc;
3053 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3055 if (!checkCodeSegName(S, LiteralLoc, Str))
3057 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3058 if (!ExistingAttr->isImplicit()) {
3060 ExistingAttr->getName() == Str
3061 ? diag::warn_duplicate_codeseg_attribute
3062 : diag::err_conflicting_codeseg_attribute);
3065 D->dropAttr<CodeSegAttr>();
3067 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str,
3068 AL.getAttributeSpellingListIndex()))
3072 // Check for things we'd like to warn about. Multiversioning issues are
3073 // handled later in the process, once we know how many exist.
3074 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3075 enum FirstParam { Unsupported, Duplicate };
3076 enum SecondParam { None, Architecture };
3077 for (auto Str : {"tune=", "fpmath="})
3078 if (AttrStr.find(Str) != StringRef::npos)
3079 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3080 << Unsupported << None << Str;
3082 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3084 if (!ParsedAttrs.Architecture.empty() &&
3085 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3086 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3087 << Unsupported << Architecture << ParsedAttrs.Architecture;
3089 if (ParsedAttrs.DuplicateArchitecture)
3090 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3091 << Duplicate << None << "arch=";
3093 for (const auto &Feature : ParsedAttrs.Features) {
3094 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3095 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3096 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3097 << Unsupported << None << CurFeature;
3103 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3105 SourceLocation LiteralLoc;
3106 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3107 S.checkTargetAttr(LiteralLoc, Str))
3110 unsigned Index = AL.getAttributeSpellingListIndex();
3111 TargetAttr *NewAttr =
3112 ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index);
3113 D->addAttr(NewAttr);
3116 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3117 Expr *E = AL.getArgAsExpr(0);
3119 if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3124 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3125 if (Existing && Existing->getVectorWidth() != VecWidth) {
3126 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3130 D->addAttr(::new (S.Context)
3131 MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth,
3132 AL.getAttributeSpellingListIndex()));
3135 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3136 Expr *E = AL.getArgAsExpr(0);
3137 SourceLocation Loc = E->getExprLoc();
3138 FunctionDecl *FD = nullptr;
3139 DeclarationNameInfo NI;
3141 // gcc only allows for simple identifiers. Since we support more than gcc, we
3142 // will warn the user.
3143 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3144 if (DRE->hasQualifier())
3145 S.Diag(Loc, diag::warn_cleanup_ext);
3146 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3147 NI = DRE->getNameInfo();
3149 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3153 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3154 if (ULE->hasExplicitTemplateArgs())
3155 S.Diag(Loc, diag::warn_cleanup_ext);
3156 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3157 NI = ULE->getNameInfo();
3159 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3161 if (ULE->getType() == S.Context.OverloadTy)
3162 S.NoteAllOverloadCandidates(ULE);
3166 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3170 if (FD->getNumParams() != 1) {
3171 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3176 // We're currently more strict than GCC about what function types we accept.
3177 // If this ever proves to be a problem it should be easy to fix.
3178 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3179 QualType ParamTy = FD->getParamDecl(0)->getType();
3180 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3181 ParamTy, Ty) != Sema::Compatible) {
3182 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3183 << NI.getName() << ParamTy << Ty;
3187 D->addAttr(::new (S.Context)
3188 CleanupAttr(AL.getRange(), S.Context, FD,
3189 AL.getAttributeSpellingListIndex()));
3192 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3193 const ParsedAttr &AL) {
3194 if (!AL.isArgIdent(0)) {
3195 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3196 << AL << 0 << AANT_ArgumentIdentifier;
3200 EnumExtensibilityAttr::Kind ExtensibilityKind;
3201 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3202 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3203 ExtensibilityKind)) {
3204 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3208 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3209 AL.getRange(), S.Context, ExtensibilityKind,
3210 AL.getAttributeSpellingListIndex()));
3213 /// Handle __attribute__((format_arg((idx)))) attribute based on
3214 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3215 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3216 Expr *IdxExpr = AL.getArgAsExpr(0);
3218 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3221 // Make sure the format string is really a string.
3222 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3224 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3225 if (NotNSStringTy &&
3226 !isCFStringType(Ty, S.Context) &&
3227 (!Ty->isPointerType() ||
3228 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3229 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3230 << "a string type" << IdxExpr->getSourceRange()
3231 << getFunctionOrMethodParamRange(D, 0);
3234 Ty = getFunctionOrMethodResultType(D);
3235 if (!isNSStringType(Ty, S.Context) &&
3236 !isCFStringType(Ty, S.Context) &&
3237 (!Ty->isPointerType() ||
3238 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3239 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3240 << (NotNSStringTy ? "string type" : "NSString")
3241 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3245 D->addAttr(::new (S.Context) FormatArgAttr(
3246 AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex()));
3249 enum FormatAttrKind {
3258 /// getFormatAttrKind - Map from format attribute names to supported format
3260 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3261 return llvm::StringSwitch<FormatAttrKind>(Format)
3262 // Check for formats that get handled specially.
3263 .Case("NSString", NSStringFormat)
3264 .Case("CFString", CFStringFormat)
3265 .Case("strftime", StrftimeFormat)
3267 // Otherwise, check for supported formats.
3268 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3269 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3270 .Case("kprintf", SupportedFormat) // OpenBSD.
3271 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3272 .Case("os_trace", SupportedFormat)
3273 .Case("os_log", SupportedFormat)
3275 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3276 .Default(InvalidFormat);
3279 /// Handle __attribute__((init_priority(priority))) attributes based on
3280 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3281 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3282 if (!S.getLangOpts().CPlusPlus) {
3283 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3287 if (S.getCurFunctionOrMethodDecl()) {
3288 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3292 QualType T = cast<VarDecl>(D)->getType();
3293 if (S.Context.getAsArrayType(T))
3294 T = S.Context.getBaseElementType(T);
3295 if (!T->getAs<RecordType>()) {
3296 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3301 Expr *E = AL.getArgAsExpr(0);
3302 uint32_t prioritynum;
3303 if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3308 if (prioritynum < 101 || prioritynum > 65535) {
3309 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3310 << E->getSourceRange() << AL << 101 << 65535;
3314 D->addAttr(::new (S.Context)
3315 InitPriorityAttr(AL.getRange(), S.Context, prioritynum,
3316 AL.getAttributeSpellingListIndex()));
3319 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3320 IdentifierInfo *Format, int FormatIdx,
3322 unsigned AttrSpellingListIndex) {
3323 // Check whether we already have an equivalent format attribute.
3324 for (auto *F : D->specific_attrs<FormatAttr>()) {
3325 if (F->getType() == Format &&
3326 F->getFormatIdx() == FormatIdx &&
3327 F->getFirstArg() == FirstArg) {
3328 // If we don't have a valid location for this attribute, adopt the
3330 if (F->getLocation().isInvalid())
3336 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3337 FirstArg, AttrSpellingListIndex);
3340 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3341 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3342 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3343 if (!AL.isArgIdent(0)) {
3344 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3345 << AL << 1 << AANT_ArgumentIdentifier;
3349 // In C++ the implicit 'this' function parameter also counts, and they are
3350 // counted from one.
3351 bool HasImplicitThisParam = isInstanceMethod(D);
3352 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3354 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3355 StringRef Format = II->getName();
3357 if (normalizeName(Format)) {
3358 // If we've modified the string name, we need a new identifier for it.
3359 II = &S.Context.Idents.get(Format);
3362 // Check for supported formats.
3363 FormatAttrKind Kind = getFormatAttrKind(Format);
3365 if (Kind == IgnoredFormat)
3368 if (Kind == InvalidFormat) {
3369 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3370 << AL << II->getName();
3374 // checks for the 2nd argument
3375 Expr *IdxExpr = AL.getArgAsExpr(1);
3377 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3380 if (Idx < 1 || Idx > NumArgs) {
3381 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3382 << AL << 2 << IdxExpr->getSourceRange();
3386 // FIXME: Do we need to bounds check?
3387 unsigned ArgIdx = Idx - 1;
3389 if (HasImplicitThisParam) {
3392 diag::err_format_attribute_implicit_this_format_string)
3393 << IdxExpr->getSourceRange();
3399 // make sure the format string is really a string
3400 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3402 if (Kind == CFStringFormat) {
3403 if (!isCFStringType(Ty, S.Context)) {
3404 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3405 << "a CFString" << IdxExpr->getSourceRange()
3406 << getFunctionOrMethodParamRange(D, ArgIdx);
3409 } else if (Kind == NSStringFormat) {
3410 // FIXME: do we need to check if the type is NSString*? What are the
3412 if (!isNSStringType(Ty, S.Context)) {
3413 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3414 << "an NSString" << IdxExpr->getSourceRange()
3415 << getFunctionOrMethodParamRange(D, ArgIdx);
3418 } else if (!Ty->isPointerType() ||
3419 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3420 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3421 << "a string type" << IdxExpr->getSourceRange()
3422 << getFunctionOrMethodParamRange(D, ArgIdx);
3426 // check the 3rd argument
3427 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3429 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3432 // check if the function is variadic if the 3rd argument non-zero
3433 if (FirstArg != 0) {
3434 if (isFunctionOrMethodVariadic(D)) {
3435 ++NumArgs; // +1 for ...
3437 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3442 // strftime requires FirstArg to be 0 because it doesn't read from any
3443 // variable the input is just the current time + the format string.
3444 if (Kind == StrftimeFormat) {
3445 if (FirstArg != 0) {
3446 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3447 << FirstArgExpr->getSourceRange();
3450 // if 0 it disables parameter checking (to use with e.g. va_list)
3451 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3452 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3453 << AL << 3 << FirstArgExpr->getSourceRange();
3457 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II,
3459 AL.getAttributeSpellingListIndex());
3461 D->addAttr(NewAttr);
3464 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3465 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3466 // The index that identifies the callback callee is mandatory.
3467 if (AL.getNumArgs() == 0) {
3468 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3473 bool HasImplicitThisParam = isInstanceMethod(D);
3474 int32_t NumArgs = getFunctionOrMethodNumParams(D);
3476 FunctionDecl *FD = D->getAsFunction();
3477 assert(FD && "Expected a function declaration!");
3479 llvm::StringMap<int> NameIdxMapping;
3480 NameIdxMapping["__"] = -1;
3482 NameIdxMapping["this"] = 0;
3485 for (const ParmVarDecl *PVD : FD->parameters())
3486 NameIdxMapping[PVD->getName()] = Idx++;
3488 auto UnknownName = NameIdxMapping.end();
3490 SmallVector<int, 8> EncodingIndices;
3491 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3495 if (AL.isArgIdent(I)) {
3496 IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3497 auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3498 if (It == UnknownName) {
3499 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3500 << IdLoc->Ident << IdLoc->Loc;
3504 SR = SourceRange(IdLoc->Loc);
3505 ArgIdx = It->second;
3506 } else if (AL.isArgExpr(I)) {
3507 Expr *IdxExpr = AL.getArgAsExpr(I);
3509 // If the expression is not parseable as an int32_t we have a problem.
3510 if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3512 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3513 << AL << (I + 1) << IdxExpr->getSourceRange();
3517 // Check oob, excluding the special values, 0 and -1.
3518 if (ArgIdx < -1 || ArgIdx > NumArgs) {
3519 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3520 << AL << (I + 1) << IdxExpr->getSourceRange();
3524 SR = IdxExpr->getSourceRange();
3526 llvm_unreachable("Unexpected ParsedAttr argument type!");
3529 if (ArgIdx == 0 && !HasImplicitThisParam) {
3530 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3535 // Adjust for the case we do not have an implicit "this" parameter. In this
3536 // case we decrease all positive values by 1 to get LLVM argument indices.
3537 if (!HasImplicitThisParam && ArgIdx > 0)
3540 EncodingIndices.push_back(ArgIdx);
3543 int CalleeIdx = EncodingIndices.front();
3544 // Check if the callee index is proper, thus not "this" and not "unknown".
3545 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3546 // is false and positive if "HasImplicitThisParam" is true.
3547 if (CalleeIdx < (int)HasImplicitThisParam) {
3548 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3553 // Get the callee type, note the index adjustment as the AST doesn't contain
3554 // the this type (which the callee cannot reference anyway!).
3555 const Type *CalleeType =
3556 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3558 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3559 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3564 const Type *CalleeFnType =
3565 CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3567 // TODO: Check the type of the callee arguments.
3569 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3570 if (!CalleeFnProtoType) {
3571 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3576 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3577 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3578 << AL << (unsigned)(EncodingIndices.size() - 1);
3582 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3583 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3584 << AL << (unsigned)(EncodingIndices.size() - 1);
3588 if (CalleeFnProtoType->isVariadic()) {
3589 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3593 // Do not allow multiple callback attributes.
3594 if (D->hasAttr<CallbackAttr>()) {
3595 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3599 D->addAttr(::new (S.Context) CallbackAttr(
3600 AL.getRange(), S.Context, EncodingIndices.data(), EncodingIndices.size(),
3601 AL.getAttributeSpellingListIndex()));
3604 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3605 // Try to find the underlying union declaration.
3606 RecordDecl *RD = nullptr;
3607 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3608 if (TD && TD->getUnderlyingType()->isUnionType())
3609 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3611 RD = dyn_cast<RecordDecl>(D);
3613 if (!RD || !RD->isUnion()) {
3614 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3619 if (!RD->isCompleteDefinition()) {
3620 if (!RD->isBeingDefined())
3622 diag::warn_transparent_union_attribute_not_definition);
3626 RecordDecl::field_iterator Field = RD->field_begin(),
3627 FieldEnd = RD->field_end();
3628 if (Field == FieldEnd) {
3629 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3633 FieldDecl *FirstField = *Field;
3634 QualType FirstType = FirstField->getType();
3635 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3636 S.Diag(FirstField->getLocation(),
3637 diag::warn_transparent_union_attribute_floating)
3638 << FirstType->isVectorType() << FirstType;
3642 if (FirstType->isIncompleteType())
3644 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3645 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3646 for (; Field != FieldEnd; ++Field) {
3647 QualType FieldType = Field->getType();
3648 if (FieldType->isIncompleteType())
3650 // FIXME: this isn't fully correct; we also need to test whether the
3651 // members of the union would all have the same calling convention as the
3652 // first member of the union. Checking just the size and alignment isn't
3653 // sufficient (consider structs passed on the stack instead of in registers
3655 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3656 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3657 // Warn if we drop the attribute.
3658 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3659 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3660 : S.Context.getTypeAlign(FieldType);
3661 S.Diag(Field->getLocation(),
3662 diag::warn_transparent_union_attribute_field_size_align)
3663 << isSize << Field->getDeclName() << FieldBits;
3664 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3665 S.Diag(FirstField->getLocation(),
3666 diag::note_transparent_union_first_field_size_align)
3667 << isSize << FirstBits;
3672 RD->addAttr(::new (S.Context)
3673 TransparentUnionAttr(AL.getRange(), S.Context,
3674 AL.getAttributeSpellingListIndex()));
3677 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3678 // Make sure that there is a string literal as the annotation's single
3681 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3684 // Don't duplicate annotations that are already set.
3685 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3686 if (I->getAnnotation() == Str)
3690 D->addAttr(::new (S.Context)
3691 AnnotateAttr(AL.getRange(), S.Context, Str,
3692 AL.getAttributeSpellingListIndex()));
3695 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3696 S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0),
3697 AL.getAttributeSpellingListIndex());
3700 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3701 unsigned SpellingListIndex) {
3702 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3703 SourceLocation AttrLoc = AttrRange.getBegin();
3706 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3707 T = TD->getUnderlyingType();
3708 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3711 llvm_unreachable("Unknown decl type for align_value");
3713 if (!T->isDependentType() && !T->isAnyPointerType() &&
3714 !T->isReferenceType() && !T->isMemberPointerType()) {
3715 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3716 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3720 if (!E->isValueDependent()) {
3721 llvm::APSInt Alignment;
3723 = VerifyIntegerConstantExpression(E, &Alignment,
3724 diag::err_align_value_attribute_argument_not_int,
3725 /*AllowFold*/ false);
3726 if (ICE.isInvalid())
3729 if (!Alignment.isPowerOf2()) {
3730 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3731 << E->getSourceRange();
3735 D->addAttr(::new (Context)
3736 AlignValueAttr(AttrRange, Context, ICE.get(),
3737 SpellingListIndex));
3741 // Save dependent expressions in the AST to be instantiated.
3742 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3745 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3746 // check the attribute arguments.
3747 if (AL.getNumArgs() > 1) {
3748 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3752 if (AL.getNumArgs() == 0) {
3753 D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context,
3754 true, nullptr, AL.getAttributeSpellingListIndex()));
3758 Expr *E = AL.getArgAsExpr(0);
3759 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3760 S.Diag(AL.getEllipsisLoc(),
3761 diag::err_pack_expansion_without_parameter_packs);
3765 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3768 S.AddAlignedAttr(AL.getRange(), D, E, AL.getAttributeSpellingListIndex(),
3769 AL.isPackExpansion());
3772 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3773 unsigned SpellingListIndex, bool IsPackExpansion) {
3774 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3775 SourceLocation AttrLoc = AttrRange.getBegin();
3777 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3778 if (TmpAttr.isAlignas()) {
3779 // C++11 [dcl.align]p1:
3780 // An alignment-specifier may be applied to a variable or to a class
3781 // data member, but it shall not be applied to a bit-field, a function
3782 // parameter, the formal parameter of a catch clause, or a variable
3783 // declared with the register storage class specifier. An
3784 // alignment-specifier may also be applied to the declaration of a class
3785 // or enumeration type.
3787 // An alignment attribute shall not be specified in a declaration of
3788 // a typedef, or a bit-field, or a function, or a parameter, or an
3789 // object declared with the register storage-class specifier.
3791 if (isa<ParmVarDecl>(D)) {
3793 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3794 if (VD->getStorageClass() == SC_Register)
3796 if (VD->isExceptionVariable())
3798 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3799 if (FD->isBitField())
3801 } else if (!isa<TagDecl>(D)) {
3802 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3803 << (TmpAttr.isC11() ? ExpectedVariableOrField
3804 : ExpectedVariableFieldOrTag);
3807 if (DiagKind != -1) {
3808 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3809 << &TmpAttr << DiagKind;
3814 if (E->isValueDependent()) {
3815 // We can't support a dependent alignment on a non-dependent type,
3816 // because we have no way to model that a type is "alignment-dependent"
3817 // but not dependent in any other way.
3818 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3819 if (!TND->getUnderlyingType()->isDependentType()) {
3820 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3821 << E->getSourceRange();
3826 // Save dependent expressions in the AST to be instantiated.
3827 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3828 AA->setPackExpansion(IsPackExpansion);
3833 // FIXME: Cache the number on the AL object?
3834 llvm::APSInt Alignment;
3836 = VerifyIntegerConstantExpression(E, &Alignment,
3837 diag::err_aligned_attribute_argument_not_int,
3838 /*AllowFold*/ false);
3839 if (ICE.isInvalid())
3842 uint64_t AlignVal = Alignment.getZExtValue();
3844 // C++11 [dcl.align]p2:
3845 // -- if the constant expression evaluates to zero, the alignment
3846 // specifier shall have no effect
3848 // An alignment specification of zero has no effect.
3849 if (!(TmpAttr.isAlignas() && !Alignment)) {
3850 if (!llvm::isPowerOf2_64(AlignVal)) {
3851 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3852 << E->getSourceRange();
3857 // Alignment calculations can wrap around if it's greater than 2**28.
3858 unsigned MaxValidAlignment =
3859 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3861 if (AlignVal > MaxValidAlignment) {
3862 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3863 << E->getSourceRange();
3867 if (Context.getTargetInfo().isTLSSupported()) {
3868 unsigned MaxTLSAlign =
3869 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3871 const auto *VD = dyn_cast<VarDecl>(D);
3872 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3873 VD->getTLSKind() != VarDecl::TLS_None) {
3874 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3875 << (unsigned)AlignVal << VD << MaxTLSAlign;
3880 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3881 ICE.get(), SpellingListIndex);
3882 AA->setPackExpansion(IsPackExpansion);
3886 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3887 unsigned SpellingListIndex, bool IsPackExpansion) {
3888 // FIXME: Cache the number on the AL object if non-dependent?
3889 // FIXME: Perform checking of type validity
3890 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3892 AA->setPackExpansion(IsPackExpansion);
3896 void Sema::CheckAlignasUnderalignment(Decl *D) {
3897 assert(D->hasAttrs() && "no attributes on decl");
3899 QualType UnderlyingTy, DiagTy;
3900 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3901 UnderlyingTy = DiagTy = VD->getType();
3903 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3904 if (const auto *ED = dyn_cast<EnumDecl>(D))
3905 UnderlyingTy = ED->getIntegerType();
3907 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3910 // C++11 [dcl.align]p5, C11 6.7.5/4:
3911 // The combined effect of all alignment attributes in a declaration shall
3912 // not specify an alignment that is less strict than the alignment that
3913 // would otherwise be required for the entity being declared.
3914 AlignedAttr *AlignasAttr = nullptr;
3916 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3917 if (I->isAlignmentDependent())
3921 Align = std::max(Align, I->getAlignment(Context));
3924 if (AlignasAttr && Align) {
3925 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3926 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3927 if (NaturalAlign > RequestedAlign)
3928 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3929 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3933 bool Sema::checkMSInheritanceAttrOnDefinition(
3934 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3935 MSInheritanceAttr::Spelling SemanticSpelling) {
3936 assert(RD->hasDefinition() && "RD has no definition!");
3938 // We may not have seen base specifiers or any virtual methods yet. We will
3939 // have to wait until the record is defined to catch any mismatches.
3940 if (!RD->getDefinition()->isCompleteDefinition())
3943 // The unspecified model never matches what a definition could need.
3944 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3948 if (RD->calculateInheritanceModel() == SemanticSpelling)
3951 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3955 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3956 << 0 /*definition*/;
3957 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3958 << RD->getNameAsString();
3962 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3964 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3965 bool &IntegerMode, bool &ComplexMode) {
3967 ComplexMode = false;
3968 switch (Str.size()) {
3990 if (Str[1] == 'F') {
3991 IntegerMode = false;
3992 } else if (Str[1] == 'C') {
3993 IntegerMode = false;
3995 } else if (Str[1] != 'I') {
4000 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4001 // pointer on PIC16 and other embedded platforms.
4003 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4004 else if (Str == "byte")
4005 DestWidth = S.Context.getTargetInfo().getCharWidth();
4008 if (Str == "pointer")
4009 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4012 if (Str == "unwind_word")
4013 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4018 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4021 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4022 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4023 /// HImode, not an intermediate pointer.
4024 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4025 // This attribute isn't documented, but glibc uses it. It changes
4026 // the width of an int or unsigned int to the specified size.
4027 if (!AL.isArgIdent(0)) {
4028 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4029 << AL << AANT_ArgumentIdentifier;
4033 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4035 S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex());
4038 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
4039 unsigned SpellingListIndex, bool InInstantiation) {
4040 StringRef Str = Name->getName();
4042 SourceLocation AttrLoc = AttrRange.getBegin();
4044 unsigned DestWidth = 0;
4045 bool IntegerMode = true;
4046 bool ComplexMode = false;
4047 llvm::APInt VectorSize(64, 0);
4048 if (Str.size() >= 4 && Str[0] == 'V') {
4049 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4050 size_t StrSize = Str.size();
4051 size_t VectorStringLength = 0;
4052 while ((VectorStringLength + 1) < StrSize &&
4053 isdigit(Str[VectorStringLength + 1]))
4054 ++VectorStringLength;
4055 if (VectorStringLength &&
4056 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4057 VectorSize.isPowerOf2()) {
4058 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4059 IntegerMode, ComplexMode);
4060 // Avoid duplicate warning from template instantiation.
4061 if (!InInstantiation)
4062 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4069 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
4071 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4072 // and friends, at least with glibc.
4073 // FIXME: Make sure floating-point mappings are accurate
4074 // FIXME: Support XF and TF types
4076 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4081 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4082 OldTy = TD->getUnderlyingType();
4083 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4084 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4085 // Try to get type from enum declaration, default to int.
4086 OldTy = ED->getIntegerType();
4088 OldTy = Context.IntTy;
4090 OldTy = cast<ValueDecl>(D)->getType();
4092 if (OldTy->isDependentType()) {
4093 D->addAttr(::new (Context)
4094 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
4098 // Base type can also be a vector type (see PR17453).
4099 // Distinguish between base type and base element type.
4100 QualType OldElemTy = OldTy;
4101 if (const auto *VT = OldTy->getAs<VectorType>())
4102 OldElemTy = VT->getElementType();
4104 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4105 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4106 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4107 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4108 VectorSize.getBoolValue()) {
4109 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
4112 bool IntegralOrAnyEnumType =
4113 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
4115 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4116 !IntegralOrAnyEnumType)
4117 Diag(AttrLoc, diag::err_mode_not_primitive);
4118 else if (IntegerMode) {
4119 if (!IntegralOrAnyEnumType)
4120 Diag(AttrLoc, diag::err_mode_wrong_type);
4121 } else if (ComplexMode) {
4122 if (!OldElemTy->isComplexType())
4123 Diag(AttrLoc, diag::err_mode_wrong_type);
4125 if (!OldElemTy->isFloatingType())
4126 Diag(AttrLoc, diag::err_mode_wrong_type);
4132 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4133 OldElemTy->isSignedIntegerType());
4135 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
4137 if (NewElemTy.isNull()) {
4138 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4143 NewElemTy = Context.getComplexType(NewElemTy);
4146 QualType NewTy = NewElemTy;
4147 if (VectorSize.getBoolValue()) {
4148 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4149 VectorType::GenericVector);
4150 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4151 // Complex machine mode does not support base vector types.
4153 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4156 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4157 OldVT->getNumElements() /
4158 Context.getTypeSize(NewElemTy);
4160 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4163 if (NewTy.isNull()) {
4164 Diag(AttrLoc, diag::err_mode_wrong_type);
4168 // Install the new type.
4169 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4170 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4171 else if (auto *ED = dyn_cast<EnumDecl>(D))
4172 ED->setIntegerType(NewTy);
4174 cast<ValueDecl>(D)->setType(NewTy);
4176 D->addAttr(::new (Context)
4177 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
4180 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4181 D->addAttr(::new (S.Context)
4182 NoDebugAttr(AL.getRange(), S.Context,
4183 AL.getAttributeSpellingListIndex()));
4186 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
4187 IdentifierInfo *Ident,
4188 unsigned AttrSpellingListIndex) {
4189 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4190 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
4191 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4195 if (D->hasAttr<AlwaysInlineAttr>())
4198 return ::new (Context) AlwaysInlineAttr(Range, Context,
4199 AttrSpellingListIndex);
4202 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4203 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4206 return ::new (Context)
4207 CommonAttr(AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4210 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4211 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4214 return ::new (Context)
4215 CommonAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4218 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4219 const ParsedAttr &AL) {
4220 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4221 // Attribute applies to Var but not any subclass of it (like ParmVar,
4222 // ImplicitParm or VarTemplateSpecialization).
4223 if (VD->getKind() != Decl::Var) {
4224 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4225 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4226 : ExpectedVariableOrFunction);
4229 // Attribute does not apply to non-static local variables.
4230 if (VD->hasLocalStorage()) {
4231 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4236 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4239 return ::new (Context) InternalLinkageAttr(
4240 AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4242 InternalLinkageAttr *
4243 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4244 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4245 // Attribute applies to Var but not any subclass of it (like ParmVar,
4246 // ImplicitParm or VarTemplateSpecialization).
4247 if (VD->getKind() != Decl::Var) {
4248 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4249 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4250 : ExpectedVariableOrFunction);
4253 // Attribute does not apply to non-static local variables.
4254 if (VD->hasLocalStorage()) {
4255 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4260 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4263 return ::new (Context)
4264 InternalLinkageAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4267 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4268 unsigned AttrSpellingListIndex) {
4269 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4270 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4271 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4275 if (D->hasAttr<MinSizeAttr>())
4278 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4281 NoSpeculativeLoadHardeningAttr *Sema::mergeNoSpeculativeLoadHardeningAttr(
4282 Decl *D, const NoSpeculativeLoadHardeningAttr &AL) {
4283 if (checkAttrMutualExclusion<SpeculativeLoadHardeningAttr>(*this, D, AL))
4286 return ::new (Context) NoSpeculativeLoadHardeningAttr(
4287 AL.getRange(), Context, AL.getSpellingListIndex());
4290 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4291 unsigned AttrSpellingListIndex) {
4292 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4293 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4294 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4295 D->dropAttr<AlwaysInlineAttr>();
4297 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4298 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4299 Diag(Range.getBegin(), diag::note_conflicting_attribute);
4300 D->dropAttr<MinSizeAttr>();
4303 if (D->hasAttr<OptimizeNoneAttr>())
4306 return ::new (Context) OptimizeNoneAttr(Range, Context,
4307 AttrSpellingListIndex);
4310 SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr(
4311 Decl *D, const SpeculativeLoadHardeningAttr &AL) {
4312 if (checkAttrMutualExclusion<NoSpeculativeLoadHardeningAttr>(*this, D, AL))
4315 return ::new (Context) SpeculativeLoadHardeningAttr(
4316 AL.getRange(), Context, AL.getSpellingListIndex());
4319 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4320 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4323 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4324 D, AL.getRange(), AL.getName(),
4325 AL.getAttributeSpellingListIndex()))
4329 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4330 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4331 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4332 D->addAttr(MinSize);
4335 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4336 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4337 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4338 D->addAttr(Optnone);
4341 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4342 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4344 const auto *VD = cast<VarDecl>(D);
4345 if (!VD->hasGlobalStorage()) {
4346 S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4349 D->addAttr(::new (S.Context) CUDAConstantAttr(
4350 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4353 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4354 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4356 const auto *VD = cast<VarDecl>(D);
4357 // extern __shared__ is only allowed on arrays with no length (e.g.
4359 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4360 !isa<IncompleteArrayType>(VD->getType())) {
4361 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4364 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4365 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4366 << S.CurrentCUDATarget())
4368 D->addAttr(::new (S.Context) CUDASharedAttr(
4369 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4372 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4373 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4374 checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4377 const auto *FD = cast<FunctionDecl>(D);
4378 if (!FD->getReturnType()->isVoidType()) {
4379 SourceRange RTRange = FD->getReturnTypeSourceRange();
4380 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4382 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4386 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4387 if (Method->isInstance()) {
4388 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4392 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4394 // Only warn for "inline" when compiling for host, to cut down on noise.
4395 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4396 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4398 D->addAttr(::new (S.Context)
4399 CUDAGlobalAttr(AL.getRange(), S.Context,
4400 AL.getAttributeSpellingListIndex()));
4403 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4404 const auto *Fn = cast<FunctionDecl>(D);
4405 if (!Fn->isInlineSpecified()) {
4406 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4410 D->addAttr(::new (S.Context)
4411 GNUInlineAttr(AL.getRange(), S.Context,
4412 AL.getAttributeSpellingListIndex()));
4415 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4416 if (hasDeclarator(D)) return;
4418 // Diagnostic is emitted elsewhere: here we store the (valid) AL
4419 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4421 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4424 if (!isa<ObjCMethodDecl>(D)) {
4425 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4426 << AL << ExpectedFunctionOrMethod;
4430 switch (AL.getKind()) {
4431 case ParsedAttr::AT_FastCall:
4432 D->addAttr(::new (S.Context)
4433 FastCallAttr(AL.getRange(), S.Context,
4434 AL.getAttributeSpellingListIndex()));
4436 case ParsedAttr::AT_StdCall:
4437 D->addAttr(::new (S.Context)
4438 StdCallAttr(AL.getRange(), S.Context,
4439 AL.getAttributeSpellingListIndex()));
4441 case ParsedAttr::AT_ThisCall:
4442 D->addAttr(::new (S.Context)
4443 ThisCallAttr(AL.getRange(), S.Context,
4444 AL.getAttributeSpellingListIndex()));
4446 case ParsedAttr::AT_CDecl:
4447 D->addAttr(::new (S.Context)
4448 CDeclAttr(AL.getRange(), S.Context,
4449 AL.getAttributeSpellingListIndex()));
4451 case ParsedAttr::AT_Pascal:
4452 D->addAttr(::new (S.Context)
4453 PascalAttr(AL.getRange(), S.Context,
4454 AL.getAttributeSpellingListIndex()));
4456 case ParsedAttr::AT_SwiftCall:
4457 D->addAttr(::new (S.Context)
4458 SwiftCallAttr(AL.getRange(), S.Context,
4459 AL.getAttributeSpellingListIndex()));
4461 case ParsedAttr::AT_VectorCall:
4462 D->addAttr(::new (S.Context)
4463 VectorCallAttr(AL.getRange(), S.Context,
4464 AL.getAttributeSpellingListIndex()));
4466 case ParsedAttr::AT_MSABI:
4467 D->addAttr(::new (S.Context)
4468 MSABIAttr(AL.getRange(), S.Context,
4469 AL.getAttributeSpellingListIndex()));
4471 case ParsedAttr::AT_SysVABI:
4472 D->addAttr(::new (S.Context)
4473 SysVABIAttr(AL.getRange(), S.Context,
4474 AL.getAttributeSpellingListIndex()));
4476 case ParsedAttr::AT_RegCall:
4477 D->addAttr(::new (S.Context) RegCallAttr(
4478 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4480 case ParsedAttr::AT_Pcs: {
4481 PcsAttr::PCSType PCS;
4484 PCS = PcsAttr::AAPCS;
4487 PCS = PcsAttr::AAPCS_VFP;
4490 llvm_unreachable("unexpected calling convention in pcs attribute");
4493 D->addAttr(::new (S.Context)
4494 PcsAttr(AL.getRange(), S.Context, PCS,
4495 AL.getAttributeSpellingListIndex()));
4498 case ParsedAttr::AT_AArch64VectorPcs:
4499 D->addAttr(::new(S.Context)
4500 AArch64VectorPcsAttr(AL.getRange(), S.Context,
4501 AL.getAttributeSpellingListIndex()));
4503 case ParsedAttr::AT_IntelOclBicc:
4504 D->addAttr(::new (S.Context)
4505 IntelOclBiccAttr(AL.getRange(), S.Context,
4506 AL.getAttributeSpellingListIndex()));
4508 case ParsedAttr::AT_PreserveMost:
4509 D->addAttr(::new (S.Context) PreserveMostAttr(
4510 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4512 case ParsedAttr::AT_PreserveAll:
4513 D->addAttr(::new (S.Context) PreserveAllAttr(
4514 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4517 llvm_unreachable("unexpected attribute kind");
4521 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4522 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4525 std::vector<StringRef> DiagnosticIdentifiers;
4526 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4529 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4532 // FIXME: Warn if the rule name is unknown. This is tricky because only
4533 // clang-tidy knows about available rules.
4534 DiagnosticIdentifiers.push_back(RuleName);
4536 D->addAttr(::new (S.Context) SuppressAttr(
4537 AL.getRange(), S.Context, DiagnosticIdentifiers.data(),
4538 DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex()));
4541 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4542 const FunctionDecl *FD) {
4543 if (Attrs.isInvalid())
4546 if (Attrs.hasProcessingCache()) {
4547 CC = (CallingConv) Attrs.getProcessingCache();
4551 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4552 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4557 // TODO: diagnose uses of these conventions on the wrong target.
4558 switch (Attrs.getKind()) {
4559 case ParsedAttr::AT_CDecl:
4562 case ParsedAttr::AT_FastCall:
4563 CC = CC_X86FastCall;
4565 case ParsedAttr::AT_StdCall:
4568 case ParsedAttr::AT_ThisCall:
4569 CC = CC_X86ThisCall;
4571 case ParsedAttr::AT_Pascal:
4574 case ParsedAttr::AT_SwiftCall:
4577 case ParsedAttr::AT_VectorCall:
4578 CC = CC_X86VectorCall;
4580 case ParsedAttr::AT_AArch64VectorPcs:
4581 CC = CC_AArch64VectorCall;
4583 case ParsedAttr::AT_RegCall:
4586 case ParsedAttr::AT_MSABI:
4587 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4590 case ParsedAttr::AT_SysVABI:
4591 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4594 case ParsedAttr::AT_Pcs: {
4596 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4600 if (StrRef == "aapcs") {
4603 } else if (StrRef == "aapcs-vfp") {
4609 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4612 case ParsedAttr::AT_IntelOclBicc:
4613 CC = CC_IntelOclBicc;
4615 case ParsedAttr::AT_PreserveMost:
4616 CC = CC_PreserveMost;
4618 case ParsedAttr::AT_PreserveAll:
4619 CC = CC_PreserveAll;
4621 default: llvm_unreachable("unexpected attribute kind");
4624 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
4625 const TargetInfo &TI = Context.getTargetInfo();
4626 // CUDA functions may have host and/or device attributes which indicate
4627 // their targeted execution environment, therefore the calling convention
4628 // of functions in CUDA should be checked against the target deduced based
4629 // on their host/device attributes.
4630 if (LangOpts.CUDA) {
4631 auto *Aux = Context.getAuxTargetInfo();
4632 auto CudaTarget = IdentifyCUDATarget(FD);
4633 bool CheckHost = false, CheckDevice = false;
4634 switch (CudaTarget) {
4635 case CFT_HostDevice:
4646 case CFT_InvalidTarget:
4647 llvm_unreachable("unexpected cuda target");
4649 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4650 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4651 if (CheckHost && HostTI)
4652 A = HostTI->checkCallingConvention(CC);
4653 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4654 A = DeviceTI->checkCallingConvention(CC);
4656 A = TI.checkCallingConvention(CC);
4660 case TargetInfo::CCCR_OK:
4663 case TargetInfo::CCCR_Ignore:
4664 // Treat an ignored convention as if it was an explicit C calling convention
4665 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4666 // that command line flags that change the default convention to
4667 // __vectorcall don't affect declarations marked __stdcall.
4671 case TargetInfo::CCCR_Warning: {
4672 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4673 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4675 // This convention is not valid for the target. Use the default function or
4676 // method calling convention.
4677 bool IsCXXMethod = false, IsVariadic = false;
4679 IsCXXMethod = FD->isCXXInstanceMember();
4680 IsVariadic = FD->isVariadic();
4682 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4687 Attrs.setProcessingCache((unsigned) CC);
4691 /// Pointer-like types in the default address space.
4692 static bool isValidSwiftContextType(QualType Ty) {
4693 if (!Ty->hasPointerRepresentation())
4694 return Ty->isDependentType();
4695 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4698 /// Pointers and references in the default address space.
4699 static bool isValidSwiftIndirectResultType(QualType Ty) {
4700 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4701 Ty = PtrType->getPointeeType();
4702 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4703 Ty = RefType->getPointeeType();
4705 return Ty->isDependentType();
4707 return Ty.getAddressSpace() == LangAS::Default;
4710 /// Pointers and references to pointers in the default address space.
4711 static bool isValidSwiftErrorResultType(QualType Ty) {
4712 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4713 Ty = PtrType->getPointeeType();
4714 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4715 Ty = RefType->getPointeeType();
4717 return Ty->isDependentType();
4719 if (!Ty.getQualifiers().empty())
4721 return isValidSwiftContextType(Ty);
4724 static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs,
4726 S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4727 Attrs.getAttributeSpellingListIndex());
4730 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4731 unsigned spellingIndex) {
4733 QualType type = cast<ParmVarDecl>(D)->getType();
4735 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4736 if (existingAttr->getABI() != abi) {
4737 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4738 << getParameterABISpelling(abi) << existingAttr;
4739 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4745 case ParameterABI::Ordinary:
4746 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4748 case ParameterABI::SwiftContext:
4749 if (!isValidSwiftContextType(type)) {
4750 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4751 << getParameterABISpelling(abi)
4752 << /*pointer to pointer */ 0 << type;
4754 D->addAttr(::new (Context)
4755 SwiftContextAttr(range, Context, spellingIndex));
4758 case ParameterABI::SwiftErrorResult:
4759 if (!isValidSwiftErrorResultType(type)) {
4760 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4761 << getParameterABISpelling(abi)
4762 << /*pointer to pointer */ 1 << type;
4764 D->addAttr(::new (Context)
4765 SwiftErrorResultAttr(range, Context, spellingIndex));
4768 case ParameterABI::SwiftIndirectResult:
4769 if (!isValidSwiftIndirectResultType(type)) {
4770 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4771 << getParameterABISpelling(abi)
4772 << /*pointer*/ 0 << type;
4774 D->addAttr(::new (Context)
4775 SwiftIndirectResultAttr(range, Context, spellingIndex));
4778 llvm_unreachable("bad parameter ABI attribute");
4781 /// Checks a regparm attribute, returning true if it is ill-formed and
4782 /// otherwise setting numParams to the appropriate value.
4783 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4787 if (!checkAttributeNumArgs(*this, AL, 1)) {
4793 Expr *NumParamsExpr = AL.getArgAsExpr(0);
4794 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4799 if (Context.getTargetInfo().getRegParmMax() == 0) {
4800 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4801 << NumParamsExpr->getSourceRange();
4807 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4808 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4809 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4817 // Checks whether an argument of launch_bounds attribute is
4818 // acceptable, performs implicit conversion to Rvalue, and returns
4819 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4820 // and may output an error.
4821 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4822 const CUDALaunchBoundsAttr &AL,
4823 const unsigned Idx) {
4824 if (S.DiagnoseUnexpandedParameterPack(E))
4827 // Accept template arguments for now as they depend on something else.
4828 // We'll get to check them when they eventually get instantiated.
4829 if (E->isValueDependent())
4833 if (!E->isIntegerConstantExpr(I, S.Context)) {
4834 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4835 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4838 // Make sure we can fit it in 32 bits.
4839 if (!I.isIntN(32)) {
4840 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4841 << 32 << /* Unsigned */ 1;
4845 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4846 << &AL << Idx << E->getSourceRange();
4848 // We may need to perform implicit conversion of the argument.
4849 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4850 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4851 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4852 assert(!ValArg.isInvalid() &&
4853 "Unexpected PerformCopyInitialization() failure.");
4855 return ValArg.getAs<Expr>();
4858 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4859 Expr *MinBlocks, unsigned SpellingListIndex) {
4860 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4862 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4863 if (MaxThreads == nullptr)
4867 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4868 if (MinBlocks == nullptr)
4872 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4873 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4876 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4877 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4878 !checkAttributeAtMostNumArgs(S, AL, 2))
4881 S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0),
4882 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
4883 AL.getAttributeSpellingListIndex());
4886 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4887 const ParsedAttr &AL) {
4888 if (!AL.isArgIdent(0)) {
4889 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4890 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4894 ParamIdx ArgumentIdx;
4895 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4899 ParamIdx TypeTagIdx;
4900 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4904 bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag";
4906 // Ensure that buffer has a pointer type.
4907 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4908 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4909 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4910 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4913 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4914 AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx,
4915 TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex()));
4918 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4919 const ParsedAttr &AL) {
4920 if (!AL.isArgIdent(0)) {
4921 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4922 << AL << 1 << AANT_ArgumentIdentifier;
4926 if (!checkAttributeNumArgs(S, AL, 1))
4929 if (!isa<VarDecl>(D)) {
4930 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4931 << AL << ExpectedVariable;
4935 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4936 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4937 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4938 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4940 D->addAttr(::new (S.Context)
4941 TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind,
4943 AL.getLayoutCompatible(),
4945 AL.getAttributeSpellingListIndex()));
4948 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4951 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4953 true /* CanIndexImplicitThis */))
4956 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4957 D->addAttr(::new (S.Context) XRayLogArgsAttr(
4958 AL.getRange(), S.Context, ArgCount.getSourceIndex(),
4959 AL.getAttributeSpellingListIndex()));
4962 //===----------------------------------------------------------------------===//
4963 // Checker-specific attribute handlers.
4964 //===----------------------------------------------------------------------===//
4965 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
4966 return QT->isDependentType() || QT->isObjCRetainableType();
4969 static bool isValidSubjectOfNSAttribute(QualType QT) {
4970 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
4971 QT->isObjCNSObjectType();
4974 static bool isValidSubjectOfCFAttribute(QualType QT) {
4975 return QT->isDependentType() || QT->isPointerType() ||
4976 isValidSubjectOfNSAttribute(QT);
4979 static bool isValidSubjectOfOSAttribute(QualType QT) {
4980 if (QT->isDependentType())
4982 QualType PT = QT->getPointeeType();
4983 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
4986 void Sema::AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
4987 RetainOwnershipKind K,
4988 bool IsTemplateInstantiation) {
4989 ValueDecl *VD = cast<ValueDecl>(D);
4991 case RetainOwnershipKind::OS:
4992 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
4993 *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()),
4994 diag::warn_ns_attribute_wrong_parameter_type,
4995 /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1);
4997 case RetainOwnershipKind::NS:
4998 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
4999 *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()),
5001 // These attributes are normally just advisory, but in ARC, ns_consumed
5002 // is significant. Allow non-dependent code to contain inappropriate
5003 // attributes even in ARC, but require template instantiations to be
5004 // set up correctly.
5005 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5006 ? diag::err_ns_attribute_wrong_parameter_type
5007 : diag::warn_ns_attribute_wrong_parameter_type),
5008 /*ExtraArgs=*/SR, "ns_consumed", /*objc pointers*/ 0);
5010 case RetainOwnershipKind::CF:
5011 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5012 *this, VD, SR, SpellingIndex,
5013 isValidSubjectOfCFAttribute(VD->getType()),
5014 diag::warn_ns_attribute_wrong_parameter_type,
5015 /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1);
5020 static Sema::RetainOwnershipKind
5021 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5022 switch (AL.getKind()) {
5023 case ParsedAttr::AT_CFConsumed:
5024 case ParsedAttr::AT_CFReturnsRetained:
5025 case ParsedAttr::AT_CFReturnsNotRetained:
5026 return Sema::RetainOwnershipKind::CF;
5027 case ParsedAttr::AT_OSConsumesThis:
5028 case ParsedAttr::AT_OSConsumed:
5029 case ParsedAttr::AT_OSReturnsRetained:
5030 case ParsedAttr::AT_OSReturnsNotRetained:
5031 case ParsedAttr::AT_OSReturnsRetainedOnZero:
5032 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5033 return Sema::RetainOwnershipKind::OS;
5034 case ParsedAttr::AT_NSConsumesSelf:
5035 case ParsedAttr::AT_NSConsumed:
5036 case ParsedAttr::AT_NSReturnsRetained:
5037 case ParsedAttr::AT_NSReturnsNotRetained:
5038 case ParsedAttr::AT_NSReturnsAutoreleased:
5039 return Sema::RetainOwnershipKind::NS;
5041 llvm_unreachable("Wrong argument supplied");
5045 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
5046 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5049 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5050 << "'ns_returns_retained'" << 0 << 0;
5054 /// \return whether the parameter is a pointer to OSObject pointer.
5055 static bool isValidOSObjectOutParameter(const Decl *D) {
5056 const auto *PVD = dyn_cast<ParmVarDecl>(D);
5059 QualType QT = PVD->getType();
5060 QualType PT = QT->getPointeeType();
5061 return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5064 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5065 const ParsedAttr &AL) {
5066 QualType ReturnType;
5067 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5069 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5070 ReturnType = MD->getReturnType();
5071 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5072 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5073 return; // ignore: was handled as a type attribute
5074 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5075 ReturnType = PD->getType();
5076 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5077 ReturnType = FD->getReturnType();
5078 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
5079 // Attributes on parameters are used for out-parameters,
5080 // passed as pointers-to-pointers.
5081 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
5082 ? /*pointer-to-CF-pointer*/2
5083 : /*pointer-to-OSObject-pointer*/3;
5084 ReturnType = Param->getType()->getPointeeType();
5085 if (ReturnType.isNull()) {
5086 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5087 << AL << DiagID << AL.getRange();
5090 } else if (AL.isUsedAsTypeAttr()) {
5093 AttributeDeclKind ExpectedDeclKind;
5094 switch (AL.getKind()) {
5095 default: llvm_unreachable("invalid ownership attribute");
5096 case ParsedAttr::AT_NSReturnsRetained:
5097 case ParsedAttr::AT_NSReturnsAutoreleased:
5098 case ParsedAttr::AT_NSReturnsNotRetained:
5099 ExpectedDeclKind = ExpectedFunctionOrMethod;
5102 case ParsedAttr::AT_OSReturnsRetained:
5103 case ParsedAttr::AT_OSReturnsNotRetained:
5104 case ParsedAttr::AT_CFReturnsRetained:
5105 case ParsedAttr::AT_CFReturnsNotRetained:
5106 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
5109 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
5110 << AL.getRange() << AL << ExpectedDeclKind;
5116 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
5117 switch (AL.getKind()) {
5118 default: llvm_unreachable("invalid ownership attribute");
5119 case ParsedAttr::AT_NSReturnsRetained:
5120 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
5124 case ParsedAttr::AT_NSReturnsAutoreleased:
5125 case ParsedAttr::AT_NSReturnsNotRetained:
5126 TypeOK = isValidSubjectOfNSAttribute(ReturnType);
5130 case ParsedAttr::AT_CFReturnsRetained:
5131 case ParsedAttr::AT_CFReturnsNotRetained:
5132 TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5136 case ParsedAttr::AT_OSReturnsRetained:
5137 case ParsedAttr::AT_OSReturnsNotRetained:
5138 TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5140 ParmDiagID = 3; // Pointer-to-OSObject-pointer
5145 if (AL.isUsedAsTypeAttr())
5148 if (isa<ParmVarDecl>(D)) {
5149 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5150 << AL << ParmDiagID << AL.getRange();
5152 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5157 } SubjectKind = Function;
5158 if (isa<ObjCMethodDecl>(D))
5159 SubjectKind = Method;
5160 else if (isa<ObjCPropertyDecl>(D))
5161 SubjectKind = Property;
5162 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5163 << AL << SubjectKind << Cf << AL.getRange();
5168 switch (AL.getKind()) {
5170 llvm_unreachable("invalid ownership attribute");
5171 case ParsedAttr::AT_NSReturnsAutoreleased:
5172 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5174 case ParsedAttr::AT_CFReturnsNotRetained:
5175 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5177 case ParsedAttr::AT_NSReturnsNotRetained:
5178 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5180 case ParsedAttr::AT_CFReturnsRetained:
5181 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5183 case ParsedAttr::AT_NSReturnsRetained:
5184 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5186 case ParsedAttr::AT_OSReturnsRetained:
5187 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5189 case ParsedAttr::AT_OSReturnsNotRetained:
5190 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5195 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5196 const ParsedAttr &Attrs) {
5197 const int EP_ObjCMethod = 1;
5198 const int EP_ObjCProperty = 2;
5200 SourceLocation loc = Attrs.getLoc();
5201 QualType resultType;
5202 if (isa<ObjCMethodDecl>(D))
5203 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5205 resultType = cast<ObjCPropertyDecl>(D)->getType();
5207 if (!resultType->isReferenceType() &&
5208 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5209 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5210 << SourceRange(loc) << Attrs
5211 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5212 << /*non-retainable pointer*/ 2;
5214 // Drop the attribute.
5218 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
5219 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5222 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5223 const ParsedAttr &Attrs) {
5224 const auto *Method = cast<ObjCMethodDecl>(D);
5226 const DeclContext *DC = Method->getDeclContext();
5227 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5228 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5230 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5233 if (Method->getMethodFamily() == OMF_dealloc) {
5234 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5239 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(
5240 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5243 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5244 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5247 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5251 // Typedefs only allow objc_bridge(id) and have some additional checking.
5252 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5253 if (!Parm->Ident->isStr("id")) {
5254 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5258 // Only allow 'cv void *'.
5259 QualType T = TD->getUnderlyingType();
5260 if (!T->isVoidPointerType()) {
5261 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5266 D->addAttr(::new (S.Context)
5267 ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident,
5268 AL.getAttributeSpellingListIndex()));
5271 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5272 const ParsedAttr &AL) {
5273 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5276 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5280 D->addAttr(::new (S.Context)
5281 ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident,
5282 AL.getAttributeSpellingListIndex()));
5285 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5286 const ParsedAttr &AL) {
5287 IdentifierInfo *RelatedClass =
5288 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5289 if (!RelatedClass) {
5290 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5293 IdentifierInfo *ClassMethod =
5294 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5295 IdentifierInfo *InstanceMethod =
5296 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5297 D->addAttr(::new (S.Context)
5298 ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass,
5299 ClassMethod, InstanceMethod,
5300 AL.getAttributeSpellingListIndex()));
5303 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5304 const ParsedAttr &AL) {
5305 DeclContext *Ctx = D->getDeclContext();
5307 // This attribute can only be applied to methods in interfaces or class
5309 if (!isa<ObjCInterfaceDecl>(Ctx) &&
5310 !(isa<ObjCCategoryDecl>(Ctx) &&
5311 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5312 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5316 ObjCInterfaceDecl *IFace;
5317 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5318 IFace = CatDecl->getClassInterface();
5320 IFace = cast<ObjCInterfaceDecl>(Ctx);
5325 IFace->setHasDesignatedInitializers();
5326 D->addAttr(::new (S.Context)
5327 ObjCDesignatedInitializerAttr(AL.getRange(), S.Context,
5328 AL.getAttributeSpellingListIndex()));
5331 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5332 StringRef MetaDataName;
5333 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5335 D->addAttr(::new (S.Context)
5336 ObjCRuntimeNameAttr(AL.getRange(), S.Context,
5338 AL.getAttributeSpellingListIndex()));
5341 // When a user wants to use objc_boxable with a union or struct
5342 // but they don't have access to the declaration (legacy/third-party code)
5343 // then they can 'enable' this feature with a typedef:
5344 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5345 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5346 bool notify = false;
5348 auto *RD = dyn_cast<RecordDecl>(D);
5349 if (RD && RD->getDefinition()) {
5350 RD = RD->getDefinition();
5355 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5356 ObjCBoxableAttr(AL.getRange(), S.Context,
5357 AL.getAttributeSpellingListIndex());
5358 RD->addAttr(BoxableAttr);
5360 // we need to notify ASTReader/ASTWriter about
5361 // modification of existing declaration
5362 if (ASTMutationListener *L = S.getASTMutationListener())
5363 L->AddedAttributeToRecord(BoxableAttr, RD);
5368 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5369 if (hasDeclarator(D)) return;
5371 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5372 << AL.getRange() << AL << ExpectedVariable;
5375 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5376 const ParsedAttr &AL) {
5377 const auto *VD = cast<ValueDecl>(D);
5378 QualType QT = VD->getType();
5380 if (!QT->isDependentType() &&
5381 !QT->isObjCLifetimeType()) {
5382 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5387 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5389 // If we have no lifetime yet, check the lifetime we're presumably
5391 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5392 Lifetime = QT->getObjCARCImplicitLifetime();
5395 case Qualifiers::OCL_None:
5396 assert(QT->isDependentType() &&
5397 "didn't infer lifetime for non-dependent type?");
5400 case Qualifiers::OCL_Weak: // meaningful
5401 case Qualifiers::OCL_Strong: // meaningful
5404 case Qualifiers::OCL_ExplicitNone:
5405 case Qualifiers::OCL_Autoreleasing:
5406 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5407 << (Lifetime == Qualifiers::OCL_Autoreleasing);
5411 D->addAttr(::new (S.Context)
5412 ObjCPreciseLifetimeAttr(AL.getRange(), S.Context,
5413 AL.getAttributeSpellingListIndex()));
5416 //===----------------------------------------------------------------------===//
5417 // Microsoft specific attribute handlers.
5418 //===----------------------------------------------------------------------===//
5420 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5421 unsigned AttrSpellingListIndex, StringRef Uuid) {
5422 if (const auto *UA = D->getAttr<UuidAttr>()) {
5423 if (UA->getGuid().equals_lower(Uuid))
5425 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5426 Diag(Range.getBegin(), diag::note_previous_uuid);
5427 D->dropAttr<UuidAttr>();
5430 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5433 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5434 if (!S.LangOpts.CPlusPlus) {
5435 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5436 << AL << AttributeLangSupport::C;
5441 SourceLocation LiteralLoc;
5442 if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5445 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5446 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5447 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5448 StrRef = StrRef.drop_front().drop_back();
5450 // Validate GUID length.
5451 if (StrRef.size() != 36) {
5452 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5456 for (unsigned i = 0; i < 36; ++i) {
5457 if (i == 8 || i == 13 || i == 18 || i == 23) {
5458 if (StrRef[i] != '-') {
5459 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5462 } else if (!isHexDigit(StrRef[i])) {
5463 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5468 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5469 // the only thing in the [] list, the [] too), and add an insertion of
5470 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5471 // separating attributes nor of the [ and the ] are in the AST.
5472 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5474 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5475 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5477 UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(),
5478 AL.getAttributeSpellingListIndex(), StrRef);
5483 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5484 if (!S.LangOpts.CPlusPlus) {
5485 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5486 << AL << AttributeLangSupport::C;
5489 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5490 D, AL.getRange(), /*BestCase=*/true,
5491 AL.getAttributeSpellingListIndex(),
5492 (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
5495 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5499 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5500 const auto *VD = cast<VarDecl>(D);
5501 if (!S.Context.getTargetInfo().isTLSSupported()) {
5502 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5505 if (VD->getTSCSpec() != TSCS_unspecified) {
5506 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5509 if (VD->hasLocalStorage()) {
5510 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5513 D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context,
5514 AL.getAttributeSpellingListIndex()));
5517 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5518 SmallVector<StringRef, 4> Tags;
5519 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5521 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5523 Tags.push_back(Tag);
5526 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5527 if (!NS->isInline()) {
5528 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5531 if (NS->isAnonymousNamespace()) {
5532 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5535 if (AL.getNumArgs() == 0)
5536 Tags.push_back(NS->getName());
5537 } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5540 // Store tags sorted and without duplicates.
5542 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5544 D->addAttr(::new (S.Context)
5545 AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(),
5546 AL.getAttributeSpellingListIndex()));
5549 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5550 // Check the attribute arguments.
5551 if (AL.getNumArgs() > 1) {
5552 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5557 SourceLocation ArgLoc;
5559 if (AL.getNumArgs() == 0)
5561 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5564 ARMInterruptAttr::InterruptType Kind;
5565 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5566 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5571 unsigned Index = AL.getAttributeSpellingListIndex();
5572 D->addAttr(::new (S.Context)
5573 ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index));
5576 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5577 // MSP430 'interrupt' attribute is applied to
5578 // a function with no parameters and void return type.
5579 if (!isFunctionOrMethod(D)) {
5580 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5581 << "'interrupt'" << ExpectedFunctionOrMethod;
5585 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5586 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5587 << /*MSP430*/ 1 << 0;
5591 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5592 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5593 << /*MSP430*/ 1 << 1;
5597 // The attribute takes one integer argument.
5598 if (!checkAttributeNumArgs(S, AL, 1))
5601 if (!AL.isArgExpr(0)) {
5602 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5603 << AL << AANT_ArgumentIntegerConstant;
5607 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5608 llvm::APSInt NumParams(32);
5609 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5610 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5611 << AL << AANT_ArgumentIntegerConstant
5612 << NumParamsExpr->getSourceRange();
5615 // The argument should be in range 0..63.
5616 unsigned Num = NumParams.getLimitedValue(255);
5618 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5619 << AL << (int)NumParams.getSExtValue()
5620 << NumParamsExpr->getSourceRange();
5624 D->addAttr(::new (S.Context)
5625 MSP430InterruptAttr(AL.getLoc(), S.Context, Num,
5626 AL.getAttributeSpellingListIndex()));
5627 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5630 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5631 // Only one optional argument permitted.
5632 if (AL.getNumArgs() > 1) {
5633 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5638 SourceLocation ArgLoc;
5640 if (AL.getNumArgs() == 0)
5642 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5645 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5646 // a) Must be a function.
5647 // b) Must have no parameters.
5648 // c) Must have the 'void' return type.
5649 // d) Cannot have the 'mips16' attribute, as that instruction set
5650 // lacks the 'eret' instruction.
5651 // e) The attribute itself must either have no argument or one of the
5652 // valid interrupt types, see [MipsInterruptDocs].
5654 if (!isFunctionOrMethod(D)) {
5655 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5656 << "'interrupt'" << ExpectedFunctionOrMethod;
5660 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5661 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5666 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5667 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5672 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
5675 MipsInterruptAttr::InterruptType Kind;
5676 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5677 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5678 << AL << "'" + std::string(Str) + "'";
5682 D->addAttr(::new (S.Context) MipsInterruptAttr(
5683 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
5686 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5687 // Semantic checks for a function with the 'interrupt' attribute.
5688 // a) Must be a function.
5689 // b) Must have the 'void' return type.
5690 // c) Must take 1 or 2 arguments.
5691 // d) The 1st argument must be a pointer.
5692 // e) The 2nd argument (if any) must be an unsigned integer.
5693 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5694 CXXMethodDecl::isStaticOverloadedOperator(
5695 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5696 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5697 << AL << ExpectedFunctionWithProtoType;
5700 // Interrupt handler must have void return type.
5701 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5702 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5703 diag::err_anyx86_interrupt_attribute)
5704 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5710 // Interrupt handler must have 1 or 2 parameters.
5711 unsigned NumParams = getFunctionOrMethodNumParams(D);
5712 if (NumParams < 1 || NumParams > 2) {
5713 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
5714 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5720 // The first argument must be a pointer.
5721 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5722 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5723 diag::err_anyx86_interrupt_attribute)
5724 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5730 // The second argument, if present, must be an unsigned integer.
5732 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5735 if (NumParams == 2 &&
5736 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5737 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5738 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5739 diag::err_anyx86_interrupt_attribute)
5740 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5743 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5746 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5747 AL.getLoc(), S.Context, AL.getAttributeSpellingListIndex()));
5748 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5751 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5752 if (!isFunctionOrMethod(D)) {
5753 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5754 << "'interrupt'" << ExpectedFunction;
5758 if (!checkAttributeNumArgs(S, AL, 0))
5761 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5764 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5765 if (!isFunctionOrMethod(D)) {
5766 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5767 << "'signal'" << ExpectedFunction;
5771 if (!checkAttributeNumArgs(S, AL, 0))
5774 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5777 static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5778 if (!isFunctionOrMethod(D)) {
5779 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5780 << "'import_module'" << ExpectedFunction;
5784 auto *FD = cast<FunctionDecl>(D);
5785 if (FD->isThisDeclarationADefinition()) {
5786 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5791 SourceLocation ArgLoc;
5792 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5795 FD->addAttr(::new (S.Context) WebAssemblyImportModuleAttr(
5796 AL.getRange(), S.Context, Str,
5797 AL.getAttributeSpellingListIndex()));
5800 static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5801 if (!isFunctionOrMethod(D)) {
5802 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5803 << "'import_name'" << ExpectedFunction;
5807 auto *FD = cast<FunctionDecl>(D);
5808 if (FD->isThisDeclarationADefinition()) {
5809 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5814 SourceLocation ArgLoc;
5815 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5818 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(
5819 AL.getRange(), S.Context, Str,
5820 AL.getAttributeSpellingListIndex()));
5823 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
5824 const ParsedAttr &AL) {
5825 // Warn about repeated attributes.
5826 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
5827 S.Diag(AL.getRange().getBegin(),
5828 diag::warn_riscv_repeated_interrupt_attribute);
5829 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
5833 // Check the attribute argument. Argument is optional.
5834 if (!checkAttributeAtMostNumArgs(S, AL, 1))
5838 SourceLocation ArgLoc;
5840 // 'machine'is the default interrupt mode.
5841 if (AL.getNumArgs() == 0)
5843 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5846 // Semantic checks for a function with the 'interrupt' attribute:
5847 // - Must be a function.
5848 // - Must have no parameters.
5849 // - Must have the 'void' return type.
5850 // - The attribute itself must either have no argument or one of the
5851 // valid interrupt types, see [RISCVInterruptDocs].
5853 if (D->getFunctionType() == nullptr) {
5854 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5855 << "'interrupt'" << ExpectedFunction;
5859 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5860 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5861 << /*RISC-V*/ 2 << 0;
5865 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5866 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5867 << /*RISC-V*/ 2 << 1;
5871 RISCVInterruptAttr::InterruptType Kind;
5872 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5873 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5878 D->addAttr(::new (S.Context) RISCVInterruptAttr(
5879 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
5882 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5883 // Dispatch the interrupt attribute based on the current target.
5884 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5885 case llvm::Triple::msp430:
5886 handleMSP430InterruptAttr(S, D, AL);
5888 case llvm::Triple::mipsel:
5889 case llvm::Triple::mips:
5890 handleMipsInterruptAttr(S, D, AL);
5892 case llvm::Triple::x86:
5893 case llvm::Triple::x86_64:
5894 handleAnyX86InterruptAttr(S, D, AL);
5896 case llvm::Triple::avr:
5897 handleAVRInterruptAttr(S, D, AL);
5899 case llvm::Triple::riscv32:
5900 case llvm::Triple::riscv64:
5901 handleRISCVInterruptAttr(S, D, AL);
5904 handleARMInterruptAttr(S, D, AL);
5910 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
5911 const AMDGPUFlatWorkGroupSizeAttr &Attr) {
5912 // Accept template arguments for now as they depend on something else.
5913 // We'll get to check them when they eventually get instantiated.
5914 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
5918 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
5922 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
5925 if (Min == 0 && Max != 0) {
5926 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5931 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5939 void Sema::addAMDGPUFlatWorkGroupSizeAttr(SourceRange AttrRange, Decl *D,
5940 Expr *MinExpr, Expr *MaxExpr,
5941 unsigned SpellingListIndex) {
5942 AMDGPUFlatWorkGroupSizeAttr TmpAttr(AttrRange, Context, MinExpr, MaxExpr,
5945 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
5948 D->addAttr(::new (Context) AMDGPUFlatWorkGroupSizeAttr(
5949 AttrRange, Context, MinExpr, MaxExpr, SpellingListIndex));
5952 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5953 const ParsedAttr &AL) {
5954 Expr *MinExpr = AL.getArgAsExpr(0);
5955 Expr *MaxExpr = AL.getArgAsExpr(1);
5957 S.addAMDGPUFlatWorkGroupSizeAttr(AL.getRange(), D, MinExpr, MaxExpr,
5958 AL.getAttributeSpellingListIndex());
5961 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
5963 const AMDGPUWavesPerEUAttr &Attr) {
5964 if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
5965 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
5968 // Accept template arguments for now as they depend on something else.
5969 // We'll get to check them when they eventually get instantiated.
5970 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
5974 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
5978 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
5981 if (Min == 0 && Max != 0) {
5982 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5986 if (Max != 0 && Min > Max) {
5987 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5995 void Sema::addAMDGPUWavesPerEUAttr(SourceRange AttrRange, Decl *D,
5996 Expr *MinExpr, Expr *MaxExpr,
5997 unsigned SpellingListIndex) {
5998 AMDGPUWavesPerEUAttr TmpAttr(AttrRange, Context, MinExpr, MaxExpr,
6001 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
6004 D->addAttr(::new (Context) AMDGPUWavesPerEUAttr(AttrRange, Context, MinExpr,
6005 MaxExpr, SpellingListIndex));
6008 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6009 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
6010 !checkAttributeAtMostNumArgs(S, AL, 2))
6013 Expr *MinExpr = AL.getArgAsExpr(0);
6014 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
6016 S.addAMDGPUWavesPerEUAttr(AL.getRange(), D, MinExpr, MaxExpr,
6017 AL.getAttributeSpellingListIndex());
6020 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6021 uint32_t NumSGPR = 0;
6022 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
6023 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
6026 D->addAttr(::new (S.Context)
6027 AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR,
6028 AL.getAttributeSpellingListIndex()));
6031 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6032 uint32_t NumVGPR = 0;
6033 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
6034 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
6037 D->addAttr(::new (S.Context)
6038 AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR,
6039 AL.getAttributeSpellingListIndex()));
6042 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
6043 const ParsedAttr &AL) {
6044 // If we try to apply it to a function pointer, don't warn, but don't
6045 // do anything, either. It doesn't matter anyway, because there's nothing
6046 // special about calling a force_align_arg_pointer function.
6047 const auto *VD = dyn_cast<ValueDecl>(D);
6048 if (VD && VD->getType()->isFunctionPointerType())
6050 // Also don't warn on function pointer typedefs.
6051 const auto *TD = dyn_cast<TypedefNameDecl>(D);
6052 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
6053 TD->getUnderlyingType()->isFunctionType()))
6055 // Attribute can only be applied to function types.
6056 if (!isa<FunctionDecl>(D)) {
6057 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6058 << AL << ExpectedFunction;
6062 D->addAttr(::new (S.Context)
6063 X86ForceAlignArgPointerAttr(AL.getRange(), S.Context,
6064 AL.getAttributeSpellingListIndex()));
6067 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
6069 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
6070 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
6073 // TODO: Investigate what happens with the next major version of MSVC.
6074 if (Version != LangOptions::MSVC2015 / 100) {
6075 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
6076 << AL << Version << VersionExpr->getSourceRange();
6080 // The attribute expects a "major" version number like 19, but new versions of
6081 // MSVC have moved to updating the "minor", or less significant numbers, so we
6082 // have to multiply by 100 now.
6085 D->addAttr(::new (S.Context)
6086 LayoutVersionAttr(AL.getRange(), S.Context, Version,
6087 AL.getAttributeSpellingListIndex()));
6090 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
6091 unsigned AttrSpellingListIndex) {
6092 if (D->hasAttr<DLLExportAttr>()) {
6093 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
6097 if (D->hasAttr<DLLImportAttr>())
6100 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
6103 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
6104 unsigned AttrSpellingListIndex) {
6105 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
6106 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
6107 D->dropAttr<DLLImportAttr>();
6110 if (D->hasAttr<DLLExportAttr>())
6113 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
6116 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6117 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
6118 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6119 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
6123 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
6124 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
6125 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6126 // MinGW doesn't allow dllimport on inline functions.
6127 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
6133 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
6134 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6135 MD->getParent()->isLambda()) {
6136 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
6141 unsigned Index = A.getAttributeSpellingListIndex();
6142 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
6143 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
6144 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
6146 D->addAttr(NewAttr);
6150 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
6151 unsigned AttrSpellingListIndex,
6152 MSInheritanceAttr::Spelling SemanticSpelling) {
6153 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
6154 if (IA->getSemanticSpelling() == SemanticSpelling)
6156 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
6157 << 1 /*previous declaration*/;
6158 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
6159 D->dropAttr<MSInheritanceAttr>();
6162 auto *RD = cast<CXXRecordDecl>(D);
6163 if (RD->hasDefinition()) {
6164 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
6165 SemanticSpelling)) {
6169 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
6170 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
6171 << 1 /*partial specialization*/;
6174 if (RD->getDescribedClassTemplate()) {
6175 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
6176 << 0 /*primary template*/;
6181 return ::new (Context)
6182 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
6185 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6186 // The capability attributes take a single string parameter for the name of
6187 // the capability they represent. The lockable attribute does not take any
6188 // parameters. However, semantically, both attributes represent the same
6189 // concept, and so they use the same semantic attribute. Eventually, the
6190 // lockable attribute will be removed.
6192 // For backward compatibility, any capability which has no specified string
6193 // literal will be considered a "mutex."
6194 StringRef N("mutex");
6195 SourceLocation LiteralLoc;
6196 if (AL.getKind() == ParsedAttr::AT_Capability &&
6197 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
6200 // Currently, there are only two names allowed for a capability: role and
6201 // mutex (case insensitive). Diagnose other capability names.
6202 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
6203 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
6205 D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N,
6206 AL.getAttributeSpellingListIndex()));
6209 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6210 SmallVector<Expr*, 1> Args;
6211 if (!checkLockFunAttrCommon(S, D, AL, Args))
6214 D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context,
6215 Args.data(), Args.size(),
6216 AL.getAttributeSpellingListIndex()));
6219 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
6220 const ParsedAttr &AL) {
6221 SmallVector<Expr*, 1> Args;
6222 if (!checkLockFunAttrCommon(S, D, AL, Args))
6225 D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(),
6227 Args.data(), Args.size(),
6228 AL.getAttributeSpellingListIndex()));
6231 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
6232 const ParsedAttr &AL) {
6233 SmallVector<Expr*, 2> Args;
6234 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
6237 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(),
6242 AL.getAttributeSpellingListIndex()));
6245 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6246 const ParsedAttr &AL) {
6247 // Check that all arguments are lockable objects.
6248 SmallVector<Expr *, 1> Args;
6249 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
6251 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
6252 AL.getRange(), S.Context, Args.data(), Args.size(),
6253 AL.getAttributeSpellingListIndex()));
6256 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6257 const ParsedAttr &AL) {
6258 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6261 // check that all arguments are lockable objects
6262 SmallVector<Expr*, 1> Args;
6263 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6267 RequiresCapabilityAttr *RCA = ::new (S.Context)
6268 RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(),
6269 Args.size(), AL.getAttributeSpellingListIndex());
6274 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6275 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
6276 if (NSD->isAnonymousNamespace()) {
6277 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
6278 // Do not want to attach the attribute to the namespace because that will
6279 // cause confusing diagnostic reports for uses of declarations within the
6285 // Handle the cases where the attribute has a text message.
6286 StringRef Str, Replacement;
6287 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
6288 !S.checkStringLiteralArgumentAttr(AL, 0, Str))
6291 // Only support a single optional message for Declspec and CXX11.
6292 if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
6293 checkAttributeAtMostNumArgs(S, AL, 1);
6294 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
6295 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
6298 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
6299 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
6301 D->addAttr(::new (S.Context)
6302 DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement,
6303 AL.getAttributeSpellingListIndex()));
6306 static bool isGlobalVar(const Decl *D) {
6307 if (const auto *S = dyn_cast<VarDecl>(D))
6308 return S->hasGlobalStorage();
6312 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6313 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6316 std::vector<StringRef> Sanitizers;
6318 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6319 StringRef SanitizerName;
6320 SourceLocation LiteralLoc;
6322 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
6325 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
6327 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
6328 else if (isGlobalVar(D) && SanitizerName != "address")
6329 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6330 << AL << ExpectedFunctionOrMethod;
6331 Sanitizers.push_back(SanitizerName);
6334 D->addAttr(::new (S.Context) NoSanitizeAttr(
6335 AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
6336 AL.getAttributeSpellingListIndex()));
6339 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
6340 const ParsedAttr &AL) {
6341 StringRef AttrName = AL.getName()->getName();
6342 normalizeName(AttrName);
6343 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
6344 .Case("no_address_safety_analysis", "address")
6345 .Case("no_sanitize_address", "address")
6346 .Case("no_sanitize_thread", "thread")
6347 .Case("no_sanitize_memory", "memory");
6348 if (isGlobalVar(D) && SanitizerName != "address")
6349 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6350 << AL << ExpectedFunction;
6352 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
6353 // NoSanitizeAttr object; but we need to calculate the correct spelling list
6354 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
6355 // has the same spellings as the index for NoSanitizeAttr. We don't have a
6356 // general way to "translate" between the two, so this hack attempts to work
6357 // around the issue with hard-coded indicies. This is critical for calling
6358 // getSpelling() or prettyPrint() on the resulting semantic attribute object
6359 // without failing assertions.
6360 unsigned TranslatedSpellingIndex = 0;
6361 if (AL.isC2xAttribute() || AL.isCXX11Attribute())
6362 TranslatedSpellingIndex = 1;
6364 D->addAttr(::new (S.Context) NoSanitizeAttr(
6365 AL.getRange(), S.Context, &SanitizerName, 1, TranslatedSpellingIndex));
6368 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6369 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
6370 D->addAttr(Internal);
6373 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6374 if (S.LangOpts.OpenCLVersion != 200)
6375 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
6376 << AL << "2.0" << 0;
6378 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
6382 /// Handles semantic checking for features that are common to all attributes,
6383 /// such as checking whether a parameter was properly specified, or the correct
6384 /// number of arguments were passed, etc.
6385 static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
6386 const ParsedAttr &AL) {
6387 // Several attributes carry different semantics than the parsing requires, so
6388 // those are opted out of the common argument checks.
6390 // We also bail on unknown and ignored attributes because those are handled
6391 // as part of the target-specific handling logic.
6392 if (AL.getKind() == ParsedAttr::UnknownAttribute)
6394 // Check whether the attribute requires specific language extensions to be
6396 if (!AL.diagnoseLangOpts(S))
6398 // Check whether the attribute appertains to the given subject.
6399 if (!AL.diagnoseAppertainsTo(S, D))
6401 if (AL.hasCustomParsing())
6404 if (AL.getMinArgs() == AL.getMaxArgs()) {
6405 // If there are no optional arguments, then checking for the argument count
6407 if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
6410 // There are optional arguments, so checking is slightly more involved.
6411 if (AL.getMinArgs() &&
6412 !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
6414 else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
6415 !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
6419 if (S.CheckAttrTarget(AL))
6425 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6426 if (D->isInvalidDecl())
6429 // Check if there is only one access qualifier.
6430 if (D->hasAttr<OpenCLAccessAttr>()) {
6431 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
6432 AL.getSemanticSpelling()) {
6433 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
6434 << AL.getName()->getName() << AL.getRange();
6436 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
6437 << D->getSourceRange();
6438 D->setInvalidDecl(true);
6443 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
6444 // image object can be read and written.
6445 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
6446 // object. Using the read_write (or __read_write) qualifier with the pipe
6447 // qualifier is a compilation error.
6448 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
6449 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
6450 if (AL.getName()->getName().find("read_write") != StringRef::npos) {
6451 if ((!S.getLangOpts().OpenCLCPlusPlus &&
6452 S.getLangOpts().OpenCLVersion < 200) ||
6453 DeclTy->isPipeType()) {
6454 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
6455 << AL << PDecl->getType() << DeclTy->isImageType();
6456 D->setInvalidDecl(true);
6462 D->addAttr(::new (S.Context) OpenCLAccessAttr(
6463 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
6466 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6467 if (!cast<VarDecl>(D)->hasGlobalStorage()) {
6468 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
6469 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
6473 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
6474 handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
6476 handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
6479 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6480 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
6481 "uninitialized is only valid on automatic duration variables");
6482 unsigned Index = AL.getAttributeSpellingListIndex();
6483 D->addAttr(::new (S.Context)
6484 UninitializedAttr(AL.getLoc(), S.Context, Index));
6487 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
6488 bool DiagnoseFailure) {
6489 QualType Ty = VD->getType();
6490 if (!Ty->isObjCRetainableType()) {
6491 if (DiagnoseFailure) {
6492 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6498 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
6500 // Sema::inferObjCARCLifetime must run after processing decl attributes
6501 // (because __block lowers to an attribute), so if the lifetime hasn't been
6502 // explicitly specified, infer it locally now.
6503 if (LifetimeQual == Qualifiers::OCL_None)
6504 LifetimeQual = Ty->getObjCARCImplicitLifetime();
6506 // The attributes only really makes sense for __strong variables; ignore any
6507 // attempts to annotate a parameter with any other lifetime qualifier.
6508 if (LifetimeQual != Qualifiers::OCL_Strong) {
6509 if (DiagnoseFailure) {
6510 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6516 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
6517 // to ensure that the variable is 'const' so that we can error on
6518 // modification, which can otherwise over-release.
6519 VD->setType(Ty.withConst());
6520 VD->setARCPseudoStrong(true);
6524 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
6525 const ParsedAttr &AL) {
6526 if (auto *VD = dyn_cast<VarDecl>(D)) {
6527 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
6528 if (!VD->hasLocalStorage()) {
6529 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6534 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
6537 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6541 // If D is a function-like declaration (method, block, or function), then we
6542 // make every parameter psuedo-strong.
6543 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6544 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
6545 QualType Ty = PVD->getType();
6547 // If a user wrote a parameter with __strong explicitly, then assume they
6548 // want "real" strong semantics for that parameter. This works because if
6549 // the parameter was written with __strong, then the strong qualifier will
6551 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
6552 Qualifiers::OCL_Strong)
6555 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
6557 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6560 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6561 // Check that the return type is a `typedef int kern_return_t` or a typedef
6562 // around it, because otherwise MIG convention checks make no sense.
6563 // BlockDecl doesn't store a return type, so it's annoying to check,
6564 // so let's skip it for now.
6565 if (!isa<BlockDecl>(D)) {
6566 QualType T = getFunctionOrMethodResultType(D);
6567 bool IsKernReturnT = false;
6568 while (const auto *TT = T->getAs<TypedefType>()) {
6569 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
6572 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
6573 S.Diag(D->getBeginLoc(),
6574 diag::warn_mig_server_routine_does_not_return_kern_return_t);
6579 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
6582 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6583 // Warn if the return type is not a pointer or reference type.
6584 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6585 QualType RetTy = FD->getReturnType();
6586 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
6587 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
6588 << AL.getRange() << RetTy;
6593 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
6596 //===----------------------------------------------------------------------===//
6597 // Top Level Sema Entry Points
6598 //===----------------------------------------------------------------------===//
6600 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
6601 /// the attribute applies to decls. If the attribute is a type attribute, just
6602 /// silently ignore it if a GNU attribute.
6603 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
6604 const ParsedAttr &AL,
6605 bool IncludeCXX11Attributes) {
6606 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
6609 // Ignore C++11 attributes on declarator chunks: they appertain to the type
6611 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
6614 // Unknown attributes are automatically warned on. Target-specific attributes
6615 // which do not apply to the current target architecture are treated as
6616 // though they were unknown attributes.
6617 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
6618 !AL.existsInTarget(S.Context.getTargetInfo())) {
6620 AL.isDeclspecAttribute()
6621 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
6622 : (unsigned)diag::warn_unknown_attribute_ignored)
6627 if (handleCommonAttributeFeatures(S, D, AL))
6630 switch (AL.getKind()) {
6632 if (!AL.isStmtAttr()) {
6633 // Type attributes are handled elsewhere; silently move on.
6634 assert(AL.isTypeAttr() && "Non-type attribute not handled");
6637 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6638 << AL << D->getLocation();
6640 case ParsedAttr::AT_Interrupt:
6641 handleInterruptAttr(S, D, AL);
6643 case ParsedAttr::AT_X86ForceAlignArgPointer:
6644 handleX86ForceAlignArgPointerAttr(S, D, AL);
6646 case ParsedAttr::AT_DLLExport:
6647 case ParsedAttr::AT_DLLImport:
6648 handleDLLAttr(S, D, AL);
6650 case ParsedAttr::AT_Mips16:
6651 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6652 MipsInterruptAttr>(S, D, AL);
6654 case ParsedAttr::AT_NoMips16:
6655 handleSimpleAttribute<NoMips16Attr>(S, D, AL);
6657 case ParsedAttr::AT_MicroMips:
6658 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
6660 case ParsedAttr::AT_NoMicroMips:
6661 handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
6663 case ParsedAttr::AT_MipsLongCall:
6664 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6667 case ParsedAttr::AT_MipsShortCall:
6668 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6671 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
6672 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
6674 case ParsedAttr::AT_AMDGPUWavesPerEU:
6675 handleAMDGPUWavesPerEUAttr(S, D, AL);
6677 case ParsedAttr::AT_AMDGPUNumSGPR:
6678 handleAMDGPUNumSGPRAttr(S, D, AL);
6680 case ParsedAttr::AT_AMDGPUNumVGPR:
6681 handleAMDGPUNumVGPRAttr(S, D, AL);
6683 case ParsedAttr::AT_AVRSignal:
6684 handleAVRSignalAttr(S, D, AL);
6686 case ParsedAttr::AT_WebAssemblyImportModule:
6687 handleWebAssemblyImportModuleAttr(S, D, AL);
6689 case ParsedAttr::AT_WebAssemblyImportName:
6690 handleWebAssemblyImportNameAttr(S, D, AL);
6692 case ParsedAttr::AT_IBAction:
6693 handleSimpleAttribute<IBActionAttr>(S, D, AL);
6695 case ParsedAttr::AT_IBOutlet:
6696 handleIBOutlet(S, D, AL);
6698 case ParsedAttr::AT_IBOutletCollection:
6699 handleIBOutletCollection(S, D, AL);
6701 case ParsedAttr::AT_IFunc:
6702 handleIFuncAttr(S, D, AL);
6704 case ParsedAttr::AT_Alias:
6705 handleAliasAttr(S, D, AL);
6707 case ParsedAttr::AT_Aligned:
6708 handleAlignedAttr(S, D, AL);
6710 case ParsedAttr::AT_AlignValue:
6711 handleAlignValueAttr(S, D, AL);
6713 case ParsedAttr::AT_AllocSize:
6714 handleAllocSizeAttr(S, D, AL);
6716 case ParsedAttr::AT_AlwaysInline:
6717 handleAlwaysInlineAttr(S, D, AL);
6719 case ParsedAttr::AT_Artificial:
6720 handleSimpleAttribute<ArtificialAttr>(S, D, AL);
6722 case ParsedAttr::AT_AnalyzerNoReturn:
6723 handleAnalyzerNoReturnAttr(S, D, AL);
6725 case ParsedAttr::AT_TLSModel:
6726 handleTLSModelAttr(S, D, AL);
6728 case ParsedAttr::AT_Annotate:
6729 handleAnnotateAttr(S, D, AL);
6731 case ParsedAttr::AT_Availability:
6732 handleAvailabilityAttr(S, D, AL);
6734 case ParsedAttr::AT_CarriesDependency:
6735 handleDependencyAttr(S, scope, D, AL);
6737 case ParsedAttr::AT_CPUDispatch:
6738 case ParsedAttr::AT_CPUSpecific:
6739 handleCPUSpecificAttr(S, D, AL);
6741 case ParsedAttr::AT_Common:
6742 handleCommonAttr(S, D, AL);
6744 case ParsedAttr::AT_CUDAConstant:
6745 handleConstantAttr(S, D, AL);
6747 case ParsedAttr::AT_PassObjectSize:
6748 handlePassObjectSizeAttr(S, D, AL);
6750 case ParsedAttr::AT_Constructor:
6751 handleConstructorAttr(S, D, AL);
6753 case ParsedAttr::AT_CXX11NoReturn:
6754 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
6756 case ParsedAttr::AT_Deprecated:
6757 handleDeprecatedAttr(S, D, AL);
6759 case ParsedAttr::AT_Destructor:
6760 handleDestructorAttr(S, D, AL);
6762 case ParsedAttr::AT_EnableIf:
6763 handleEnableIfAttr(S, D, AL);
6765 case ParsedAttr::AT_DiagnoseIf:
6766 handleDiagnoseIfAttr(S, D, AL);
6768 case ParsedAttr::AT_ExtVectorType:
6769 handleExtVectorTypeAttr(S, D, AL);
6771 case ParsedAttr::AT_ExternalSourceSymbol:
6772 handleExternalSourceSymbolAttr(S, D, AL);
6774 case ParsedAttr::AT_MinSize:
6775 handleMinSizeAttr(S, D, AL);
6777 case ParsedAttr::AT_OptimizeNone:
6778 handleOptimizeNoneAttr(S, D, AL);
6780 case ParsedAttr::AT_FlagEnum:
6781 handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
6783 case ParsedAttr::AT_EnumExtensibility:
6784 handleEnumExtensibilityAttr(S, D, AL);
6786 case ParsedAttr::AT_Flatten:
6787 handleSimpleAttribute<FlattenAttr>(S, D, AL);
6789 case ParsedAttr::AT_Format:
6790 handleFormatAttr(S, D, AL);
6792 case ParsedAttr::AT_FormatArg:
6793 handleFormatArgAttr(S, D, AL);
6795 case ParsedAttr::AT_Callback:
6796 handleCallbackAttr(S, D, AL);
6798 case ParsedAttr::AT_CUDAGlobal:
6799 handleGlobalAttr(S, D, AL);
6801 case ParsedAttr::AT_CUDADevice:
6802 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6805 case ParsedAttr::AT_CUDAHost:
6806 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
6808 case ParsedAttr::AT_HIPPinnedShadow:
6809 handleSimpleAttributeWithExclusions<HIPPinnedShadowAttr, CUDADeviceAttr,
6810 CUDAConstantAttr>(S, D, AL);
6812 case ParsedAttr::AT_GNUInline:
6813 handleGNUInlineAttr(S, D, AL);
6815 case ParsedAttr::AT_CUDALaunchBounds:
6816 handleLaunchBoundsAttr(S, D, AL);
6818 case ParsedAttr::AT_Restrict:
6819 handleRestrictAttr(S, D, AL);
6821 case ParsedAttr::AT_LifetimeBound:
6822 handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL);
6824 case ParsedAttr::AT_MayAlias:
6825 handleSimpleAttribute<MayAliasAttr>(S, D, AL);
6827 case ParsedAttr::AT_Mode:
6828 handleModeAttr(S, D, AL);
6830 case ParsedAttr::AT_NoAlias:
6831 handleSimpleAttribute<NoAliasAttr>(S, D, AL);
6833 case ParsedAttr::AT_NoCommon:
6834 handleSimpleAttribute<NoCommonAttr>(S, D, AL);
6836 case ParsedAttr::AT_NoSplitStack:
6837 handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
6839 case ParsedAttr::AT_NoUniqueAddress:
6840 handleSimpleAttribute<NoUniqueAddressAttr>(S, D, AL);
6842 case ParsedAttr::AT_NonNull:
6843 if (auto *PVD = dyn_cast<ParmVarDecl>(D))
6844 handleNonNullAttrParameter(S, PVD, AL);
6846 handleNonNullAttr(S, D, AL);
6848 case ParsedAttr::AT_ReturnsNonNull:
6849 handleReturnsNonNullAttr(S, D, AL);
6851 case ParsedAttr::AT_NoEscape:
6852 handleNoEscapeAttr(S, D, AL);
6854 case ParsedAttr::AT_AssumeAligned:
6855 handleAssumeAlignedAttr(S, D, AL);
6857 case ParsedAttr::AT_AllocAlign:
6858 handleAllocAlignAttr(S, D, AL);
6860 case ParsedAttr::AT_Overloadable:
6861 handleSimpleAttribute<OverloadableAttr>(S, D, AL);
6863 case ParsedAttr::AT_Ownership:
6864 handleOwnershipAttr(S, D, AL);
6866 case ParsedAttr::AT_Cold:
6867 handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
6869 case ParsedAttr::AT_Hot:
6870 handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
6872 case ParsedAttr::AT_Naked:
6873 handleNakedAttr(S, D, AL);
6875 case ParsedAttr::AT_NoReturn:
6876 handleNoReturnAttr(S, D, AL);
6878 case ParsedAttr::AT_AnyX86NoCfCheck:
6879 handleNoCfCheckAttr(S, D, AL);
6881 case ParsedAttr::AT_NoThrow:
6882 if (!AL.isUsedAsTypeAttr())
6883 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
6885 case ParsedAttr::AT_CUDAShared:
6886 handleSharedAttr(S, D, AL);
6888 case ParsedAttr::AT_VecReturn:
6889 handleVecReturnAttr(S, D, AL);
6891 case ParsedAttr::AT_ObjCOwnership:
6892 handleObjCOwnershipAttr(S, D, AL);
6894 case ParsedAttr::AT_ObjCPreciseLifetime:
6895 handleObjCPreciseLifetimeAttr(S, D, AL);
6897 case ParsedAttr::AT_ObjCReturnsInnerPointer:
6898 handleObjCReturnsInnerPointerAttr(S, D, AL);
6900 case ParsedAttr::AT_ObjCRequiresSuper:
6901 handleObjCRequiresSuperAttr(S, D, AL);
6903 case ParsedAttr::AT_ObjCBridge:
6904 handleObjCBridgeAttr(S, D, AL);
6906 case ParsedAttr::AT_ObjCBridgeMutable:
6907 handleObjCBridgeMutableAttr(S, D, AL);
6909 case ParsedAttr::AT_ObjCBridgeRelated:
6910 handleObjCBridgeRelatedAttr(S, D, AL);
6912 case ParsedAttr::AT_ObjCDesignatedInitializer:
6913 handleObjCDesignatedInitializer(S, D, AL);
6915 case ParsedAttr::AT_ObjCRuntimeName:
6916 handleObjCRuntimeName(S, D, AL);
6918 case ParsedAttr::AT_ObjCRuntimeVisible:
6919 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
6921 case ParsedAttr::AT_ObjCBoxable:
6922 handleObjCBoxable(S, D, AL);
6924 case ParsedAttr::AT_CFAuditedTransfer:
6925 handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
6926 CFUnknownTransferAttr>(S, D, AL);
6928 case ParsedAttr::AT_CFUnknownTransfer:
6929 handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
6930 CFAuditedTransferAttr>(S, D, AL);
6932 case ParsedAttr::AT_CFConsumed:
6933 case ParsedAttr::AT_NSConsumed:
6934 case ParsedAttr::AT_OSConsumed:
6935 S.AddXConsumedAttr(D, AL.getRange(), AL.getAttributeSpellingListIndex(),
6936 parsedAttrToRetainOwnershipKind(AL),
6937 /*IsTemplateInstantiation=*/false);
6939 case ParsedAttr::AT_NSConsumesSelf:
6940 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
6942 case ParsedAttr::AT_OSConsumesThis:
6943 handleSimpleAttribute<OSConsumesThisAttr>(S, D, AL);
6945 case ParsedAttr::AT_OSReturnsRetainedOnZero:
6946 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
6947 S, D, AL, isValidOSObjectOutParameter(D),
6948 diag::warn_ns_attribute_wrong_parameter_type,
6949 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
6951 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
6952 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
6953 S, D, AL, isValidOSObjectOutParameter(D),
6954 diag::warn_ns_attribute_wrong_parameter_type,
6955 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
6957 case ParsedAttr::AT_NSReturnsAutoreleased:
6958 case ParsedAttr::AT_NSReturnsNotRetained:
6959 case ParsedAttr::AT_NSReturnsRetained:
6960 case ParsedAttr::AT_CFReturnsNotRetained:
6961 case ParsedAttr::AT_CFReturnsRetained:
6962 case ParsedAttr::AT_OSReturnsNotRetained:
6963 case ParsedAttr::AT_OSReturnsRetained:
6964 handleXReturnsXRetainedAttr(S, D, AL);
6966 case ParsedAttr::AT_WorkGroupSizeHint:
6967 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
6969 case ParsedAttr::AT_ReqdWorkGroupSize:
6970 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
6972 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
6973 handleSubGroupSize(S, D, AL);
6975 case ParsedAttr::AT_VecTypeHint:
6976 handleVecTypeHint(S, D, AL);
6978 case ParsedAttr::AT_RequireConstantInit:
6979 handleSimpleAttribute<RequireConstantInitAttr>(S, D, AL);
6981 case ParsedAttr::AT_InitPriority:
6982 handleInitPriorityAttr(S, D, AL);
6984 case ParsedAttr::AT_Packed:
6985 handlePackedAttr(S, D, AL);
6987 case ParsedAttr::AT_Section:
6988 handleSectionAttr(S, D, AL);
6990 case ParsedAttr::AT_SpeculativeLoadHardening:
6991 handleSimpleAttributeWithExclusions<SpeculativeLoadHardeningAttr,
6992 NoSpeculativeLoadHardeningAttr>(S, D,
6995 case ParsedAttr::AT_NoSpeculativeLoadHardening:
6996 handleSimpleAttributeWithExclusions<NoSpeculativeLoadHardeningAttr,
6997 SpeculativeLoadHardeningAttr>(S, D, AL);
6999 case ParsedAttr::AT_CodeSeg:
7000 handleCodeSegAttr(S, D, AL);
7002 case ParsedAttr::AT_Target:
7003 handleTargetAttr(S, D, AL);
7005 case ParsedAttr::AT_MinVectorWidth:
7006 handleMinVectorWidthAttr(S, D, AL);
7008 case ParsedAttr::AT_Unavailable:
7009 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
7011 case ParsedAttr::AT_ArcWeakrefUnavailable:
7012 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
7014 case ParsedAttr::AT_ObjCRootClass:
7015 handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL);
7017 case ParsedAttr::AT_ObjCNonLazyClass:
7018 handleSimpleAttribute<ObjCNonLazyClassAttr>(S, D, AL);
7020 case ParsedAttr::AT_ObjCSubclassingRestricted:
7021 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
7023 case ParsedAttr::AT_ObjCClassStub:
7024 handleSimpleAttribute<ObjCClassStubAttr>(S, D, AL);
7026 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
7027 handleObjCSuppresProtocolAttr(S, D, AL);
7029 case ParsedAttr::AT_ObjCRequiresPropertyDefs:
7030 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
7032 case ParsedAttr::AT_Unused:
7033 handleUnusedAttr(S, D, AL);
7035 case ParsedAttr::AT_ReturnsTwice:
7036 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
7038 case ParsedAttr::AT_NotTailCalled:
7039 handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
7042 case ParsedAttr::AT_DisableTailCalls:
7043 handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
7046 case ParsedAttr::AT_Used:
7047 handleSimpleAttribute<UsedAttr>(S, D, AL);
7049 case ParsedAttr::AT_Visibility:
7050 handleVisibilityAttr(S, D, AL, false);
7052 case ParsedAttr::AT_TypeVisibility:
7053 handleVisibilityAttr(S, D, AL, true);
7055 case ParsedAttr::AT_WarnUnused:
7056 handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
7058 case ParsedAttr::AT_WarnUnusedResult:
7059 handleWarnUnusedResult(S, D, AL);
7061 case ParsedAttr::AT_Weak:
7062 handleSimpleAttribute<WeakAttr>(S, D, AL);
7064 case ParsedAttr::AT_WeakRef:
7065 handleWeakRefAttr(S, D, AL);
7067 case ParsedAttr::AT_WeakImport:
7068 handleWeakImportAttr(S, D, AL);
7070 case ParsedAttr::AT_TransparentUnion:
7071 handleTransparentUnionAttr(S, D, AL);
7073 case ParsedAttr::AT_ObjCException:
7074 handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
7076 case ParsedAttr::AT_ObjCMethodFamily:
7077 handleObjCMethodFamilyAttr(S, D, AL);
7079 case ParsedAttr::AT_ObjCNSObject:
7080 handleObjCNSObject(S, D, AL);
7082 case ParsedAttr::AT_ObjCIndependentClass:
7083 handleObjCIndependentClass(S, D, AL);
7085 case ParsedAttr::AT_Blocks:
7086 handleBlocksAttr(S, D, AL);
7088 case ParsedAttr::AT_Sentinel:
7089 handleSentinelAttr(S, D, AL);
7091 case ParsedAttr::AT_Const:
7092 handleSimpleAttribute<ConstAttr>(S, D, AL);
7094 case ParsedAttr::AT_Pure:
7095 handleSimpleAttribute<PureAttr>(S, D, AL);
7097 case ParsedAttr::AT_Cleanup:
7098 handleCleanupAttr(S, D, AL);
7100 case ParsedAttr::AT_NoDebug:
7101 handleNoDebugAttr(S, D, AL);
7103 case ParsedAttr::AT_NoDuplicate:
7104 handleSimpleAttribute<NoDuplicateAttr>(S, D, AL);
7106 case ParsedAttr::AT_Convergent:
7107 handleSimpleAttribute<ConvergentAttr>(S, D, AL);
7109 case ParsedAttr::AT_NoInline:
7110 handleSimpleAttribute<NoInlineAttr>(S, D, AL);
7112 case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg.
7113 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL);
7115 case ParsedAttr::AT_NoStackProtector:
7116 // Interacts with -fstack-protector options.
7117 handleSimpleAttribute<NoStackProtectorAttr>(S, D, AL);
7119 case ParsedAttr::AT_StdCall:
7120 case ParsedAttr::AT_CDecl:
7121 case ParsedAttr::AT_FastCall:
7122 case ParsedAttr::AT_ThisCall:
7123 case ParsedAttr::AT_Pascal:
7124 case ParsedAttr::AT_RegCall:
7125 case ParsedAttr::AT_SwiftCall:
7126 case ParsedAttr::AT_VectorCall:
7127 case ParsedAttr::AT_MSABI:
7128 case ParsedAttr::AT_SysVABI:
7129 case ParsedAttr::AT_Pcs:
7130 case ParsedAttr::AT_IntelOclBicc:
7131 case ParsedAttr::AT_PreserveMost:
7132 case ParsedAttr::AT_PreserveAll:
7133 case ParsedAttr::AT_AArch64VectorPcs:
7134 handleCallConvAttr(S, D, AL);
7136 case ParsedAttr::AT_Suppress:
7137 handleSuppressAttr(S, D, AL);
7139 case ParsedAttr::AT_OpenCLKernel:
7140 handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL);
7142 case ParsedAttr::AT_OpenCLAccess:
7143 handleOpenCLAccessAttr(S, D, AL);
7145 case ParsedAttr::AT_OpenCLNoSVM:
7146 handleOpenCLNoSVMAttr(S, D, AL);
7148 case ParsedAttr::AT_SwiftContext:
7149 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftContext);
7151 case ParsedAttr::AT_SwiftErrorResult:
7152 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftErrorResult);
7154 case ParsedAttr::AT_SwiftIndirectResult:
7155 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftIndirectResult);
7157 case ParsedAttr::AT_InternalLinkage:
7158 handleInternalLinkageAttr(S, D, AL);
7160 case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
7161 handleSimpleAttribute<ExcludeFromExplicitInstantiationAttr>(S, D, AL);
7163 case ParsedAttr::AT_LTOVisibilityPublic:
7164 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL);
7167 // Microsoft attributes:
7168 case ParsedAttr::AT_EmptyBases:
7169 handleSimpleAttribute<EmptyBasesAttr>(S, D, AL);
7171 case ParsedAttr::AT_LayoutVersion:
7172 handleLayoutVersion(S, D, AL);
7174 case ParsedAttr::AT_TrivialABI:
7175 handleSimpleAttribute<TrivialABIAttr>(S, D, AL);
7177 case ParsedAttr::AT_MSNoVTable:
7178 handleSimpleAttribute<MSNoVTableAttr>(S, D, AL);
7180 case ParsedAttr::AT_MSStruct:
7181 handleSimpleAttribute<MSStructAttr>(S, D, AL);
7183 case ParsedAttr::AT_Uuid:
7184 handleUuidAttr(S, D, AL);
7186 case ParsedAttr::AT_MSInheritance:
7187 handleMSInheritanceAttr(S, D, AL);
7189 case ParsedAttr::AT_SelectAny:
7190 handleSimpleAttribute<SelectAnyAttr>(S, D, AL);
7192 case ParsedAttr::AT_Thread:
7193 handleDeclspecThreadAttr(S, D, AL);
7196 case ParsedAttr::AT_AbiTag:
7197 handleAbiTagAttr(S, D, AL);
7200 // Thread safety attributes:
7201 case ParsedAttr::AT_AssertExclusiveLock:
7202 handleAssertExclusiveLockAttr(S, D, AL);
7204 case ParsedAttr::AT_AssertSharedLock:
7205 handleAssertSharedLockAttr(S, D, AL);
7207 case ParsedAttr::AT_GuardedVar:
7208 handleSimpleAttribute<GuardedVarAttr>(S, D, AL);
7210 case ParsedAttr::AT_PtGuardedVar:
7211 handlePtGuardedVarAttr(S, D, AL);
7213 case ParsedAttr::AT_ScopedLockable:
7214 handleSimpleAttribute<ScopedLockableAttr>(S, D, AL);
7216 case ParsedAttr::AT_NoSanitize:
7217 handleNoSanitizeAttr(S, D, AL);
7219 case ParsedAttr::AT_NoSanitizeSpecific:
7220 handleNoSanitizeSpecificAttr(S, D, AL);
7222 case ParsedAttr::AT_NoThreadSafetyAnalysis:
7223 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL);
7225 case ParsedAttr::AT_GuardedBy:
7226 handleGuardedByAttr(S, D, AL);
7228 case ParsedAttr::AT_PtGuardedBy:
7229 handlePtGuardedByAttr(S, D, AL);
7231 case ParsedAttr::AT_ExclusiveTrylockFunction:
7232 handleExclusiveTrylockFunctionAttr(S, D, AL);
7234 case ParsedAttr::AT_LockReturned:
7235 handleLockReturnedAttr(S, D, AL);
7237 case ParsedAttr::AT_LocksExcluded:
7238 handleLocksExcludedAttr(S, D, AL);
7240 case ParsedAttr::AT_SharedTrylockFunction:
7241 handleSharedTrylockFunctionAttr(S, D, AL);
7243 case ParsedAttr::AT_AcquiredBefore:
7244 handleAcquiredBeforeAttr(S, D, AL);
7246 case ParsedAttr::AT_AcquiredAfter:
7247 handleAcquiredAfterAttr(S, D, AL);
7250 // Capability analysis attributes.
7251 case ParsedAttr::AT_Capability:
7252 case ParsedAttr::AT_Lockable:
7253 handleCapabilityAttr(S, D, AL);
7255 case ParsedAttr::AT_RequiresCapability:
7256 handleRequiresCapabilityAttr(S, D, AL);
7259 case ParsedAttr::AT_AssertCapability:
7260 handleAssertCapabilityAttr(S, D, AL);
7262 case ParsedAttr::AT_AcquireCapability:
7263 handleAcquireCapabilityAttr(S, D, AL);
7265 case ParsedAttr::AT_ReleaseCapability:
7266 handleReleaseCapabilityAttr(S, D, AL);
7268 case ParsedAttr::AT_TryAcquireCapability:
7269 handleTryAcquireCapabilityAttr(S, D, AL);
7272 // Consumed analysis attributes.
7273 case ParsedAttr::AT_Consumable:
7274 handleConsumableAttr(S, D, AL);
7276 case ParsedAttr::AT_ConsumableAutoCast:
7277 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL);
7279 case ParsedAttr::AT_ConsumableSetOnRead:
7280 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL);
7282 case ParsedAttr::AT_CallableWhen:
7283 handleCallableWhenAttr(S, D, AL);
7285 case ParsedAttr::AT_ParamTypestate:
7286 handleParamTypestateAttr(S, D, AL);
7288 case ParsedAttr::AT_ReturnTypestate:
7289 handleReturnTypestateAttr(S, D, AL);
7291 case ParsedAttr::AT_SetTypestate:
7292 handleSetTypestateAttr(S, D, AL);
7294 case ParsedAttr::AT_TestTypestate:
7295 handleTestTypestateAttr(S, D, AL);
7298 // Type safety attributes.
7299 case ParsedAttr::AT_ArgumentWithTypeTag:
7300 handleArgumentWithTypeTagAttr(S, D, AL);
7302 case ParsedAttr::AT_TypeTagForDatatype:
7303 handleTypeTagForDatatypeAttr(S, D, AL);
7305 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:
7306 handleSimpleAttribute<AnyX86NoCallerSavedRegistersAttr>(S, D, AL);
7308 case ParsedAttr::AT_RenderScriptKernel:
7309 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL);
7312 case ParsedAttr::AT_XRayInstrument:
7313 handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL);
7315 case ParsedAttr::AT_XRayLogArgs:
7316 handleXRayLogArgsAttr(S, D, AL);
7319 // Move semantics attribute.
7320 case ParsedAttr::AT_Reinitializes:
7321 handleSimpleAttribute<ReinitializesAttr>(S, D, AL);
7324 case ParsedAttr::AT_AlwaysDestroy:
7325 case ParsedAttr::AT_NoDestroy:
7326 handleDestroyAttr(S, D, AL);
7329 case ParsedAttr::AT_Uninitialized:
7330 handleUninitializedAttr(S, D, AL);
7333 case ParsedAttr::AT_ObjCExternallyRetained:
7334 handleObjCExternallyRetainedAttr(S, D, AL);
7337 case ParsedAttr::AT_MIGServerRoutine:
7338 handleMIGServerRoutineAttr(S, D, AL);
7341 case ParsedAttr::AT_MSAllocator:
7342 handleMSAllocatorAttr(S, D, AL);
7347 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
7348 /// attribute list to the specified decl, ignoring any type attributes.
7349 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
7350 const ParsedAttributesView &AttrList,
7351 bool IncludeCXX11Attributes) {
7352 if (AttrList.empty())
7355 for (const ParsedAttr &AL : AttrList)
7356 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
7358 // FIXME: We should be able to handle these cases in TableGen.
7360 // static int a9 __attribute__((weakref));
7361 // but that looks really pointless. We reject it.
7362 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
7363 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
7364 << cast<NamedDecl>(D);
7365 D->dropAttr<WeakRefAttr>();
7369 // FIXME: We should be able to handle this in TableGen as well. It would be
7370 // good to have a way to specify "these attributes must appear as a group",
7371 // for these. Additionally, it would be good to have a way to specify "these
7372 // attribute must never appear as a group" for attributes like cold and hot.
7373 if (!D->hasAttr<OpenCLKernelAttr>()) {
7374 // These attributes cannot be applied to a non-kernel function.
7375 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
7376 // FIXME: This emits a different error message than
7377 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
7378 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7379 D->setInvalidDecl();
7380 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
7381 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7382 D->setInvalidDecl();
7383 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
7384 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7385 D->setInvalidDecl();
7386 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7387 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7388 D->setInvalidDecl();
7389 } else if (!D->hasAttr<CUDAGlobalAttr>()) {
7390 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7391 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7392 << A << ExpectedKernelFunction;
7393 D->setInvalidDecl();
7394 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
7395 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7396 << A << ExpectedKernelFunction;
7397 D->setInvalidDecl();
7398 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
7399 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7400 << A << ExpectedKernelFunction;
7401 D->setInvalidDecl();
7402 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
7403 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7404 << A << ExpectedKernelFunction;
7405 D->setInvalidDecl();
7410 // Do this check after processing D's attributes because the attribute
7411 // objc_method_family can change whether the given method is in the init
7412 // family, and it can be applied after objc_designated_initializer. This is a
7413 // bit of a hack, but we need it to be compatible with versions of clang that
7414 // processed the attribute list in the wrong order.
7415 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
7416 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
7417 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
7418 D->dropAttr<ObjCDesignatedInitializerAttr>();
7422 // Helper for delayed processing TransparentUnion attribute.
7423 void Sema::ProcessDeclAttributeDelayed(Decl *D,
7424 const ParsedAttributesView &AttrList) {
7425 for (const ParsedAttr &AL : AttrList)
7426 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
7427 handleTransparentUnionAttr(*this, D, AL);
7432 // Annotation attributes are the only attributes allowed after an access
7434 bool Sema::ProcessAccessDeclAttributeList(
7435 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
7436 for (const ParsedAttr &AL : AttrList) {
7437 if (AL.getKind() == ParsedAttr::AT_Annotate) {
7438 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
7440 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
7447 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
7448 /// contains any decl attributes that we should warn about.
7449 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
7450 for (const ParsedAttr &AL : A) {
7451 // Only warn if the attribute is an unignored, non-type attribute.
7452 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
7454 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
7457 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
7458 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7459 << AL << AL.getRange();
7461 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
7467 /// checkUnusedDeclAttributes - Given a declarator which is not being
7468 /// used to build a declaration, complain about any decl attributes
7469 /// which might be lying around on it.
7470 void Sema::checkUnusedDeclAttributes(Declarator &D) {
7471 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
7472 ::checkUnusedDeclAttributes(*this, D.getAttributes());
7473 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
7474 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
7477 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
7478 /// \#pragma weak needs a non-definition decl and source may not have one.
7479 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7480 SourceLocation Loc) {
7481 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
7482 NamedDecl *NewD = nullptr;
7483 if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
7484 FunctionDecl *NewFD;
7485 // FIXME: Missing call to CheckFunctionDeclaration().
7487 // FIXME: Is the qualifier info correct?
7488 // FIXME: Is the DeclContext correct?
7489 NewFD = FunctionDecl::Create(
7490 FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
7491 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
7492 false /*isInlineSpecified*/, FD->hasPrototype(), CSK_unspecified);
7495 if (FD->getQualifier())
7496 NewFD->setQualifierInfo(FD->getQualifierLoc());
7498 // Fake up parameter variables; they are declared as if this were
7500 QualType FDTy = FD->getType();
7501 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
7502 SmallVector<ParmVarDecl*, 16> Params;
7503 for (const auto &AI : FT->param_types()) {
7504 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
7505 Param->setScopeInfo(0, Params.size());
7506 Params.push_back(Param);
7508 NewFD->setParams(Params);
7510 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
7511 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
7512 VD->getInnerLocStart(), VD->getLocation(), II,
7513 VD->getType(), VD->getTypeSourceInfo(),
7514 VD->getStorageClass());
7515 if (VD->getQualifier())
7516 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
7521 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
7522 /// applied to it, possibly with an alias.
7523 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
7524 if (W.getUsed()) return; // only do this once
7526 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
7527 IdentifierInfo *NDId = ND->getIdentifier();
7528 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
7529 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
7531 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7532 WeakTopLevelDecl.push_back(NewD);
7533 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
7534 // to insert Decl at TU scope, sorry.
7535 DeclContext *SavedContext = CurContext;
7536 CurContext = Context.getTranslationUnitDecl();
7537 NewD->setDeclContext(CurContext);
7538 NewD->setLexicalDeclContext(CurContext);
7539 PushOnScopeChains(NewD, S);
7540 CurContext = SavedContext;
7541 } else { // just add weak to existing
7542 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
7546 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
7547 // It's valid to "forward-declare" #pragma weak, in which case we
7549 LoadExternalWeakUndeclaredIdentifiers();
7550 if (!WeakUndeclaredIdentifiers.empty()) {
7551 NamedDecl *ND = nullptr;
7552 if (auto *VD = dyn_cast<VarDecl>(D))
7553 if (VD->isExternC())
7555 if (auto *FD = dyn_cast<FunctionDecl>(D))
7556 if (FD->isExternC())
7559 if (IdentifierInfo *Id = ND->getIdentifier()) {
7560 auto I = WeakUndeclaredIdentifiers.find(Id);
7561 if (I != WeakUndeclaredIdentifiers.end()) {
7562 WeakInfo W = I->second;
7563 DeclApplyPragmaWeak(S, ND, W);
7564 WeakUndeclaredIdentifiers[Id] = W;
7571 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
7572 /// it, apply them to D. This is a bit tricky because PD can have attributes
7573 /// specified in many different places, and we need to find and apply them all.
7574 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
7575 // Apply decl attributes from the DeclSpec if present.
7576 if (!PD.getDeclSpec().getAttributes().empty())
7577 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
7579 // Walk the declarator structure, applying decl attributes that were in a type
7580 // position to the decl itself. This handles cases like:
7581 // int *__attr__(x)** D;
7582 // when X is a decl attribute.
7583 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
7584 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
7585 /*IncludeCXX11Attributes=*/false);
7587 // Finally, apply any attributes on the decl itself.
7588 ProcessDeclAttributeList(S, D, PD.getAttributes());
7590 // Apply additional attributes specified by '#pragma clang attribute'.
7591 AddPragmaAttributes(S, D);
7594 /// Is the given declaration allowed to use a forbidden type?
7595 /// If so, it'll still be annotated with an attribute that makes it
7596 /// illegal to actually use.
7597 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
7598 const DelayedDiagnostic &diag,
7599 UnavailableAttr::ImplicitReason &reason) {
7600 // Private ivars are always okay. Unfortunately, people don't
7601 // always properly make their ivars private, even in system headers.
7602 // Plus we need to make fields okay, too.
7603 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
7604 !isa<FunctionDecl>(D))
7607 // Silently accept unsupported uses of __weak in both user and system
7608 // declarations when it's been disabled, for ease of integration with
7609 // -fno-objc-arc files. We do have to take some care against attempts
7610 // to define such things; for now, we've only done that for ivars
7612 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
7613 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
7614 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
7615 reason = UnavailableAttr::IR_ForbiddenWeak;
7620 // Allow all sorts of things in system headers.
7621 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
7622 // Currently, all the failures dealt with this way are due to ARC
7624 reason = UnavailableAttr::IR_ARCForbiddenType;
7631 /// Handle a delayed forbidden-type diagnostic.
7632 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
7634 auto Reason = UnavailableAttr::IR_None;
7635 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
7636 assert(Reason && "didn't set reason?");
7637 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
7640 if (S.getLangOpts().ObjCAutoRefCount)
7641 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7642 // FIXME: we may want to suppress diagnostics for all
7643 // kind of forbidden type messages on unavailable functions.
7644 if (FD->hasAttr<UnavailableAttr>() &&
7645 DD.getForbiddenTypeDiagnostic() ==
7646 diag::err_arc_array_param_no_ownership) {
7647 DD.Triggered = true;
7652 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
7653 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
7654 DD.Triggered = true;
7657 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
7659 // Check each AvailabilityAttr to find the one for this platform.
7660 for (const auto *A : D->attrs()) {
7661 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
7662 // FIXME: this is copied from CheckAvailability. We should try to
7665 // Check if this is an App Extension "platform", and if so chop off
7666 // the suffix for matching with the actual platform.
7667 StringRef ActualPlatform = Avail->getPlatform()->getName();
7668 StringRef RealizedPlatform = ActualPlatform;
7669 if (Context.getLangOpts().AppExt) {
7670 size_t suffix = RealizedPlatform.rfind("_app_extension");
7671 if (suffix != StringRef::npos)
7672 RealizedPlatform = RealizedPlatform.slice(0, suffix);
7675 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
7677 // Match the platform name.
7678 if (RealizedPlatform == TargetPlatform)
7685 /// The diagnostic we should emit for \c D, and the declaration that
7686 /// originated it, or \c AR_Available.
7688 /// \param D The declaration to check.
7689 /// \param Message If non-null, this will be populated with the message from
7690 /// the availability attribute that is selected.
7691 /// \param ClassReceiver If we're checking the the method of a class message
7692 /// send, the class. Otherwise nullptr.
7693 static std::pair<AvailabilityResult, const NamedDecl *>
7694 ShouldDiagnoseAvailabilityOfDecl(Sema &S, const NamedDecl *D,
7695 std::string *Message,
7696 ObjCInterfaceDecl *ClassReceiver) {
7697 AvailabilityResult Result = D->getAvailability(Message);
7699 // For typedefs, if the typedef declaration appears available look
7700 // to the underlying type to see if it is more restrictive.
7701 while (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
7702 if (Result == AR_Available) {
7703 if (const auto *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7705 Result = D->getAvailability(Message);
7712 // Forward class declarations get their attributes from their definition.
7713 if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
7714 if (IDecl->getDefinition()) {
7715 D = IDecl->getDefinition();
7716 Result = D->getAvailability(Message);
7720 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
7721 if (Result == AR_Available) {
7722 const DeclContext *DC = ECD->getDeclContext();
7723 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
7724 Result = TheEnumDecl->getAvailability(Message);
7729 // For +new, infer availability from -init.
7730 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7731 if (S.NSAPIObj && ClassReceiver) {
7732 ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod(
7733 S.NSAPIObj->getInitSelector());
7734 if (Init && Result == AR_Available && MD->isClassMethod() &&
7735 MD->getSelector() == S.NSAPIObj->getNewSelector() &&
7736 MD->definedInNSObject(S.getASTContext())) {
7737 Result = Init->getAvailability(Message);
7747 /// whether we should emit a diagnostic for \c K and \c DeclVersion in
7748 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
7749 /// in a deprecated context, but not the other way around.
7751 ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
7752 VersionTuple DeclVersion, Decl *Ctx,
7753 const NamedDecl *OffendingDecl) {
7754 assert(K != AR_Available && "Expected an unavailable declaration here!");
7756 // Checks if we should emit the availability diagnostic in the context of C.
7757 auto CheckContext = [&](const Decl *C) {
7758 if (K == AR_NotYetIntroduced) {
7759 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
7760 if (AA->getIntroduced() >= DeclVersion)
7762 } else if (K == AR_Deprecated) {
7763 if (C->isDeprecated())
7765 } else if (K == AR_Unavailable) {
7766 // It is perfectly fine to refer to an 'unavailable' Objective-C method
7767 // when it is referenced from within the @implementation itself. In this
7768 // context, we interpret unavailable as a form of access control.
7769 if (const auto *MD = dyn_cast<ObjCMethodDecl>(OffendingDecl)) {
7770 if (const auto *Impl = dyn_cast<ObjCImplDecl>(C)) {
7771 if (MD->getClassInterface() == Impl->getClassInterface())
7777 if (C->isUnavailable())
7783 if (CheckContext(Ctx))
7786 // An implementation implicitly has the availability of the interface.
7787 // Unless it is "+load" method.
7788 if (const auto *MethodD = dyn_cast<ObjCMethodDecl>(Ctx))
7789 if (MethodD->isClassMethod() &&
7790 MethodD->getSelector().getAsString() == "load")
7793 if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7794 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7795 if (CheckContext(Interface))
7798 // A category implicitly has the availability of the interface.
7799 else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7800 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7801 if (CheckContext(Interface))
7803 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7809 shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7810 const VersionTuple &DeploymentVersion,
7811 const VersionTuple &DeclVersion) {
7812 const auto &Triple = Context.getTargetInfo().getTriple();
7813 VersionTuple ForceAvailabilityFromVersion;
7814 switch (Triple.getOS()) {
7815 case llvm::Triple::IOS:
7816 case llvm::Triple::TvOS:
7817 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7819 case llvm::Triple::WatchOS:
7820 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7822 case llvm::Triple::Darwin:
7823 case llvm::Triple::MacOSX:
7824 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7827 // New targets should always warn about availability.
7828 return Triple.getVendor() == llvm::Triple::Apple;
7830 return DeploymentVersion >= ForceAvailabilityFromVersion ||
7831 DeclVersion >= ForceAvailabilityFromVersion;
7834 static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7835 for (Decl *Ctx = OrigCtx; Ctx;
7836 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7837 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7838 return cast<NamedDecl>(Ctx);
7839 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7840 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7841 return Imp->getClassInterface();
7846 return dyn_cast<NamedDecl>(OrigCtx);
7851 struct AttributeInsertion {
7856 static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7857 return {" ", D->getEndLoc(), ""};
7859 static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7860 return {" ", Loc, ""};
7862 static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7863 return {"", D->getBeginLoc(), "\n"};
7867 } // end anonymous namespace
7869 /// Tries to parse a string as ObjC method name.
7871 /// \param Name The string to parse. Expected to originate from availability
7872 /// attribute argument.
7873 /// \param SlotNames The vector that will be populated with slot names. In case
7874 /// of unsuccessful parsing can contain invalid data.
7875 /// \returns A number of method parameters if parsing was successful, None
7877 static Optional<unsigned>
7878 tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames,
7879 const LangOptions &LangOpts) {
7880 // Accept replacements starting with - or + as valid ObjC method names.
7881 if (!Name.empty() && (Name.front() == '-' || Name.front() == '+'))
7882 Name = Name.drop_front(1);
7885 Name.split(SlotNames, ':');
7887 if (Name.back() == ':') {
7888 // Remove an empty string at the end that doesn't represent any slot.
7889 SlotNames.pop_back();
7890 NumParams = SlotNames.size();
7892 if (SlotNames.size() != 1)
7893 // Not a valid method name, just a colon-separated string.
7897 // Verify all slot names are valid.
7898 bool AllowDollar = LangOpts.DollarIdents;
7899 for (StringRef S : SlotNames) {
7902 if (!isValidIdentifier(S, AllowDollar))
7908 /// Returns a source location in which it's appropriate to insert a new
7909 /// attribute for the given declaration \D.
7910 static Optional<AttributeInsertion>
7911 createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7912 const LangOptions &LangOpts) {
7913 if (isa<ObjCPropertyDecl>(D))
7914 return AttributeInsertion::createInsertionAfter(D);
7915 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7918 return AttributeInsertion::createInsertionAfter(D);
7920 if (const auto *TD = dyn_cast<TagDecl>(D)) {
7921 SourceLocation Loc =
7922 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7923 if (Loc.isInvalid())
7925 // Insert after the 'struct'/whatever keyword.
7926 return AttributeInsertion::createInsertionAfter(Loc);
7928 return AttributeInsertion::createInsertionBefore(D);
7931 /// Actually emit an availability diagnostic for a reference to an unavailable
7934 /// \param Ctx The context that the reference occurred in
7935 /// \param ReferringDecl The exact declaration that was referenced.
7936 /// \param OffendingDecl A related decl to \c ReferringDecl that has an
7937 /// availability attribute corresponding to \c K attached to it. Note that this
7938 /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7939 /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7940 /// and OffendingDecl is the EnumDecl.
7941 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
7942 Decl *Ctx, const NamedDecl *ReferringDecl,
7943 const NamedDecl *OffendingDecl,
7945 ArrayRef<SourceLocation> Locs,
7946 const ObjCInterfaceDecl *UnknownObjCClass,
7947 const ObjCPropertyDecl *ObjCProperty,
7948 bool ObjCPropertyAccess) {
7949 // Diagnostics for deprecated or unavailable.
7950 unsigned diag, diag_message, diag_fwdclass_message;
7951 unsigned diag_available_here = diag::note_availability_specified_here;
7952 SourceLocation NoteLocation = OffendingDecl->getLocation();
7954 // Matches 'diag::note_property_attribute' options.
7955 unsigned property_note_select;
7957 // Matches diag::note_availability_specified_here.
7958 unsigned available_here_select_kind;
7960 VersionTuple DeclVersion;
7961 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
7962 DeclVersion = AA->getIntroduced();
7964 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx,
7968 SourceLocation Loc = Locs.front();
7970 // The declaration can have multiple availability attributes, we are looking
7972 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
7973 if (A && A->isInherited()) {
7974 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
7975 Redecl = Redecl->getPreviousDecl()) {
7976 const AvailabilityAttr *AForRedecl =
7977 getAttrForPlatform(S.Context, Redecl);
7978 if (AForRedecl && !AForRedecl->isInherited()) {
7979 // If D is a declaration with inherited attributes, the note should
7980 // point to the declaration with actual attributes.
7981 NoteLocation = Redecl->getLocation();
7988 case AR_NotYetIntroduced: {
7989 // We would like to emit the diagnostic even if -Wunguarded-availability is
7990 // not specified for deployment targets >= to iOS 11 or equivalent or
7991 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7993 const AvailabilityAttr *AA =
7994 getAttrForPlatform(S.getASTContext(), OffendingDecl);
7995 VersionTuple Introduced = AA->getIntroduced();
7997 bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
7998 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
8000 unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
8001 : diag::warn_unguarded_availability;
8003 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
8004 S.getASTContext().getTargetInfo().getPlatformName());
8006 S.Diag(Loc, Warning) << OffendingDecl << PlatformName
8007 << Introduced.getAsString();
8009 S.Diag(OffendingDecl->getLocation(),
8010 diag::note_partial_availability_specified_here)
8011 << OffendingDecl << PlatformName << Introduced.getAsString()
8012 << S.Context.getTargetInfo().getPlatformMinVersion().getAsString();
8014 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
8015 if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
8016 if (TD->getDeclName().isEmpty()) {
8017 S.Diag(TD->getLocation(),
8018 diag::note_decl_unguarded_availability_silence)
8019 << /*Anonymous*/ 1 << TD->getKindName();
8022 auto FixitNoteDiag =
8023 S.Diag(Enclosing->getLocation(),
8024 diag::note_decl_unguarded_availability_silence)
8025 << /*Named*/ 0 << Enclosing;
8026 // Don't offer a fixit for declarations with availability attributes.
8027 if (Enclosing->hasAttr<AvailabilityAttr>())
8029 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
8031 Optional<AttributeInsertion> Insertion = createAttributeInsertion(
8032 Enclosing, S.getSourceManager(), S.getLangOpts());
8035 std::string PlatformName =
8036 AvailabilityAttr::getPlatformNameSourceSpelling(
8037 S.getASTContext().getTargetInfo().getPlatformName())
8039 std::string Introduced =
8040 OffendingDecl->getVersionIntroduced().getAsString();
8041 FixitNoteDiag << FixItHint::CreateInsertion(
8043 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
8044 "(" + Introduced + "))" + Insertion->Suffix)
8050 diag = !ObjCPropertyAccess ? diag::warn_deprecated
8051 : diag::warn_property_method_deprecated;
8052 diag_message = diag::warn_deprecated_message;
8053 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
8054 property_note_select = /* deprecated */ 0;
8055 available_here_select_kind = /* deprecated */ 2;
8056 if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>())
8057 NoteLocation = AL->getLocation();
8060 case AR_Unavailable:
8061 diag = !ObjCPropertyAccess ? diag::err_unavailable
8062 : diag::err_property_method_unavailable;
8063 diag_message = diag::err_unavailable_message;
8064 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
8065 property_note_select = /* unavailable */ 1;
8066 available_here_select_kind = /* unavailable */ 0;
8068 if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) {
8069 if (AL->isImplicit() && AL->getImplicitReason()) {
8070 // Most of these failures are due to extra restrictions in ARC;
8071 // reflect that in the primary diagnostic when applicable.
8072 auto flagARCError = [&] {
8073 if (S.getLangOpts().ObjCAutoRefCount &&
8074 S.getSourceManager().isInSystemHeader(
8075 OffendingDecl->getLocation()))
8076 diag = diag::err_unavailable_in_arc;
8079 switch (AL->getImplicitReason()) {
8080 case UnavailableAttr::IR_None: break;
8082 case UnavailableAttr::IR_ARCForbiddenType:
8084 diag_available_here = diag::note_arc_forbidden_type;
8087 case UnavailableAttr::IR_ForbiddenWeak:
8088 if (S.getLangOpts().ObjCWeakRuntime)
8089 diag_available_here = diag::note_arc_weak_disabled;
8091 diag_available_here = diag::note_arc_weak_no_runtime;
8094 case UnavailableAttr::IR_ARCForbiddenConversion:
8096 diag_available_here = diag::note_performs_forbidden_arc_conversion;
8099 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
8101 diag_available_here = diag::note_arc_init_returns_unrelated;
8104 case UnavailableAttr::IR_ARCFieldWithOwnership:
8106 diag_available_here = diag::note_arc_field_with_ownership;
8114 llvm_unreachable("Warning for availability of available declaration?");
8117 SmallVector<FixItHint, 12> FixIts;
8118 if (K == AR_Deprecated) {
8119 StringRef Replacement;
8120 if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>())
8121 Replacement = AL->getReplacement();
8122 if (auto AL = getAttrForPlatform(S.Context, OffendingDecl))
8123 Replacement = AL->getReplacement();
8125 CharSourceRange UseRange;
8126 if (!Replacement.empty())
8128 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8129 if (UseRange.isValid()) {
8130 if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) {
8131 Selector Sel = MethodDecl->getSelector();
8132 SmallVector<StringRef, 12> SelectorSlotNames;
8133 Optional<unsigned> NumParams = tryParseObjCMethodName(
8134 Replacement, SelectorSlotNames, S.getLangOpts());
8135 if (NumParams && NumParams.getValue() == Sel.getNumArgs()) {
8136 assert(SelectorSlotNames.size() == Locs.size());
8137 for (unsigned I = 0; I < Locs.size(); ++I) {
8138 if (!Sel.getNameForSlot(I).empty()) {
8139 CharSourceRange NameRange = CharSourceRange::getCharRange(
8140 Locs[I], S.getLocForEndOfToken(Locs[I]));
8141 FixIts.push_back(FixItHint::CreateReplacement(
8142 NameRange, SelectorSlotNames[I]));
8145 FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I]));
8148 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
8150 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
8154 if (!Message.empty()) {
8155 S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts;
8157 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
8158 << ObjCProperty->getDeclName() << property_note_select;
8159 } else if (!UnknownObjCClass) {
8160 S.Diag(Loc, diag) << ReferringDecl << FixIts;
8162 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
8163 << ObjCProperty->getDeclName() << property_note_select;
8165 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts;
8166 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
8169 S.Diag(NoteLocation, diag_available_here)
8170 << OffendingDecl << available_here_select_kind;
8173 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
8175 assert(DD.Kind == DelayedDiagnostic::Availability &&
8176 "Expected an availability diagnostic here");
8178 DD.Triggered = true;
8179 DoEmitAvailabilityWarning(
8180 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
8181 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(),
8182 DD.getAvailabilitySelectorLocs(), DD.getUnknownObjCClass(),
8183 DD.getObjCProperty(), false);
8186 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
8187 assert(DelayedDiagnostics.getCurrentPool());
8188 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
8189 DelayedDiagnostics.popWithoutEmitting(state);
8191 // When delaying diagnostics to run in the context of a parsed
8192 // declaration, we only want to actually emit anything if parsing
8196 // We emit all the active diagnostics in this pool or any of its
8197 // parents. In general, we'll get one pool for the decl spec
8198 // and a child pool for each declarator; in a decl group like:
8199 // deprecated_typedef foo, *bar, baz();
8200 // only the declarator pops will be passed decls. This is correct;
8201 // we really do need to consider delayed diagnostics from the decl spec
8202 // for each of the different declarations.
8203 const DelayedDiagnosticPool *pool = &poppedPool;
8205 bool AnyAccessFailures = false;
8206 for (DelayedDiagnosticPool::pool_iterator
8207 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
8208 // This const_cast is a bit lame. Really, Triggered should be mutable.
8209 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
8213 switch (diag.Kind) {
8214 case DelayedDiagnostic::Availability:
8215 // Don't bother giving deprecation/unavailable diagnostics if
8216 // the decl is invalid.
8217 if (!decl->isInvalidDecl())
8218 handleDelayedAvailabilityCheck(*this, diag, decl);
8221 case DelayedDiagnostic::Access:
8222 // Only produce one access control diagnostic for a structured binding
8223 // declaration: we don't need to tell the user that all the fields are
8224 // inaccessible one at a time.
8225 if (AnyAccessFailures && isa<DecompositionDecl>(decl))
8227 HandleDelayedAccessCheck(diag, decl);
8229 AnyAccessFailures = true;
8232 case DelayedDiagnostic::ForbiddenType:
8233 handleDelayedForbiddenType(*this, diag, decl);
8237 } while ((pool = pool->getParent()));
8240 /// Given a set of delayed diagnostics, re-emit them as if they had
8241 /// been delayed in the current context instead of in the given pool.
8242 /// Essentially, this just moves them to the current pool.
8243 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
8244 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
8245 assert(curPool && "re-emitting in undelayed context not supported");
8246 curPool->steal(pool);
8249 static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
8250 const NamedDecl *ReferringDecl,
8251 const NamedDecl *OffendingDecl,
8253 ArrayRef<SourceLocation> Locs,
8254 const ObjCInterfaceDecl *UnknownObjCClass,
8255 const ObjCPropertyDecl *ObjCProperty,
8256 bool ObjCPropertyAccess) {
8257 // Delay if we're currently parsing a declaration.
8258 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
8259 S.DelayedDiagnostics.add(
8260 DelayedDiagnostic::makeAvailability(
8261 AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass,
8262 ObjCProperty, Message, ObjCPropertyAccess));
8266 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
8267 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
8268 Message, Locs, UnknownObjCClass, ObjCProperty,
8269 ObjCPropertyAccess);
8274 /// Returns true if the given statement can be a body-like child of \p Parent.
8275 bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
8276 switch (Parent->getStmtClass()) {
8277 case Stmt::IfStmtClass:
8278 return cast<IfStmt>(Parent)->getThen() == S ||
8279 cast<IfStmt>(Parent)->getElse() == S;
8280 case Stmt::WhileStmtClass:
8281 return cast<WhileStmt>(Parent)->getBody() == S;
8282 case Stmt::DoStmtClass:
8283 return cast<DoStmt>(Parent)->getBody() == S;
8284 case Stmt::ForStmtClass:
8285 return cast<ForStmt>(Parent)->getBody() == S;
8286 case Stmt::CXXForRangeStmtClass:
8287 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
8288 case Stmt::ObjCForCollectionStmtClass:
8289 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
8290 case Stmt::CaseStmtClass:
8291 case Stmt::DefaultStmtClass:
8292 return cast<SwitchCase>(Parent)->getSubStmt() == S;
8298 class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
8302 bool VisitStmt(Stmt *S) { return S != Target; }
8304 /// Returns true if the given statement is present in the given declaration.
8305 static bool isContained(const Stmt *Target, const Decl *D) {
8306 StmtUSEFinder Visitor;
8307 Visitor.Target = Target;
8308 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
8312 /// Traverses the AST and finds the last statement that used a given
8314 class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
8318 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
8319 if (DRE->getDecl() == D)
8324 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
8325 const CompoundStmt *Scope) {
8326 LastDeclUSEFinder Visitor;
8328 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
8330 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
8337 /// This class implements -Wunguarded-availability.
8339 /// This is done with a traversal of the AST of a function that makes reference
8340 /// to a partially available declaration. Whenever we encounter an \c if of the
8341 /// form: \c if(@available(...)), we use the version from the condition to visit
8342 /// the then statement.
8343 class DiagnoseUnguardedAvailability
8344 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
8345 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
8350 /// Stack of potentially nested 'if (@available(...))'s.
8351 SmallVector<VersionTuple, 8> AvailabilityStack;
8352 SmallVector<const Stmt *, 16> StmtStack;
8354 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range,
8355 ObjCInterfaceDecl *ClassReceiver = nullptr);
8358 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
8359 : SemaRef(SemaRef), Ctx(Ctx) {
8360 AvailabilityStack.push_back(
8361 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
8364 bool TraverseDecl(Decl *D) {
8365 // Avoid visiting nested functions to prevent duplicate warnings.
8366 if (!D || isa<FunctionDecl>(D))
8368 return Base::TraverseDecl(D);
8371 bool TraverseStmt(Stmt *S) {
8374 StmtStack.push_back(S);
8375 bool Result = Base::TraverseStmt(S);
8376 StmtStack.pop_back();
8380 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
8382 bool TraverseIfStmt(IfStmt *If);
8384 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
8386 // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
8387 // to any useful diagnostics.
8388 bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
8390 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
8391 if (PRE->isClassReceiver())
8392 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
8396 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
8397 if (ObjCMethodDecl *D = Msg->getMethodDecl()) {
8398 ObjCInterfaceDecl *ID = nullptr;
8399 QualType ReceiverTy = Msg->getClassReceiver();
8400 if (!ReceiverTy.isNull() && ReceiverTy->getAsObjCInterfaceType())
8401 ID = ReceiverTy->getAsObjCInterfaceType()->getInterface();
8403 DiagnoseDeclAvailability(
8404 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getEndLoc()), ID);
8409 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
8410 DiagnoseDeclAvailability(DRE->getDecl(),
8411 SourceRange(DRE->getBeginLoc(), DRE->getEndLoc()));
8415 bool VisitMemberExpr(MemberExpr *ME) {
8416 DiagnoseDeclAvailability(ME->getMemberDecl(),
8417 SourceRange(ME->getBeginLoc(), ME->getEndLoc()));
8421 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
8422 SemaRef.Diag(E->getBeginLoc(), diag::warn_at_available_unchecked_use)
8423 << (!SemaRef.getLangOpts().ObjC);
8427 bool VisitTypeLoc(TypeLoc Ty);
8430 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
8431 NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) {
8432 AvailabilityResult Result;
8433 const NamedDecl *OffendingDecl;
8434 std::tie(Result, OffendingDecl) =
8435 ShouldDiagnoseAvailabilityOfDecl(SemaRef, D, nullptr, ReceiverClass);
8436 if (Result != AR_Available) {
8437 // All other diagnostic kinds have already been handled in
8438 // DiagnoseAvailabilityOfDecl.
8439 if (Result != AR_NotYetIntroduced)
8442 const AvailabilityAttr *AA =
8443 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
8444 VersionTuple Introduced = AA->getIntroduced();
8446 if (AvailabilityStack.back() >= Introduced)
8449 // If the context of this function is less available than D, we should not
8450 // emit a diagnostic.
8451 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx,
8455 // We would like to emit the diagnostic even if -Wunguarded-availability is
8456 // not specified for deployment targets >= to iOS 11 or equivalent or
8457 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
8460 shouldDiagnoseAvailabilityByDefault(
8462 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
8463 ? diag::warn_unguarded_availability_new
8464 : diag::warn_unguarded_availability;
8466 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
8467 SemaRef.getASTContext().getTargetInfo().getPlatformName());
8469 SemaRef.Diag(Range.getBegin(), DiagKind)
8470 << Range << D << PlatformName << Introduced.getAsString();
8472 SemaRef.Diag(OffendingDecl->getLocation(),
8473 diag::note_partial_availability_specified_here)
8474 << OffendingDecl << PlatformName << Introduced.getAsString()
8475 << SemaRef.Context.getTargetInfo()
8476 .getPlatformMinVersion()
8480 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
8482 << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
8483 : /*__builtin_available*/ 1);
8485 // Find the statement which should be enclosed in the if @available check.
8486 if (StmtStack.empty())
8488 const Stmt *StmtOfUse = StmtStack.back();
8489 const CompoundStmt *Scope = nullptr;
8490 for (const Stmt *S : llvm::reverse(StmtStack)) {
8491 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
8495 if (isBodyLikeChildStmt(StmtOfUse, S)) {
8496 // The declaration won't be seen outside of the statement, so we don't
8497 // have to wrap the uses of any declared variables in if (@available).
8498 // Therefore we can avoid setting Scope here.
8503 const Stmt *LastStmtOfUse = nullptr;
8504 if (isa<DeclStmt>(StmtOfUse) && Scope) {
8505 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
8506 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
8507 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
8513 const SourceManager &SM = SemaRef.getSourceManager();
8514 SourceLocation IfInsertionLoc =
8515 SM.getExpansionLoc(StmtOfUse->getBeginLoc());
8516 SourceLocation StmtEndLoc =
8517 SM.getExpansionRange(
8518 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
8520 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
8523 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
8524 const char *ExtraIndentation = " ";
8525 std::string FixItString;
8526 llvm::raw_string_ostream FixItOS(FixItString);
8527 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available"
8528 : "__builtin_available")
8530 << AvailabilityAttr::getPlatformNameSourceSpelling(
8531 SemaRef.getASTContext().getTargetInfo().getPlatformName())
8532 << " " << Introduced.getAsString() << ", *)) {\n"
8533 << Indentation << ExtraIndentation;
8534 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
8535 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
8536 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
8537 /*SkipTrailingWhitespaceAndNewLine=*/false);
8538 if (ElseInsertionLoc.isInvalid())
8540 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
8541 FixItOS.str().clear();
8543 << Indentation << "} else {\n"
8544 << Indentation << ExtraIndentation
8545 << "// Fallback on earlier versions\n"
8546 << Indentation << "}";
8547 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
8551 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
8552 const Type *TyPtr = Ty.getTypePtr();
8553 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
8555 if (Range.isInvalid())
8558 if (const auto *TT = dyn_cast<TagType>(TyPtr)) {
8559 TagDecl *TD = TT->getDecl();
8560 DiagnoseDeclAvailability(TD, Range);
8562 } else if (const auto *TD = dyn_cast<TypedefType>(TyPtr)) {
8563 TypedefNameDecl *D = TD->getDecl();
8564 DiagnoseDeclAvailability(D, Range);
8566 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
8567 if (NamedDecl *D = ObjCO->getInterface())
8568 DiagnoseDeclAvailability(D, Range);
8574 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
8575 VersionTuple CondVersion;
8576 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
8577 CondVersion = E->getVersion();
8579 // If we're using the '*' case here or if this check is redundant, then we
8580 // use the enclosing version to check both branches.
8581 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
8582 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
8584 // This isn't an availability checking 'if', we can just continue.
8585 return Base::TraverseIfStmt(If);
8588 AvailabilityStack.push_back(CondVersion);
8589 bool ShouldContinue = TraverseStmt(If->getThen());
8590 AvailabilityStack.pop_back();
8592 return ShouldContinue && TraverseStmt(If->getElse());
8595 } // end anonymous namespace
8597 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
8598 Stmt *Body = nullptr;
8600 if (auto *FD = D->getAsFunction()) {
8601 // FIXME: We only examine the pattern decl for availability violations now,
8602 // but we should also examine instantiated templates.
8603 if (FD->isTemplateInstantiation())
8606 Body = FD->getBody();
8607 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
8608 Body = MD->getBody();
8609 else if (auto *BD = dyn_cast<BlockDecl>(D))
8610 Body = BD->getBody();
8612 assert(Body && "Need a body here!");
8614 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
8617 void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D,
8618 ArrayRef<SourceLocation> Locs,
8619 const ObjCInterfaceDecl *UnknownObjCClass,
8620 bool ObjCPropertyAccess,
8621 bool AvoidPartialAvailabilityChecks,
8622 ObjCInterfaceDecl *ClassReceiver) {
8623 std::string Message;
8624 AvailabilityResult Result;
8625 const NamedDecl* OffendingDecl;
8626 // See if this declaration is unavailable, deprecated, or partial.
8627 std::tie(Result, OffendingDecl) =
8628 ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver);
8629 if (Result == AR_Available)
8632 if (Result == AR_NotYetIntroduced) {
8633 if (AvoidPartialAvailabilityChecks)
8636 // We need to know the @available context in the current function to
8637 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
8638 // when we're done parsing the current function.
8639 if (getCurFunctionOrMethodDecl()) {
8640 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
8642 } else if (getCurBlock() || getCurLambda()) {
8643 getCurFunction()->HasPotentialAvailabilityViolations = true;
8648 const ObjCPropertyDecl *ObjCPDecl = nullptr;
8649 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
8650 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
8651 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
8652 if (PDeclResult == Result)
8657 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs,
8658 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);