1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements decl-related attribute processing.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Support/MathExtras.h"
38 using namespace clang;
41 namespace AttributeLangSupport {
47 } // end namespace AttributeLangSupport
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
53 /// isFunctionOrMethod - Return true if the given decl has function
54 /// type (function or function-typed variable) or an Objective-C
56 static bool isFunctionOrMethod(const Decl *D) {
57 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
60 /// \brief Return true if the given decl has function type (function or
61 /// function-typed variable) or an Objective-C method or a block.
62 static bool isFunctionOrMethodOrBlock(const Decl *D) {
63 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
66 /// Return true if the given decl has a declarator that should have
67 /// been processed by Sema::GetTypeForDeclarator.
68 static bool hasDeclarator(const Decl *D) {
69 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
70 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
71 isa<ObjCPropertyDecl>(D);
74 /// hasFunctionProto - Return true if the given decl has a argument
75 /// information. This decl should have already passed
76 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
77 static bool hasFunctionProto(const Decl *D) {
78 if (const FunctionType *FnTy = D->getFunctionType())
79 return isa<FunctionProtoType>(FnTy);
80 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
83 /// getFunctionOrMethodNumParams - Return number of function or method
84 /// parameters. It is an error to call this on a K&R function (use
85 /// hasFunctionProto first).
86 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
87 if (const FunctionType *FnTy = D->getFunctionType())
88 return cast<FunctionProtoType>(FnTy)->getNumParams();
89 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
90 return BD->getNumParams();
91 return cast<ObjCMethodDecl>(D)->param_size();
94 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
95 if (const FunctionType *FnTy = D->getFunctionType())
96 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
97 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
98 return BD->getParamDecl(Idx)->getType();
100 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
103 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
104 if (const auto *FD = dyn_cast<FunctionDecl>(D))
105 return FD->getParamDecl(Idx)->getSourceRange();
106 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
107 return MD->parameters()[Idx]->getSourceRange();
108 if (const auto *BD = dyn_cast<BlockDecl>(D))
109 return BD->getParamDecl(Idx)->getSourceRange();
110 return SourceRange();
113 static QualType getFunctionOrMethodResultType(const Decl *D) {
114 if (const FunctionType *FnTy = D->getFunctionType())
115 return cast<FunctionType>(FnTy)->getReturnType();
116 return cast<ObjCMethodDecl>(D)->getReturnType();
119 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
120 if (const auto *FD = dyn_cast<FunctionDecl>(D))
121 return FD->getReturnTypeSourceRange();
122 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
123 return MD->getReturnTypeSourceRange();
124 return SourceRange();
127 static bool isFunctionOrMethodVariadic(const Decl *D) {
128 if (const FunctionType *FnTy = D->getFunctionType()) {
129 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
130 return proto->isVariadic();
132 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
133 return BD->isVariadic();
135 return cast<ObjCMethodDecl>(D)->isVariadic();
138 static bool isInstanceMethod(const Decl *D) {
139 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
140 return MethodDecl->isInstance();
144 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
145 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
149 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
153 IdentifierInfo* ClsName = Cls->getIdentifier();
155 // FIXME: Should we walk the chain of classes?
156 return ClsName == &Ctx.Idents.get("NSString") ||
157 ClsName == &Ctx.Idents.get("NSMutableString");
160 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
161 const PointerType *PT = T->getAs<PointerType>();
165 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
169 const RecordDecl *RD = RT->getDecl();
170 if (RD->getTagKind() != TTK_Struct)
173 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
176 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
177 // FIXME: Include the type in the argument list.
178 return Attr.getNumArgs() + Attr.hasParsedType();
181 template <typename Compare>
182 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
183 unsigned Num, unsigned Diag,
185 if (Comp(getNumAttributeArgs(Attr), Num)) {
186 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
193 /// \brief Check if the attribute has exactly as many args as Num. May
195 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
197 return checkAttributeNumArgsImpl(S, Attr, Num,
198 diag::err_attribute_wrong_number_arguments,
199 std::not_equal_to<unsigned>());
202 /// \brief Check if the attribute has at least as many args as Num. May
204 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
206 return checkAttributeNumArgsImpl(S, Attr, Num,
207 diag::err_attribute_too_few_arguments,
208 std::less<unsigned>());
211 /// \brief Check if the attribute has at most as many args as Num. May
213 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
215 return checkAttributeNumArgsImpl(S, Attr, Num,
216 diag::err_attribute_too_many_arguments,
217 std::greater<unsigned>());
220 /// \brief If Expr is a valid integer constant, get the value of the integer
221 /// expression and return success or failure. May output an error.
222 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
223 const Expr *Expr, uint32_t &Val,
224 unsigned Idx = UINT_MAX) {
226 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
227 !Expr->isIntegerConstantExpr(I, S.Context)) {
229 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
230 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
231 << Expr->getSourceRange();
233 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
234 << Attr.getName() << AANT_ArgumentIntegerConstant
235 << Expr->getSourceRange();
240 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
241 << I.toString(10, false) << 32 << /* Unsigned */ 1;
245 Val = (uint32_t)I.getZExtValue();
249 /// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
250 /// that the result will fit into a regular (signed) int. All args have the same
251 /// purpose as they do in checkUInt32Argument.
252 static bool checkPositiveIntArgument(Sema &S, const AttributeList &Attr,
253 const Expr *Expr, int &Val,
254 unsigned Idx = UINT_MAX) {
256 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
259 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
260 llvm::APSInt I(32); // for toString
262 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
263 << I.toString(10, false) << 32 << /* Unsigned */ 0;
271 /// \brief Diagnose mutually exclusive attributes when present on a given
272 /// declaration. Returns true if diagnosed.
273 template <typename AttrTy>
274 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
275 IdentifierInfo *Ident) {
276 if (AttrTy *A = D->getAttr<AttrTy>()) {
277 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
279 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
285 /// \brief Check if IdxExpr is a valid parameter index for a function or
286 /// instance method D. May output an error.
288 /// \returns true if IdxExpr is a valid index.
289 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
290 const AttributeList &Attr,
294 assert(isFunctionOrMethodOrBlock(D));
296 // In C++ the implicit 'this' function parameter also counts.
297 // Parameters are counted from one.
298 bool HP = hasFunctionProto(D);
299 bool HasImplicitThisParam = isInstanceMethod(D);
300 bool IV = HP && isFunctionOrMethodVariadic(D);
302 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
305 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
306 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
307 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
308 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
309 << IdxExpr->getSourceRange();
313 Idx = IdxInt.getLimitedValue();
314 if (Idx < 1 || (!IV && Idx > NumParams)) {
315 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
316 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
319 Idx--; // Convert to zero-based.
320 if (HasImplicitThisParam) {
322 S.Diag(Attr.getLoc(),
323 diag::err_attribute_invalid_implicit_this_argument)
324 << Attr.getName() << IdxExpr->getSourceRange();
333 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
334 /// If not emit an error and return false. If the argument is an identifier it
335 /// will emit an error with a fixit hint and treat it as if it was a string
337 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
338 unsigned ArgNum, StringRef &Str,
339 SourceLocation *ArgLocation) {
340 // Look for identifiers. If we have one emit a hint to fix it to a literal.
341 if (Attr.isArgIdent(ArgNum)) {
342 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
343 Diag(Loc->Loc, diag::err_attribute_argument_type)
344 << Attr.getName() << AANT_ArgumentString
345 << FixItHint::CreateInsertion(Loc->Loc, "\"")
346 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
347 Str = Loc->Ident->getName();
349 *ArgLocation = Loc->Loc;
353 // Now check for an actual string literal.
354 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
355 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
357 *ArgLocation = ArgExpr->getLocStart();
359 if (!Literal || !Literal->isAscii()) {
360 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
361 << Attr.getName() << AANT_ArgumentString;
365 Str = Literal->getString();
369 /// \brief Applies the given attribute to the Decl without performing any
370 /// additional semantic checking.
371 template <typename AttrType>
372 static void handleSimpleAttribute(Sema &S, Decl *D,
373 const AttributeList &Attr) {
374 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
375 Attr.getAttributeSpellingListIndex()));
378 template <typename AttrType>
379 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
380 const AttributeList &Attr) {
381 handleSimpleAttribute<AttrType>(S, D, Attr);
384 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't
385 /// already have one of the given incompatible attributes.
386 template <typename AttrType, typename IncompatibleAttrType,
387 typename... IncompatibleAttrTypes>
388 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
389 const AttributeList &Attr) {
390 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
393 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
397 /// \brief Check if the passed-in expression is of type int or bool.
398 static bool isIntOrBool(Expr *Exp) {
399 QualType QT = Exp->getType();
400 return QT->isBooleanType() || QT->isIntegerType();
404 // Check to see if the type is a smart pointer of some kind. We assume
405 // it's a smart pointer if it defines both operator-> and operator*.
406 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
407 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
408 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
412 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
413 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
420 /// \brief Check if passed in Decl is a pointer type.
421 /// Note that this function may produce an error message.
422 /// \return true if the Decl is a pointer type; false otherwise
423 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
424 const AttributeList &Attr) {
425 const ValueDecl *vd = cast<ValueDecl>(D);
426 QualType QT = vd->getType();
427 if (QT->isAnyPointerType())
430 if (const RecordType *RT = QT->getAs<RecordType>()) {
431 // If it's an incomplete type, it could be a smart pointer; skip it.
432 // (We don't want to force template instantiation if we can avoid it,
433 // since that would alter the order in which templates are instantiated.)
434 if (RT->isIncompleteType())
437 if (threadSafetyCheckIsSmartPointer(S, RT))
441 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
442 << Attr.getName() << QT;
446 /// \brief Checks that the passed in QualType either is of RecordType or points
447 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
448 static const RecordType *getRecordType(QualType QT) {
449 if (const RecordType *RT = QT->getAs<RecordType>())
452 // Now check if we point to record type.
453 if (const PointerType *PT = QT->getAs<PointerType>())
454 return PT->getPointeeType()->getAs<RecordType>();
459 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
460 const RecordType *RT = getRecordType(Ty);
465 // Don't check for the capability if the class hasn't been defined yet.
466 if (RT->isIncompleteType())
469 // Allow smart pointers to be used as capability objects.
470 // FIXME -- Check the type that the smart pointer points to.
471 if (threadSafetyCheckIsSmartPointer(S, RT))
474 // Check if the record itself has a capability.
475 RecordDecl *RD = RT->getDecl();
476 if (RD->hasAttr<CapabilityAttr>())
479 // Else check if any base classes have a capability.
480 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
481 CXXBasePaths BPaths(false, false);
482 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
483 const auto *Type = BS->getType()->getAs<RecordType>();
484 return Type->getDecl()->hasAttr<CapabilityAttr>();
491 static bool checkTypedefTypeForCapability(QualType Ty) {
492 const auto *TD = Ty->getAs<TypedefType>();
496 TypedefNameDecl *TN = TD->getDecl();
500 return TN->hasAttr<CapabilityAttr>();
503 static bool typeHasCapability(Sema &S, QualType Ty) {
504 if (checkTypedefTypeForCapability(Ty))
507 if (checkRecordTypeForCapability(S, Ty))
513 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
514 // Capability expressions are simple expressions involving the boolean logic
515 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
516 // a DeclRefExpr is found, its type should be checked to determine whether it
517 // is a capability or not.
519 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
520 return typeHasCapability(S, E->getType());
521 else if (const auto *E = dyn_cast<CastExpr>(Ex))
522 return isCapabilityExpr(S, E->getSubExpr());
523 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
524 return isCapabilityExpr(S, E->getSubExpr());
525 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
526 if (E->getOpcode() == UO_LNot)
527 return isCapabilityExpr(S, E->getSubExpr());
529 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
530 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
531 return isCapabilityExpr(S, E->getLHS()) &&
532 isCapabilityExpr(S, E->getRHS());
539 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
540 /// a capability object.
541 /// \param Sidx The attribute argument index to start checking with.
542 /// \param ParamIdxOk Whether an argument can be indexing into a function
544 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
545 const AttributeList &Attr,
546 SmallVectorImpl<Expr *> &Args,
548 bool ParamIdxOk = false) {
549 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
550 Expr *ArgExp = Attr.getArgAsExpr(Idx);
552 if (ArgExp->isTypeDependent()) {
553 // FIXME -- need to check this again on template instantiation
554 Args.push_back(ArgExp);
558 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
559 if (StrLit->getLength() == 0 ||
560 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
561 // Pass empty strings to the analyzer without warnings.
562 // Treat "*" as the universal lock.
563 Args.push_back(ArgExp);
567 // We allow constant strings to be used as a placeholder for expressions
568 // that are not valid C++ syntax, but warn that they are ignored.
569 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
571 Args.push_back(ArgExp);
575 QualType ArgTy = ArgExp->getType();
577 // A pointer to member expression of the form &MyClass::mu is treated
578 // specially -- we need to look at the type of the member.
579 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
580 if (UOp->getOpcode() == UO_AddrOf)
581 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
582 if (DRE->getDecl()->isCXXInstanceMember())
583 ArgTy = DRE->getDecl()->getType();
585 // First see if we can just cast to record type, or pointer to record type.
586 const RecordType *RT = getRecordType(ArgTy);
588 // Now check if we index into a record type function param.
589 if(!RT && ParamIdxOk) {
590 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
591 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
593 unsigned int NumParams = FD->getNumParams();
594 llvm::APInt ArgValue = IL->getValue();
595 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
596 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
597 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
598 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
599 << Attr.getName() << Idx + 1 << NumParams;
602 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
606 // If the type does not have a capability, see if the components of the
607 // expression have capabilities. This allows for writing C code where the
608 // capability may be on the type, and the expression is a capability
609 // boolean logic expression. Eg) requires_capability(A || B && !C)
610 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
611 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
612 << Attr.getName() << ArgTy;
614 Args.push_back(ArgExp);
618 //===----------------------------------------------------------------------===//
619 // Attribute Implementations
620 //===----------------------------------------------------------------------===//
622 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
623 const AttributeList &Attr) {
624 if (!threadSafetyCheckIsPointer(S, D, Attr))
627 D->addAttr(::new (S.Context)
628 PtGuardedVarAttr(Attr.getRange(), S.Context,
629 Attr.getAttributeSpellingListIndex()));
632 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
633 const AttributeList &Attr,
635 SmallVector<Expr*, 1> Args;
636 // check that all arguments are lockable objects
637 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
638 unsigned Size = Args.size();
647 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
649 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
652 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
653 Attr.getAttributeSpellingListIndex()));
656 static void handlePtGuardedByAttr(Sema &S, Decl *D,
657 const AttributeList &Attr) {
659 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
662 if (!threadSafetyCheckIsPointer(S, D, Attr))
665 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
667 Attr.getAttributeSpellingListIndex()));
670 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
671 const AttributeList &Attr,
672 SmallVectorImpl<Expr *> &Args) {
673 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
676 // Check that this attribute only applies to lockable types.
677 QualType QT = cast<ValueDecl>(D)->getType();
678 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
679 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
684 // Check that all arguments are lockable objects.
685 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
692 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
693 const AttributeList &Attr) {
694 SmallVector<Expr*, 1> Args;
695 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
698 Expr **StartArg = &Args[0];
699 D->addAttr(::new (S.Context)
700 AcquiredAfterAttr(Attr.getRange(), S.Context,
701 StartArg, Args.size(),
702 Attr.getAttributeSpellingListIndex()));
705 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
706 const AttributeList &Attr) {
707 SmallVector<Expr*, 1> Args;
708 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
711 Expr **StartArg = &Args[0];
712 D->addAttr(::new (S.Context)
713 AcquiredBeforeAttr(Attr.getRange(), S.Context,
714 StartArg, Args.size(),
715 Attr.getAttributeSpellingListIndex()));
718 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
719 const AttributeList &Attr,
720 SmallVectorImpl<Expr *> &Args) {
721 // zero or more arguments ok
722 // check that all arguments are lockable objects
723 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
728 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
729 const AttributeList &Attr) {
730 SmallVector<Expr*, 1> Args;
731 if (!checkLockFunAttrCommon(S, D, Attr, Args))
734 unsigned Size = Args.size();
735 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
736 D->addAttr(::new (S.Context)
737 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
738 Attr.getAttributeSpellingListIndex()));
741 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
742 const AttributeList &Attr) {
743 SmallVector<Expr*, 1> Args;
744 if (!checkLockFunAttrCommon(S, D, Attr, Args))
747 unsigned Size = Args.size();
748 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
749 D->addAttr(::new (S.Context)
750 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
752 Attr.getAttributeSpellingListIndex()));
755 /// \brief Checks to be sure that the given parameter number is inbounds, and is
756 /// an some integral type. Will emit appropriate diagnostics if this returns
759 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
760 /// to actually retrieve the argument, so it's base-0.
761 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
762 const AttributeList &Attr,
763 unsigned FuncParamNo, unsigned AttrArgNo) {
764 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
766 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo,
767 Attr.getArgAsExpr(AttrArgNo), Idx))
770 const ParmVarDecl *Param = FD->getParamDecl(Idx);
771 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
772 SourceLocation SrcLoc = Attr.getArgAsExpr(AttrArgNo)->getLocStart();
773 S.Diag(SrcLoc, diag::err_attribute_integers_only)
774 << Attr.getName() << Param->getSourceRange();
780 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
781 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
782 !checkAttributeAtMostNumArgs(S, Attr, 2))
785 const auto *FD = cast<FunctionDecl>(D);
786 if (!FD->getReturnType()->isPointerType()) {
787 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
792 const Expr *SizeExpr = Attr.getArgAsExpr(0);
794 // Paramater indices are 1-indexed, hence Index=1
795 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
798 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
801 // Args are 1-indexed, so 0 implies that the arg was not present
803 if (Attr.getNumArgs() == 2) {
804 const Expr *NumberExpr = Attr.getArgAsExpr(1);
805 // Paramater indices are 1-based, hence Index=2
806 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
810 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
814 D->addAttr(::new (S.Context) AllocSizeAttr(
815 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
816 Attr.getAttributeSpellingListIndex()));
819 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
820 const AttributeList &Attr,
821 SmallVectorImpl<Expr *> &Args) {
822 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
825 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
826 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
827 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
831 // check that all arguments are lockable objects
832 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
837 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
838 const AttributeList &Attr) {
839 SmallVector<Expr*, 2> Args;
840 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
843 D->addAttr(::new (S.Context)
844 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
845 Attr.getArgAsExpr(0),
846 Args.data(), Args.size(),
847 Attr.getAttributeSpellingListIndex()));
850 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
851 const AttributeList &Attr) {
852 SmallVector<Expr*, 2> Args;
853 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
856 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
857 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
858 Args.size(), Attr.getAttributeSpellingListIndex()));
861 static void handleLockReturnedAttr(Sema &S, Decl *D,
862 const AttributeList &Attr) {
863 // check that the argument is lockable object
864 SmallVector<Expr*, 1> Args;
865 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
866 unsigned Size = Args.size();
870 D->addAttr(::new (S.Context)
871 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
872 Attr.getAttributeSpellingListIndex()));
875 static void handleLocksExcludedAttr(Sema &S, Decl *D,
876 const AttributeList &Attr) {
877 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
880 // check that all arguments are lockable objects
881 SmallVector<Expr*, 1> Args;
882 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
883 unsigned Size = Args.size();
886 Expr **StartArg = &Args[0];
888 D->addAttr(::new (S.Context)
889 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
890 Attr.getAttributeSpellingListIndex()));
893 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
894 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
896 Expr *Cond = Attr.getArgAsExpr(0);
897 if (!Cond->isTypeDependent()) {
898 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
899 if (Converted.isInvalid())
901 Cond = Converted.get();
905 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
908 SmallVector<PartialDiagnosticAt, 8> Diags;
909 if (!Cond->isValueDependent() &&
910 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
912 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
913 for (const PartialDiagnosticAt &PDiag : Diags)
914 S.Diag(PDiag.first, PDiag.second);
918 D->addAttr(::new (S.Context)
919 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
920 Attr.getAttributeSpellingListIndex()));
923 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
924 const AttributeList &Attr) {
925 if (D->hasAttr<PassObjectSizeAttr>()) {
926 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
931 Expr *E = Attr.getArgAsExpr(0);
933 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
936 // pass_object_size's argument is passed in as the second argument of
937 // __builtin_object_size. So, it has the same constraints as that second
938 // argument; namely, it must be in the range [0, 3].
940 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
941 << Attr.getName() << 0 << 3 << E->getSourceRange();
945 // pass_object_size is only supported on constant pointer parameters; as a
946 // kindness to users, we allow the parameter to be non-const for declarations.
947 // At this point, we have no clue if `D` belongs to a function declaration or
948 // definition, so we defer the constness check until later.
949 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
950 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
951 << Attr.getName() << 1;
955 D->addAttr(::new (S.Context)
956 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
957 Attr.getAttributeSpellingListIndex()));
960 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
961 ConsumableAttr::ConsumedState DefaultState;
963 if (Attr.isArgIdent(0)) {
964 IdentifierLoc *IL = Attr.getArgAsIdent(0);
965 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
967 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
968 << Attr.getName() << IL->Ident;
972 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
973 << Attr.getName() << AANT_ArgumentIdentifier;
977 D->addAttr(::new (S.Context)
978 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
979 Attr.getAttributeSpellingListIndex()));
982 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
983 const AttributeList &Attr) {
984 ASTContext &CurrContext = S.getASTContext();
985 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
987 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
988 if (!RD->hasAttr<ConsumableAttr>()) {
989 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
990 RD->getNameAsString();
999 static void handleCallableWhenAttr(Sema &S, Decl *D,
1000 const AttributeList &Attr) {
1001 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1004 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1007 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1008 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1009 CallableWhenAttr::ConsumedState CallableState;
1011 StringRef StateString;
1013 if (Attr.isArgIdent(ArgIndex)) {
1014 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1015 StateString = Ident->Ident->getName();
1018 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1022 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1024 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1025 << Attr.getName() << StateString;
1029 States.push_back(CallableState);
1032 D->addAttr(::new (S.Context)
1033 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1034 States.size(), Attr.getAttributeSpellingListIndex()));
1037 static void handleParamTypestateAttr(Sema &S, Decl *D,
1038 const AttributeList &Attr) {
1039 ParamTypestateAttr::ConsumedState ParamState;
1041 if (Attr.isArgIdent(0)) {
1042 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1043 StringRef StateString = Ident->Ident->getName();
1045 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1047 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1048 << Attr.getName() << StateString;
1052 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1053 Attr.getName() << AANT_ArgumentIdentifier;
1057 // FIXME: This check is currently being done in the analysis. It can be
1058 // enabled here only after the parser propagates attributes at
1059 // template specialization definition, not declaration.
1060 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1061 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1063 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1064 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1065 // ReturnType.getAsString();
1069 D->addAttr(::new (S.Context)
1070 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1071 Attr.getAttributeSpellingListIndex()));
1074 static void handleReturnTypestateAttr(Sema &S, Decl *D,
1075 const AttributeList &Attr) {
1076 ReturnTypestateAttr::ConsumedState ReturnState;
1078 if (Attr.isArgIdent(0)) {
1079 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1080 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1082 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1083 << Attr.getName() << IL->Ident;
1087 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1088 Attr.getName() << AANT_ArgumentIdentifier;
1092 // FIXME: This check is currently being done in the analysis. It can be
1093 // enabled here only after the parser propagates attributes at
1094 // template specialization definition, not declaration.
1095 //QualType ReturnType;
1097 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1098 // ReturnType = Param->getType();
1100 //} else if (const CXXConstructorDecl *Constructor =
1101 // dyn_cast<CXXConstructorDecl>(D)) {
1102 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1106 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1109 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1111 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1112 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1113 // ReturnType.getAsString();
1117 D->addAttr(::new (S.Context)
1118 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1119 Attr.getAttributeSpellingListIndex()));
1122 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1123 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1126 SetTypestateAttr::ConsumedState NewState;
1127 if (Attr.isArgIdent(0)) {
1128 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1129 StringRef Param = Ident->Ident->getName();
1130 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1131 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1132 << Attr.getName() << Param;
1136 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1137 Attr.getName() << AANT_ArgumentIdentifier;
1141 D->addAttr(::new (S.Context)
1142 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1143 Attr.getAttributeSpellingListIndex()));
1146 static void handleTestTypestateAttr(Sema &S, Decl *D,
1147 const AttributeList &Attr) {
1148 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1151 TestTypestateAttr::ConsumedState TestState;
1152 if (Attr.isArgIdent(0)) {
1153 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1154 StringRef Param = Ident->Ident->getName();
1155 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1156 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1157 << Attr.getName() << Param;
1161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1162 Attr.getName() << AANT_ArgumentIdentifier;
1166 D->addAttr(::new (S.Context)
1167 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1168 Attr.getAttributeSpellingListIndex()));
1171 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1172 const AttributeList &Attr) {
1173 // Remember this typedef decl, we will need it later for diagnostics.
1174 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1177 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1178 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1179 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1180 Attr.getAttributeSpellingListIndex()));
1181 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1182 // Report warning about changed offset in the newer compiler versions.
1183 if (!FD->getType()->isDependentType() &&
1184 !FD->getType()->isIncompleteType() && FD->isBitField() &&
1185 S.Context.getTypeAlign(FD->getType()) <= 8)
1186 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1188 FD->addAttr(::new (S.Context) PackedAttr(
1189 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1191 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1194 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1195 // The IBOutlet/IBOutletCollection attributes only apply to instance
1196 // variables or properties of Objective-C classes. The outlet must also
1197 // have an object reference type.
1198 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1199 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1200 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1201 << Attr.getName() << VD->getType() << 0;
1205 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1206 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1207 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1208 << Attr.getName() << PD->getType() << 1;
1213 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1220 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1221 if (!checkIBOutletCommon(S, D, Attr))
1224 D->addAttr(::new (S.Context)
1225 IBOutletAttr(Attr.getRange(), S.Context,
1226 Attr.getAttributeSpellingListIndex()));
1229 static void handleIBOutletCollection(Sema &S, Decl *D,
1230 const AttributeList &Attr) {
1232 // The iboutletcollection attribute can have zero or one arguments.
1233 if (Attr.getNumArgs() > 1) {
1234 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1235 << Attr.getName() << 1;
1239 if (!checkIBOutletCommon(S, D, Attr))
1244 if (Attr.hasParsedType())
1245 PT = Attr.getTypeArg();
1247 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1248 S.getScopeForContext(D->getDeclContext()->getParent()));
1250 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1255 TypeSourceInfo *QTLoc = nullptr;
1256 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1258 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1260 // Diagnose use of non-object type in iboutletcollection attribute.
1261 // FIXME. Gnu attribute extension ignores use of builtin types in
1262 // attributes. So, __attribute__((iboutletcollection(char))) will be
1263 // treated as __attribute__((iboutletcollection())).
1264 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1265 S.Diag(Attr.getLoc(),
1266 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1267 : diag::err_iboutletcollection_type) << QT;
1271 D->addAttr(::new (S.Context)
1272 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1273 Attr.getAttributeSpellingListIndex()));
1276 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1278 if (T->isReferenceType())
1281 T = T.getNonReferenceType();
1284 // The nonnull attribute, and other similar attributes, can be applied to a
1285 // transparent union that contains a pointer type.
1286 if (const RecordType *UT = T->getAsUnionType()) {
1287 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1288 RecordDecl *UD = UT->getDecl();
1289 for (const auto *I : UD->fields()) {
1290 QualType QT = I->getType();
1291 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1297 return T->isAnyPointerType() || T->isBlockPointerType();
1300 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1301 SourceRange AttrParmRange,
1302 SourceRange TypeRange,
1303 bool isReturnValue = false) {
1304 if (!S.isValidPointerAttrType(T)) {
1306 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1307 << Attr.getName() << AttrParmRange << TypeRange;
1309 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1310 << Attr.getName() << AttrParmRange << TypeRange << 0;
1316 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1317 SmallVector<unsigned, 8> NonNullArgs;
1318 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1319 Expr *Ex = Attr.getArgAsExpr(I);
1321 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1324 // Is the function argument a pointer type?
1325 if (Idx < getFunctionOrMethodNumParams(D) &&
1326 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1327 Ex->getSourceRange(),
1328 getFunctionOrMethodParamRange(D, Idx)))
1331 NonNullArgs.push_back(Idx);
1334 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1335 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1336 // check if the attribute came from a macro expansion or a template
1338 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1339 S.ActiveTemplateInstantiations.empty()) {
1340 bool AnyPointers = isFunctionOrMethodVariadic(D);
1341 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1342 I != E && !AnyPointers; ++I) {
1343 QualType T = getFunctionOrMethodParamType(D, I);
1344 if (T->isDependentType() || S.isValidPointerAttrType(T))
1349 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1352 unsigned *Start = NonNullArgs.data();
1353 unsigned Size = NonNullArgs.size();
1354 llvm::array_pod_sort(Start, Start + Size);
1355 D->addAttr(::new (S.Context)
1356 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1357 Attr.getAttributeSpellingListIndex()));
1360 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1361 const AttributeList &Attr) {
1362 if (Attr.getNumArgs() > 0) {
1363 if (D->getFunctionType()) {
1364 handleNonNullAttr(S, D, Attr);
1366 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1367 << D->getSourceRange();
1372 // Is the argument a pointer type?
1373 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1374 D->getSourceRange()))
1377 D->addAttr(::new (S.Context)
1378 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1379 Attr.getAttributeSpellingListIndex()));
1382 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1383 const AttributeList &Attr) {
1384 QualType ResultType = getFunctionOrMethodResultType(D);
1385 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1386 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1387 /* isReturnValue */ true))
1390 D->addAttr(::new (S.Context)
1391 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1392 Attr.getAttributeSpellingListIndex()));
1395 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1396 const AttributeList &Attr) {
1397 Expr *E = Attr.getArgAsExpr(0),
1398 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1399 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1400 Attr.getAttributeSpellingListIndex());
1403 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1404 Expr *OE, unsigned SpellingListIndex) {
1405 QualType ResultType = getFunctionOrMethodResultType(D);
1406 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1408 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1409 SourceLocation AttrLoc = AttrRange.getBegin();
1411 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1412 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1413 << &TmpAttr << AttrRange << SR;
1417 if (!E->isValueDependent()) {
1419 if (!E->isIntegerConstantExpr(I, Context)) {
1421 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1422 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1423 << E->getSourceRange();
1425 Diag(AttrLoc, diag::err_attribute_argument_type)
1426 << &TmpAttr << AANT_ArgumentIntegerConstant
1427 << E->getSourceRange();
1431 if (!I.isPowerOf2()) {
1432 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1433 << E->getSourceRange();
1439 if (!OE->isValueDependent()) {
1441 if (!OE->isIntegerConstantExpr(I, Context)) {
1442 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1443 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1444 << OE->getSourceRange();
1450 D->addAttr(::new (Context)
1451 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1454 /// Normalize the attribute, __foo__ becomes foo.
1455 /// Returns true if normalization was applied.
1456 static bool normalizeName(StringRef &AttrName) {
1457 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1458 AttrName.endswith("__")) {
1459 AttrName = AttrName.drop_front(2).drop_back(2);
1465 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1466 // This attribute must be applied to a function declaration. The first
1467 // argument to the attribute must be an identifier, the name of the resource,
1468 // for example: malloc. The following arguments must be argument indexes, the
1469 // arguments must be of integer type for Returns, otherwise of pointer type.
1470 // The difference between Holds and Takes is that a pointer may still be used
1471 // after being held. free() should be __attribute((ownership_takes)), whereas
1472 // a list append function may well be __attribute((ownership_holds)).
1474 if (!AL.isArgIdent(0)) {
1475 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1476 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1480 // Figure out our Kind.
1481 OwnershipAttr::OwnershipKind K =
1482 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1483 AL.getAttributeSpellingListIndex()).getOwnKind();
1487 case OwnershipAttr::Takes:
1488 case OwnershipAttr::Holds:
1489 if (AL.getNumArgs() < 2) {
1490 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1491 << AL.getName() << 2;
1495 case OwnershipAttr::Returns:
1496 if (AL.getNumArgs() > 2) {
1497 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1498 << AL.getName() << 1;
1504 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1506 StringRef ModuleName = Module->getName();
1507 if (normalizeName(ModuleName)) {
1508 Module = &S.PP.getIdentifierTable().get(ModuleName);
1511 SmallVector<unsigned, 8> OwnershipArgs;
1512 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1513 Expr *Ex = AL.getArgAsExpr(i);
1515 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1518 // Is the function argument a pointer type?
1519 QualType T = getFunctionOrMethodParamType(D, Idx);
1520 int Err = -1; // No error
1522 case OwnershipAttr::Takes:
1523 case OwnershipAttr::Holds:
1524 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1527 case OwnershipAttr::Returns:
1528 if (!T->isIntegerType())
1533 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1534 << Ex->getSourceRange();
1538 // Check we don't have a conflict with another ownership attribute.
1539 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1540 // Cannot have two ownership attributes of different kinds for the same
1542 if (I->getOwnKind() != K && I->args_end() !=
1543 std::find(I->args_begin(), I->args_end(), Idx)) {
1544 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1545 << AL.getName() << I;
1547 } else if (K == OwnershipAttr::Returns &&
1548 I->getOwnKind() == OwnershipAttr::Returns) {
1549 // A returns attribute conflicts with any other returns attribute using
1550 // a different index. Note, diagnostic reporting is 1-based, but stored
1551 // argument indexes are 0-based.
1552 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1553 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1554 << *(I->args_begin()) + 1;
1556 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1557 << (unsigned)Idx + 1 << Ex->getSourceRange();
1562 OwnershipArgs.push_back(Idx);
1565 unsigned* start = OwnershipArgs.data();
1566 unsigned size = OwnershipArgs.size();
1567 llvm::array_pod_sort(start, start + size);
1569 D->addAttr(::new (S.Context)
1570 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1571 AL.getAttributeSpellingListIndex()));
1574 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1575 // Check the attribute arguments.
1576 if (Attr.getNumArgs() > 1) {
1577 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1578 << Attr.getName() << 1;
1582 NamedDecl *nd = cast<NamedDecl>(D);
1586 // static int a __attribute__((weakref ("v2")));
1587 // static int b() __attribute__((weakref ("f3")));
1589 // and ignores the attributes of
1591 // static int a __attribute__((weakref ("v2")));
1594 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1595 if (!Ctx->isFileContext()) {
1596 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1601 // The GCC manual says
1603 // At present, a declaration to which `weakref' is attached can only
1608 // Without a TARGET,
1609 // given as an argument to `weakref' or to `alias', `weakref' is
1610 // equivalent to `weak'.
1612 // gcc 4.4.1 will accept
1613 // int a7 __attribute__((weakref));
1615 // int a7 __attribute__((weak));
1616 // This looks like a bug in gcc. We reject that for now. We should revisit
1617 // it if this behaviour is actually used.
1620 // static ((alias ("y"), weakref)).
1621 // Should we? How to check that weakref is before or after alias?
1623 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1624 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1625 // StringRef parameter it was given anyway.
1627 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1628 // GCC will accept anything as the argument of weakref. Should we
1629 // check for an existing decl?
1630 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1631 Attr.getAttributeSpellingListIndex()));
1633 D->addAttr(::new (S.Context)
1634 WeakRefAttr(Attr.getRange(), S.Context,
1635 Attr.getAttributeSpellingListIndex()));
1638 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1640 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1643 // Aliases should be on declarations, not definitions.
1644 const auto *FD = cast<FunctionDecl>(D);
1645 if (FD->isThisDeclarationADefinition()) {
1646 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1649 // FIXME: it should be handled as a target specific attribute.
1650 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1651 llvm::Triple::ELF) {
1652 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1656 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1657 Attr.getAttributeSpellingListIndex()));
1660 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1662 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1665 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1666 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1669 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1670 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1673 // Aliases should be on declarations, not definitions.
1674 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1675 if (FD->isThisDeclarationADefinition()) {
1676 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
1680 const auto *VD = cast<VarDecl>(D);
1681 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1682 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
1687 // FIXME: check if target symbol exists in current file
1689 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1690 Attr.getAttributeSpellingListIndex()));
1693 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1694 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1697 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1698 Attr.getAttributeSpellingListIndex()));
1701 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1702 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1705 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1706 Attr.getAttributeSpellingListIndex()));
1709 static void handleTLSModelAttr(Sema &S, Decl *D,
1710 const AttributeList &Attr) {
1712 SourceLocation LiteralLoc;
1713 // Check that it is a string.
1714 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1717 // Check that the value.
1718 if (Model != "global-dynamic" && Model != "local-dynamic"
1719 && Model != "initial-exec" && Model != "local-exec") {
1720 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1724 D->addAttr(::new (S.Context)
1725 TLSModelAttr(Attr.getRange(), S.Context, Model,
1726 Attr.getAttributeSpellingListIndex()));
1729 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1730 QualType ResultType = getFunctionOrMethodResultType(D);
1731 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1732 D->addAttr(::new (S.Context) RestrictAttr(
1733 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1737 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1738 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1741 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1742 if (S.LangOpts.CPlusPlus) {
1743 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1744 << Attr.getName() << AttributeLangSupport::Cpp;
1748 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1749 Attr.getAttributeSpellingListIndex()))
1753 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1754 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1758 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1759 Attr.getAttributeSpellingListIndex()));
1762 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1763 if (hasDeclarator(D)) return;
1765 if (S.CheckNoReturnAttr(attr)) return;
1767 if (!isa<ObjCMethodDecl>(D)) {
1768 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1769 << attr.getName() << ExpectedFunctionOrMethod;
1773 D->addAttr(::new (S.Context)
1774 NoReturnAttr(attr.getRange(), S.Context,
1775 attr.getAttributeSpellingListIndex()));
1778 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1779 if (!checkAttributeNumArgs(*this, attr, 0)) {
1787 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1788 const AttributeList &Attr) {
1790 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1791 // because 'analyzer_noreturn' does not impact the type.
1792 if (!isFunctionOrMethodOrBlock(D)) {
1793 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1794 if (!VD || (!VD->getType()->isBlockPointerType() &&
1795 !VD->getType()->isFunctionPointerType())) {
1796 S.Diag(Attr.getLoc(),
1797 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1798 : diag::warn_attribute_wrong_decl_type)
1799 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1804 D->addAttr(::new (S.Context)
1805 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1806 Attr.getAttributeSpellingListIndex()));
1809 // PS3 PPU-specific.
1810 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1812 Returning a Vector Class in Registers
1814 According to the PPU ABI specifications, a class with a single member of
1815 vector type is returned in memory when used as the return value of a function.
1816 This results in inefficient code when implementing vector classes. To return
1817 the value in a single vector register, add the vecreturn attribute to the
1818 class definition. This attribute is also applicable to struct types.
1824 __vector float xyzw;
1825 } __attribute__((vecreturn));
1827 Vector Add(Vector lhs, Vector rhs)
1830 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1831 return result; // This will be returned in a register
1834 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1835 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1839 RecordDecl *record = cast<RecordDecl>(D);
1842 if (!isa<CXXRecordDecl>(record)) {
1843 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1847 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1848 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1852 for (const auto *I : record->fields()) {
1853 if ((count == 1) || !I->getType()->isVectorType()) {
1854 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1860 D->addAttr(::new (S.Context)
1861 VecReturnAttr(Attr.getRange(), S.Context,
1862 Attr.getAttributeSpellingListIndex()));
1865 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1866 const AttributeList &Attr) {
1867 if (isa<ParmVarDecl>(D)) {
1868 // [[carries_dependency]] can only be applied to a parameter if it is a
1869 // parameter of a function declaration or lambda.
1870 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1871 S.Diag(Attr.getLoc(),
1872 diag::err_carries_dependency_param_not_function_decl);
1877 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1878 Attr.getRange(), S.Context,
1879 Attr.getAttributeSpellingListIndex()));
1882 static void handleNotTailCalledAttr(Sema &S, Decl *D,
1883 const AttributeList &Attr) {
1884 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1888 D->addAttr(::new (S.Context) NotTailCalledAttr(
1889 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1892 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1893 const AttributeList &Attr) {
1894 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1898 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1899 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1902 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1903 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1904 if (VD->hasLocalStorage()) {
1905 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1908 } else if (!isFunctionOrMethod(D)) {
1909 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1910 << Attr.getName() << ExpectedVariableOrFunction;
1914 D->addAttr(::new (S.Context)
1915 UsedAttr(Attr.getRange(), S.Context,
1916 Attr.getAttributeSpellingListIndex()));
1919 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1920 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
1922 if (IsCXX1zAttr && isa<VarDecl>(D)) {
1923 // The C++1z spelling of this attribute cannot be applied to a static data
1924 // member per [dcl.attr.unused]p2.
1925 if (cast<VarDecl>(D)->isStaticDataMember()) {
1926 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1927 << Attr.getName() << ExpectedForMaybeUnused;
1932 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
1933 // about using it as an extension.
1934 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
1935 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
1937 D->addAttr(::new (S.Context) UnusedAttr(
1938 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1941 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1942 uint32_t priority = ConstructorAttr::DefaultPriority;
1943 if (Attr.getNumArgs() &&
1944 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1947 D->addAttr(::new (S.Context)
1948 ConstructorAttr(Attr.getRange(), S.Context, priority,
1949 Attr.getAttributeSpellingListIndex()));
1952 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1953 uint32_t priority = DestructorAttr::DefaultPriority;
1954 if (Attr.getNumArgs() &&
1955 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1958 D->addAttr(::new (S.Context)
1959 DestructorAttr(Attr.getRange(), S.Context, priority,
1960 Attr.getAttributeSpellingListIndex()));
1963 template <typename AttrTy>
1964 static void handleAttrWithMessage(Sema &S, Decl *D,
1965 const AttributeList &Attr) {
1966 // Handle the case where the attribute has a text message.
1968 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1971 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1972 Attr.getAttributeSpellingListIndex()));
1975 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1976 const AttributeList &Attr) {
1977 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1978 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1979 << Attr.getName() << Attr.getRange();
1983 D->addAttr(::new (S.Context)
1984 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1985 Attr.getAttributeSpellingListIndex()));
1988 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1989 IdentifierInfo *Platform,
1990 VersionTuple Introduced,
1991 VersionTuple Deprecated,
1992 VersionTuple Obsoleted) {
1993 StringRef PlatformName
1994 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1995 if (PlatformName.empty())
1996 PlatformName = Platform->getName();
1998 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1999 // of these steps are needed).
2000 if (!Introduced.empty() && !Deprecated.empty() &&
2001 !(Introduced <= Deprecated)) {
2002 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2003 << 1 << PlatformName << Deprecated.getAsString()
2004 << 0 << Introduced.getAsString();
2008 if (!Introduced.empty() && !Obsoleted.empty() &&
2009 !(Introduced <= Obsoleted)) {
2010 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2011 << 2 << PlatformName << Obsoleted.getAsString()
2012 << 0 << Introduced.getAsString();
2016 if (!Deprecated.empty() && !Obsoleted.empty() &&
2017 !(Deprecated <= Obsoleted)) {
2018 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2019 << 2 << PlatformName << Obsoleted.getAsString()
2020 << 1 << Deprecated.getAsString();
2027 /// \brief Check whether the two versions match.
2029 /// If either version tuple is empty, then they are assumed to match. If
2030 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2031 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2032 bool BeforeIsOkay) {
2033 if (X.empty() || Y.empty())
2039 if (BeforeIsOkay && X < Y)
2045 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2046 IdentifierInfo *Platform,
2048 VersionTuple Introduced,
2049 VersionTuple Deprecated,
2050 VersionTuple Obsoleted,
2054 StringRef Replacement,
2055 AvailabilityMergeKind AMK,
2056 unsigned AttrSpellingListIndex) {
2057 VersionTuple MergedIntroduced = Introduced;
2058 VersionTuple MergedDeprecated = Deprecated;
2059 VersionTuple MergedObsoleted = Obsoleted;
2060 bool FoundAny = false;
2061 bool OverrideOrImpl = false;
2064 case AMK_Redeclaration:
2065 OverrideOrImpl = false;
2069 case AMK_ProtocolImplementation:
2070 OverrideOrImpl = true;
2074 if (D->hasAttrs()) {
2075 AttrVec &Attrs = D->getAttrs();
2076 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2077 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2083 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2084 if (OldPlatform != Platform) {
2089 // If there is an existing availability attribute for this platform that
2090 // is explicit and the new one is implicit use the explicit one and
2091 // discard the new implicit attribute.
2092 if (!OldAA->isImplicit() && Implicit) {
2096 // If there is an existing attribute for this platform that is implicit
2097 // and the new attribute is explicit then erase the old one and
2098 // continue processing the attributes.
2099 if (!Implicit && OldAA->isImplicit()) {
2100 Attrs.erase(Attrs.begin() + i);
2106 VersionTuple OldIntroduced = OldAA->getIntroduced();
2107 VersionTuple OldDeprecated = OldAA->getDeprecated();
2108 VersionTuple OldObsoleted = OldAA->getObsoleted();
2109 bool OldIsUnavailable = OldAA->getUnavailable();
2111 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2112 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2113 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2114 !(OldIsUnavailable == IsUnavailable ||
2115 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2116 if (OverrideOrImpl) {
2118 VersionTuple FirstVersion;
2119 VersionTuple SecondVersion;
2120 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2122 FirstVersion = OldIntroduced;
2123 SecondVersion = Introduced;
2124 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2126 FirstVersion = Deprecated;
2127 SecondVersion = OldDeprecated;
2128 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2130 FirstVersion = Obsoleted;
2131 SecondVersion = OldObsoleted;
2135 Diag(OldAA->getLocation(),
2136 diag::warn_mismatched_availability_override_unavail)
2137 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2138 << (AMK == AMK_Override);
2140 Diag(OldAA->getLocation(),
2141 diag::warn_mismatched_availability_override)
2143 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2144 << FirstVersion.getAsString() << SecondVersion.getAsString()
2145 << (AMK == AMK_Override);
2147 if (AMK == AMK_Override)
2148 Diag(Range.getBegin(), diag::note_overridden_method);
2150 Diag(Range.getBegin(), diag::note_protocol_method);
2152 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2153 Diag(Range.getBegin(), diag::note_previous_attribute);
2156 Attrs.erase(Attrs.begin() + i);
2161 VersionTuple MergedIntroduced2 = MergedIntroduced;
2162 VersionTuple MergedDeprecated2 = MergedDeprecated;
2163 VersionTuple MergedObsoleted2 = MergedObsoleted;
2165 if (MergedIntroduced2.empty())
2166 MergedIntroduced2 = OldIntroduced;
2167 if (MergedDeprecated2.empty())
2168 MergedDeprecated2 = OldDeprecated;
2169 if (MergedObsoleted2.empty())
2170 MergedObsoleted2 = OldObsoleted;
2172 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2173 MergedIntroduced2, MergedDeprecated2,
2174 MergedObsoleted2)) {
2175 Attrs.erase(Attrs.begin() + i);
2180 MergedIntroduced = MergedIntroduced2;
2181 MergedDeprecated = MergedDeprecated2;
2182 MergedObsoleted = MergedObsoleted2;
2188 MergedIntroduced == Introduced &&
2189 MergedDeprecated == Deprecated &&
2190 MergedObsoleted == Obsoleted)
2193 // Only create a new attribute if !OverrideOrImpl, but we want to do
2195 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2196 MergedDeprecated, MergedObsoleted) &&
2198 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2199 Introduced, Deprecated,
2200 Obsoleted, IsUnavailable, Message,
2201 IsStrict, Replacement,
2202 AttrSpellingListIndex);
2203 Avail->setImplicit(Implicit);
2209 static void handleAvailabilityAttr(Sema &S, Decl *D,
2210 const AttributeList &Attr) {
2211 if (!checkAttributeNumArgs(S, Attr, 1))
2213 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2214 unsigned Index = Attr.getAttributeSpellingListIndex();
2216 IdentifierInfo *II = Platform->Ident;
2217 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2218 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2221 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2223 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2227 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2228 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2229 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2230 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2231 bool IsStrict = Attr.getStrictLoc().isValid();
2233 if (const StringLiteral *SE =
2234 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2235 Str = SE->getString();
2236 StringRef Replacement;
2237 if (const StringLiteral *SE =
2238 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2239 Replacement = SE->getString();
2241 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2247 IsStrict, Replacement,
2251 D->addAttr(NewAttr);
2253 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2254 // matches before the start of the watchOS platform.
2255 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2256 IdentifierInfo *NewII = nullptr;
2257 if (II->getName() == "ios")
2258 NewII = &S.Context.Idents.get("watchos");
2259 else if (II->getName() == "ios_app_extension")
2260 NewII = &S.Context.Idents.get("watchos_app_extension");
2263 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2264 if (Version.empty())
2266 auto Major = Version.getMajor();
2267 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2268 if (NewMajor >= 2) {
2269 if (Version.getMinor().hasValue()) {
2270 if (Version.getSubminor().hasValue())
2271 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2272 Version.getSubminor().getValue());
2274 return VersionTuple(NewMajor, Version.getMinor().getValue());
2278 return VersionTuple(2, 0);
2281 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2282 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2283 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2285 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2298 D->addAttr(NewAttr);
2300 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2301 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2302 // matches before the start of the tvOS platform.
2303 IdentifierInfo *NewII = nullptr;
2304 if (II->getName() == "ios")
2305 NewII = &S.Context.Idents.get("tvos");
2306 else if (II->getName() == "ios_app_extension")
2307 NewII = &S.Context.Idents.get("tvos_app_extension");
2310 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2323 D->addAttr(NewAttr);
2329 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2330 typename T::VisibilityType value,
2331 unsigned attrSpellingListIndex) {
2332 T *existingAttr = D->getAttr<T>();
2334 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2335 if (existingValue == value)
2337 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2338 S.Diag(range.getBegin(), diag::note_previous_attribute);
2341 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2344 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2345 VisibilityAttr::VisibilityType Vis,
2346 unsigned AttrSpellingListIndex) {
2347 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2348 AttrSpellingListIndex);
2351 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2352 TypeVisibilityAttr::VisibilityType Vis,
2353 unsigned AttrSpellingListIndex) {
2354 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2355 AttrSpellingListIndex);
2358 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2359 bool isTypeVisibility) {
2360 // Visibility attributes don't mean anything on a typedef.
2361 if (isa<TypedefNameDecl>(D)) {
2362 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2367 // 'type_visibility' can only go on a type or namespace.
2368 if (isTypeVisibility &&
2369 !(isa<TagDecl>(D) ||
2370 isa<ObjCInterfaceDecl>(D) ||
2371 isa<NamespaceDecl>(D))) {
2372 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2373 << Attr.getName() << ExpectedTypeOrNamespace;
2377 // Check that the argument is a string literal.
2379 SourceLocation LiteralLoc;
2380 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2383 VisibilityAttr::VisibilityType type;
2384 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2385 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2386 << Attr.getName() << TypeStr;
2390 // Complain about attempts to use protected visibility on targets
2391 // (like Darwin) that don't support it.
2392 if (type == VisibilityAttr::Protected &&
2393 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2394 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2395 type = VisibilityAttr::Default;
2398 unsigned Index = Attr.getAttributeSpellingListIndex();
2399 clang::Attr *newAttr;
2400 if (isTypeVisibility) {
2401 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2402 (TypeVisibilityAttr::VisibilityType) type,
2405 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2408 D->addAttr(newAttr);
2411 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2412 const AttributeList &Attr) {
2413 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2414 if (!Attr.isArgIdent(0)) {
2415 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2416 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2420 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2421 ObjCMethodFamilyAttr::FamilyKind F;
2422 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2423 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2428 if (F == ObjCMethodFamilyAttr::OMF_init &&
2429 !method->getReturnType()->isObjCObjectPointerType()) {
2430 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2431 << method->getReturnType();
2432 // Ignore the attribute.
2436 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2438 Attr.getAttributeSpellingListIndex()));
2441 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2442 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2443 QualType T = TD->getUnderlyingType();
2444 if (!T->isCARCBridgableType()) {
2445 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2449 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2450 QualType T = PD->getType();
2451 if (!T->isCARCBridgableType()) {
2452 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2457 // It is okay to include this attribute on properties, e.g.:
2459 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2461 // In this case it follows tradition and suppresses an error in the above
2463 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2465 D->addAttr(::new (S.Context)
2466 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2467 Attr.getAttributeSpellingListIndex()));
2470 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2471 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2472 QualType T = TD->getUnderlyingType();
2473 if (!T->isObjCObjectPointerType()) {
2474 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2478 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2481 D->addAttr(::new (S.Context)
2482 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2483 Attr.getAttributeSpellingListIndex()));
2486 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2487 if (!Attr.isArgIdent(0)) {
2488 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2489 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2493 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2494 BlocksAttr::BlockType type;
2495 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2496 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2497 << Attr.getName() << II;
2501 D->addAttr(::new (S.Context)
2502 BlocksAttr(Attr.getRange(), S.Context, type,
2503 Attr.getAttributeSpellingListIndex()));
2506 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2507 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2508 if (Attr.getNumArgs() > 0) {
2509 Expr *E = Attr.getArgAsExpr(0);
2510 llvm::APSInt Idx(32);
2511 if (E->isTypeDependent() || E->isValueDependent() ||
2512 !E->isIntegerConstantExpr(Idx, S.Context)) {
2513 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2514 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2515 << E->getSourceRange();
2519 if (Idx.isSigned() && Idx.isNegative()) {
2520 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2521 << E->getSourceRange();
2525 sentinel = Idx.getZExtValue();
2528 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2529 if (Attr.getNumArgs() > 1) {
2530 Expr *E = Attr.getArgAsExpr(1);
2531 llvm::APSInt Idx(32);
2532 if (E->isTypeDependent() || E->isValueDependent() ||
2533 !E->isIntegerConstantExpr(Idx, S.Context)) {
2534 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2535 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2536 << E->getSourceRange();
2539 nullPos = Idx.getZExtValue();
2541 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2542 // FIXME: This error message could be improved, it would be nice
2543 // to say what the bounds actually are.
2544 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2545 << E->getSourceRange();
2550 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2551 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2552 if (isa<FunctionNoProtoType>(FT)) {
2553 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2557 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2558 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2561 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2562 if (!MD->isVariadic()) {
2563 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2566 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2567 if (!BD->isVariadic()) {
2568 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2571 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2572 QualType Ty = V->getType();
2573 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2574 const FunctionType *FT = Ty->isFunctionPointerType()
2575 ? D->getFunctionType()
2576 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2577 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2578 int m = Ty->isFunctionPointerType() ? 0 : 1;
2579 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2583 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2584 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2588 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2589 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2592 D->addAttr(::new (S.Context)
2593 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2594 Attr.getAttributeSpellingListIndex()));
2597 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2598 if (D->getFunctionType() &&
2599 D->getFunctionType()->getReturnType()->isVoidType()) {
2600 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2601 << Attr.getName() << 0;
2604 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2605 if (MD->getReturnType()->isVoidType()) {
2606 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2607 << Attr.getName() << 1;
2611 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2612 // about using it as an extension.
2613 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2614 !Attr.getScopeName())
2615 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2617 D->addAttr(::new (S.Context)
2618 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2619 Attr.getAttributeSpellingListIndex()));
2622 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2623 // weak_import only applies to variable & function declarations.
2625 if (!D->canBeWeakImported(isDef)) {
2627 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2629 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2630 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2631 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2632 // Nothing to warn about here.
2634 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2635 << Attr.getName() << ExpectedVariableOrFunction;
2640 D->addAttr(::new (S.Context)
2641 WeakImportAttr(Attr.getRange(), S.Context,
2642 Attr.getAttributeSpellingListIndex()));
2645 // Handles reqd_work_group_size and work_group_size_hint.
2646 template <typename WorkGroupAttr>
2647 static void handleWorkGroupSize(Sema &S, Decl *D,
2648 const AttributeList &Attr) {
2650 for (unsigned i = 0; i < 3; ++i) {
2651 const Expr *E = Attr.getArgAsExpr(i);
2652 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2654 if (WGSize[i] == 0) {
2655 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2656 << Attr.getName() << E->getSourceRange();
2661 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2662 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2663 Existing->getYDim() == WGSize[1] &&
2664 Existing->getZDim() == WGSize[2]))
2665 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2667 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2668 WGSize[0], WGSize[1], WGSize[2],
2669 Attr.getAttributeSpellingListIndex()));
2672 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2673 if (!Attr.hasParsedType()) {
2674 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2675 << Attr.getName() << 1;
2679 TypeSourceInfo *ParmTSI = nullptr;
2680 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2681 assert(ParmTSI && "no type source info for attribute argument");
2683 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2684 (ParmType->isBooleanType() ||
2685 !ParmType->isIntegralType(S.getASTContext()))) {
2686 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2691 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2692 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2693 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2698 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2700 Attr.getAttributeSpellingListIndex()));
2703 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2705 unsigned AttrSpellingListIndex) {
2706 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2707 if (ExistingAttr->getName() == Name)
2709 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2710 Diag(Range.getBegin(), diag::note_previous_attribute);
2713 return ::new (Context) SectionAttr(Range, Context, Name,
2714 AttrSpellingListIndex);
2717 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2718 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2719 if (!Error.empty()) {
2720 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2726 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2727 // Make sure that there is a string literal as the sections's single
2730 SourceLocation LiteralLoc;
2731 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2734 if (!S.checkSectionName(LiteralLoc, Str))
2737 // If the target wants to validate the section specifier, make it happen.
2738 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2739 if (!Error.empty()) {
2740 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2745 unsigned Index = Attr.getAttributeSpellingListIndex();
2746 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2748 D->addAttr(NewAttr);
2751 // Check for things we'd like to warn about, no errors or validation for now.
2752 // TODO: Validation should use a backend target library that specifies
2753 // the allowable subtarget features and cpus. We could use something like a
2754 // TargetCodeGenInfo hook here to do validation.
2755 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2756 for (auto Str : {"tune=", "fpmath="})
2757 if (AttrStr.find(Str) != StringRef::npos)
2758 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2761 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2763 SourceLocation LiteralLoc;
2764 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2766 S.checkTargetAttr(LiteralLoc, Str);
2767 unsigned Index = Attr.getAttributeSpellingListIndex();
2768 TargetAttr *NewAttr =
2769 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2770 D->addAttr(NewAttr);
2773 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2774 VarDecl *VD = cast<VarDecl>(D);
2775 if (!VD->hasLocalStorage()) {
2776 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2780 Expr *E = Attr.getArgAsExpr(0);
2781 SourceLocation Loc = E->getExprLoc();
2782 FunctionDecl *FD = nullptr;
2783 DeclarationNameInfo NI;
2785 // gcc only allows for simple identifiers. Since we support more than gcc, we
2786 // will warn the user.
2787 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2788 if (DRE->hasQualifier())
2789 S.Diag(Loc, diag::warn_cleanup_ext);
2790 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2791 NI = DRE->getNameInfo();
2793 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2797 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2798 if (ULE->hasExplicitTemplateArgs())
2799 S.Diag(Loc, diag::warn_cleanup_ext);
2800 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2801 NI = ULE->getNameInfo();
2803 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2805 if (ULE->getType() == S.Context.OverloadTy)
2806 S.NoteAllOverloadCandidates(ULE);
2810 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2814 if (FD->getNumParams() != 1) {
2815 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2820 // We're currently more strict than GCC about what function types we accept.
2821 // If this ever proves to be a problem it should be easy to fix.
2822 QualType Ty = S.Context.getPointerType(VD->getType());
2823 QualType ParamTy = FD->getParamDecl(0)->getType();
2824 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2825 ParamTy, Ty) != Sema::Compatible) {
2826 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2827 << NI.getName() << ParamTy << Ty;
2831 D->addAttr(::new (S.Context)
2832 CleanupAttr(Attr.getRange(), S.Context, FD,
2833 Attr.getAttributeSpellingListIndex()));
2836 /// Handle __attribute__((format_arg((idx)))) attribute based on
2837 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2838 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2839 Expr *IdxExpr = Attr.getArgAsExpr(0);
2841 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2844 // Make sure the format string is really a string.
2845 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2847 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2848 if (NotNSStringTy &&
2849 !isCFStringType(Ty, S.Context) &&
2850 (!Ty->isPointerType() ||
2851 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2852 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2853 << "a string type" << IdxExpr->getSourceRange()
2854 << getFunctionOrMethodParamRange(D, 0);
2857 Ty = getFunctionOrMethodResultType(D);
2858 if (!isNSStringType(Ty, S.Context) &&
2859 !isCFStringType(Ty, S.Context) &&
2860 (!Ty->isPointerType() ||
2861 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2862 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2863 << (NotNSStringTy ? "string type" : "NSString")
2864 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2868 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2869 // because that has corrected for the implicit this parameter, and is zero-
2870 // based. The attribute expects what the user wrote explicitly.
2872 IdxExpr->EvaluateAsInt(Val, S.Context);
2874 D->addAttr(::new (S.Context)
2875 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2876 Attr.getAttributeSpellingListIndex()));
2879 enum FormatAttrKind {
2888 /// getFormatAttrKind - Map from format attribute names to supported format
2890 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2891 return llvm::StringSwitch<FormatAttrKind>(Format)
2892 // Check for formats that get handled specially.
2893 .Case("NSString", NSStringFormat)
2894 .Case("CFString", CFStringFormat)
2895 .Case("strftime", StrftimeFormat)
2897 // Otherwise, check for supported formats.
2898 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2899 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2900 .Case("kprintf", SupportedFormat) // OpenBSD.
2901 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2902 .Case("os_trace", SupportedFormat)
2903 .Case("os_log", SupportedFormat)
2905 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2906 .Default(InvalidFormat);
2909 /// Handle __attribute__((init_priority(priority))) attributes based on
2910 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2911 static void handleInitPriorityAttr(Sema &S, Decl *D,
2912 const AttributeList &Attr) {
2913 if (!S.getLangOpts().CPlusPlus) {
2914 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2918 if (S.getCurFunctionOrMethodDecl()) {
2919 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2923 QualType T = cast<VarDecl>(D)->getType();
2924 if (S.Context.getAsArrayType(T))
2925 T = S.Context.getBaseElementType(T);
2926 if (!T->getAs<RecordType>()) {
2927 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2932 Expr *E = Attr.getArgAsExpr(0);
2933 uint32_t prioritynum;
2934 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2939 if (prioritynum < 101 || prioritynum > 65535) {
2940 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2941 << E->getSourceRange() << Attr.getName() << 101 << 65535;
2945 D->addAttr(::new (S.Context)
2946 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2947 Attr.getAttributeSpellingListIndex()));
2950 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2951 IdentifierInfo *Format, int FormatIdx,
2953 unsigned AttrSpellingListIndex) {
2954 // Check whether we already have an equivalent format attribute.
2955 for (auto *F : D->specific_attrs<FormatAttr>()) {
2956 if (F->getType() == Format &&
2957 F->getFormatIdx() == FormatIdx &&
2958 F->getFirstArg() == FirstArg) {
2959 // If we don't have a valid location for this attribute, adopt the
2961 if (F->getLocation().isInvalid())
2967 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2968 FirstArg, AttrSpellingListIndex);
2971 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2972 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2973 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2974 if (!Attr.isArgIdent(0)) {
2975 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2976 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2980 // In C++ the implicit 'this' function parameter also counts, and they are
2981 // counted from one.
2982 bool HasImplicitThisParam = isInstanceMethod(D);
2983 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2985 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2986 StringRef Format = II->getName();
2988 if (normalizeName(Format)) {
2989 // If we've modified the string name, we need a new identifier for it.
2990 II = &S.Context.Idents.get(Format);
2993 // Check for supported formats.
2994 FormatAttrKind Kind = getFormatAttrKind(Format);
2996 if (Kind == IgnoredFormat)
2999 if (Kind == InvalidFormat) {
3000 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3001 << Attr.getName() << II->getName();
3005 // checks for the 2nd argument
3006 Expr *IdxExpr = Attr.getArgAsExpr(1);
3008 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3011 if (Idx < 1 || Idx > NumArgs) {
3012 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3013 << Attr.getName() << 2 << IdxExpr->getSourceRange();
3017 // FIXME: Do we need to bounds check?
3018 unsigned ArgIdx = Idx - 1;
3020 if (HasImplicitThisParam) {
3022 S.Diag(Attr.getLoc(),
3023 diag::err_format_attribute_implicit_this_format_string)
3024 << IdxExpr->getSourceRange();
3030 // make sure the format string is really a string
3031 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3033 if (Kind == CFStringFormat) {
3034 if (!isCFStringType(Ty, S.Context)) {
3035 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3036 << "a CFString" << IdxExpr->getSourceRange()
3037 << getFunctionOrMethodParamRange(D, ArgIdx);
3040 } else if (Kind == NSStringFormat) {
3041 // FIXME: do we need to check if the type is NSString*? What are the
3043 if (!isNSStringType(Ty, S.Context)) {
3044 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3045 << "an NSString" << IdxExpr->getSourceRange()
3046 << getFunctionOrMethodParamRange(D, ArgIdx);
3049 } else if (!Ty->isPointerType() ||
3050 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3051 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3052 << "a string type" << IdxExpr->getSourceRange()
3053 << getFunctionOrMethodParamRange(D, ArgIdx);
3057 // check the 3rd argument
3058 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3060 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3063 // check if the function is variadic if the 3rd argument non-zero
3064 if (FirstArg != 0) {
3065 if (isFunctionOrMethodVariadic(D)) {
3066 ++NumArgs; // +1 for ...
3068 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3073 // strftime requires FirstArg to be 0 because it doesn't read from any
3074 // variable the input is just the current time + the format string.
3075 if (Kind == StrftimeFormat) {
3076 if (FirstArg != 0) {
3077 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3078 << FirstArgExpr->getSourceRange();
3081 // if 0 it disables parameter checking (to use with e.g. va_list)
3082 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3083 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3084 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3088 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3090 Attr.getAttributeSpellingListIndex());
3092 D->addAttr(NewAttr);
3095 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3096 const AttributeList &Attr) {
3097 // Try to find the underlying union declaration.
3098 RecordDecl *RD = nullptr;
3099 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3100 if (TD && TD->getUnderlyingType()->isUnionType())
3101 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3103 RD = dyn_cast<RecordDecl>(D);
3105 if (!RD || !RD->isUnion()) {
3106 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3107 << Attr.getName() << ExpectedUnion;
3111 if (!RD->isCompleteDefinition()) {
3112 S.Diag(Attr.getLoc(),
3113 diag::warn_transparent_union_attribute_not_definition);
3117 RecordDecl::field_iterator Field = RD->field_begin(),
3118 FieldEnd = RD->field_end();
3119 if (Field == FieldEnd) {
3120 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3124 FieldDecl *FirstField = *Field;
3125 QualType FirstType = FirstField->getType();
3126 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3127 S.Diag(FirstField->getLocation(),
3128 diag::warn_transparent_union_attribute_floating)
3129 << FirstType->isVectorType() << FirstType;
3133 if (FirstType->isIncompleteType())
3135 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3136 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3137 for (; Field != FieldEnd; ++Field) {
3138 QualType FieldType = Field->getType();
3139 if (FieldType->isIncompleteType())
3141 // FIXME: this isn't fully correct; we also need to test whether the
3142 // members of the union would all have the same calling convention as the
3143 // first member of the union. Checking just the size and alignment isn't
3144 // sufficient (consider structs passed on the stack instead of in registers
3146 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3147 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3148 // Warn if we drop the attribute.
3149 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3150 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3151 : S.Context.getTypeAlign(FieldType);
3152 S.Diag(Field->getLocation(),
3153 diag::warn_transparent_union_attribute_field_size_align)
3154 << isSize << Field->getDeclName() << FieldBits;
3155 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3156 S.Diag(FirstField->getLocation(),
3157 diag::note_transparent_union_first_field_size_align)
3158 << isSize << FirstBits;
3163 RD->addAttr(::new (S.Context)
3164 TransparentUnionAttr(Attr.getRange(), S.Context,
3165 Attr.getAttributeSpellingListIndex()));
3168 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3169 // Make sure that there is a string literal as the annotation's single
3172 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3175 // Don't duplicate annotations that are already set.
3176 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3177 if (I->getAnnotation() == Str)
3181 D->addAttr(::new (S.Context)
3182 AnnotateAttr(Attr.getRange(), S.Context, Str,
3183 Attr.getAttributeSpellingListIndex()));
3186 static void handleAlignValueAttr(Sema &S, Decl *D,
3187 const AttributeList &Attr) {
3188 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3189 Attr.getAttributeSpellingListIndex());
3192 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3193 unsigned SpellingListIndex) {
3194 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3195 SourceLocation AttrLoc = AttrRange.getBegin();
3198 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3199 T = TD->getUnderlyingType();
3200 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3203 llvm_unreachable("Unknown decl type for align_value");
3205 if (!T->isDependentType() && !T->isAnyPointerType() &&
3206 !T->isReferenceType() && !T->isMemberPointerType()) {
3207 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3208 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3212 if (!E->isValueDependent()) {
3213 llvm::APSInt Alignment;
3215 = VerifyIntegerConstantExpression(E, &Alignment,
3216 diag::err_align_value_attribute_argument_not_int,
3217 /*AllowFold*/ false);
3218 if (ICE.isInvalid())
3221 if (!Alignment.isPowerOf2()) {
3222 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3223 << E->getSourceRange();
3227 D->addAttr(::new (Context)
3228 AlignValueAttr(AttrRange, Context, ICE.get(),
3229 SpellingListIndex));
3233 // Save dependent expressions in the AST to be instantiated.
3234 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3237 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3238 // check the attribute arguments.
3239 if (Attr.getNumArgs() > 1) {
3240 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3241 << Attr.getName() << 1;
3245 if (Attr.getNumArgs() == 0) {
3246 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3247 true, nullptr, Attr.getAttributeSpellingListIndex()));
3251 Expr *E = Attr.getArgAsExpr(0);
3252 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3253 S.Diag(Attr.getEllipsisLoc(),
3254 diag::err_pack_expansion_without_parameter_packs);
3258 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3261 if (E->isValueDependent()) {
3262 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3263 if (!TND->getUnderlyingType()->isDependentType()) {
3264 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3265 << E->getSourceRange();
3271 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3272 Attr.isPackExpansion());
3275 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3276 unsigned SpellingListIndex, bool IsPackExpansion) {
3277 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3278 SourceLocation AttrLoc = AttrRange.getBegin();
3280 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3281 if (TmpAttr.isAlignas()) {
3282 // C++11 [dcl.align]p1:
3283 // An alignment-specifier may be applied to a variable or to a class
3284 // data member, but it shall not be applied to a bit-field, a function
3285 // parameter, the formal parameter of a catch clause, or a variable
3286 // declared with the register storage class specifier. An
3287 // alignment-specifier may also be applied to the declaration of a class
3288 // or enumeration type.
3290 // An alignment attribute shall not be specified in a declaration of
3291 // a typedef, or a bit-field, or a function, or a parameter, or an
3292 // object declared with the register storage-class specifier.
3294 if (isa<ParmVarDecl>(D)) {
3296 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3297 if (VD->getStorageClass() == SC_Register)
3299 if (VD->isExceptionVariable())
3301 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3302 if (FD->isBitField())
3304 } else if (!isa<TagDecl>(D)) {
3305 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3306 << (TmpAttr.isC11() ? ExpectedVariableOrField
3307 : ExpectedVariableFieldOrTag);
3310 if (DiagKind != -1) {
3311 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3312 << &TmpAttr << DiagKind;
3317 if (E->isTypeDependent() || E->isValueDependent()) {
3318 // Save dependent expressions in the AST to be instantiated.
3319 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3320 AA->setPackExpansion(IsPackExpansion);
3325 // FIXME: Cache the number on the Attr object?
3326 llvm::APSInt Alignment;
3328 = VerifyIntegerConstantExpression(E, &Alignment,
3329 diag::err_aligned_attribute_argument_not_int,
3330 /*AllowFold*/ false);
3331 if (ICE.isInvalid())
3334 uint64_t AlignVal = Alignment.getZExtValue();
3336 // C++11 [dcl.align]p2:
3337 // -- if the constant expression evaluates to zero, the alignment
3338 // specifier shall have no effect
3340 // An alignment specification of zero has no effect.
3341 if (!(TmpAttr.isAlignas() && !Alignment)) {
3342 if (!llvm::isPowerOf2_64(AlignVal)) {
3343 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3344 << E->getSourceRange();
3349 // Alignment calculations can wrap around if it's greater than 2**28.
3350 unsigned MaxValidAlignment =
3351 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3353 if (AlignVal > MaxValidAlignment) {
3354 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3355 << E->getSourceRange();
3359 if (Context.getTargetInfo().isTLSSupported()) {
3360 unsigned MaxTLSAlign =
3361 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3363 auto *VD = dyn_cast<VarDecl>(D);
3364 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3365 VD->getTLSKind() != VarDecl::TLS_None) {
3366 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3367 << (unsigned)AlignVal << VD << MaxTLSAlign;
3372 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3373 ICE.get(), SpellingListIndex);
3374 AA->setPackExpansion(IsPackExpansion);
3378 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3379 unsigned SpellingListIndex, bool IsPackExpansion) {
3380 // FIXME: Cache the number on the Attr object if non-dependent?
3381 // FIXME: Perform checking of type validity
3382 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3384 AA->setPackExpansion(IsPackExpansion);
3388 void Sema::CheckAlignasUnderalignment(Decl *D) {
3389 assert(D->hasAttrs() && "no attributes on decl");
3391 QualType UnderlyingTy, DiagTy;
3392 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3393 UnderlyingTy = DiagTy = VD->getType();
3395 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3396 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3397 UnderlyingTy = ED->getIntegerType();
3399 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3402 // C++11 [dcl.align]p5, C11 6.7.5/4:
3403 // The combined effect of all alignment attributes in a declaration shall
3404 // not specify an alignment that is less strict than the alignment that
3405 // would otherwise be required for the entity being declared.
3406 AlignedAttr *AlignasAttr = nullptr;
3408 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3409 if (I->isAlignmentDependent())
3413 Align = std::max(Align, I->getAlignment(Context));
3416 if (AlignasAttr && Align) {
3417 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3418 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3419 if (NaturalAlign > RequestedAlign)
3420 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3421 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3425 bool Sema::checkMSInheritanceAttrOnDefinition(
3426 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3427 MSInheritanceAttr::Spelling SemanticSpelling) {
3428 assert(RD->hasDefinition() && "RD has no definition!");
3430 // We may not have seen base specifiers or any virtual methods yet. We will
3431 // have to wait until the record is defined to catch any mismatches.
3432 if (!RD->getDefinition()->isCompleteDefinition())
3435 // The unspecified model never matches what a definition could need.
3436 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3440 if (RD->calculateInheritanceModel() == SemanticSpelling)
3443 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3447 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3448 << 0 /*definition*/;
3449 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3450 << RD->getNameAsString();
3454 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3456 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3457 bool &IntegerMode, bool &ComplexMode) {
3459 ComplexMode = false;
3460 switch (Str.size()) {
3482 if (Str[1] == 'F') {
3483 IntegerMode = false;
3484 } else if (Str[1] == 'C') {
3485 IntegerMode = false;
3487 } else if (Str[1] != 'I') {
3492 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3493 // pointer on PIC16 and other embedded platforms.
3495 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3496 else if (Str == "byte")
3497 DestWidth = S.Context.getTargetInfo().getCharWidth();
3500 if (Str == "pointer")
3501 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3504 if (Str == "unwind_word")
3505 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3510 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3513 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3514 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3515 /// HImode, not an intermediate pointer.
3516 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3517 // This attribute isn't documented, but glibc uses it. It changes
3518 // the width of an int or unsigned int to the specified size.
3519 if (!Attr.isArgIdent(0)) {
3520 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3521 << AANT_ArgumentIdentifier;
3525 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3527 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3530 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3531 unsigned SpellingListIndex, bool InInstantiation) {
3532 StringRef Str = Name->getName();
3534 SourceLocation AttrLoc = AttrRange.getBegin();
3536 unsigned DestWidth = 0;
3537 bool IntegerMode = true;
3538 bool ComplexMode = false;
3539 llvm::APInt VectorSize(64, 0);
3540 if (Str.size() >= 4 && Str[0] == 'V') {
3541 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3542 size_t StrSize = Str.size();
3543 size_t VectorStringLength = 0;
3544 while ((VectorStringLength + 1) < StrSize &&
3545 isdigit(Str[VectorStringLength + 1]))
3546 ++VectorStringLength;
3547 if (VectorStringLength &&
3548 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3549 VectorSize.isPowerOf2()) {
3550 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3551 IntegerMode, ComplexMode);
3552 // Avoid duplicate warning from template instantiation.
3553 if (!InInstantiation)
3554 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3561 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3563 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3564 // and friends, at least with glibc.
3565 // FIXME: Make sure floating-point mappings are accurate
3566 // FIXME: Support XF and TF types
3568 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3573 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3574 OldTy = TD->getUnderlyingType();
3575 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3576 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3577 // Try to get type from enum declaration, default to int.
3578 OldTy = ED->getIntegerType();
3580 OldTy = Context.IntTy;
3582 OldTy = cast<ValueDecl>(D)->getType();
3584 if (OldTy->isDependentType()) {
3585 D->addAttr(::new (Context)
3586 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3590 // Base type can also be a vector type (see PR17453).
3591 // Distinguish between base type and base element type.
3592 QualType OldElemTy = OldTy;
3593 if (const VectorType *VT = OldTy->getAs<VectorType>())
3594 OldElemTy = VT->getElementType();
3596 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3597 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3598 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3599 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3600 VectorSize.getBoolValue()) {
3601 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3604 bool IntegralOrAnyEnumType =
3605 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3607 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3608 !IntegralOrAnyEnumType)
3609 Diag(AttrLoc, diag::err_mode_not_primitive);
3610 else if (IntegerMode) {
3611 if (!IntegralOrAnyEnumType)
3612 Diag(AttrLoc, diag::err_mode_wrong_type);
3613 } else if (ComplexMode) {
3614 if (!OldElemTy->isComplexType())
3615 Diag(AttrLoc, diag::err_mode_wrong_type);
3617 if (!OldElemTy->isFloatingType())
3618 Diag(AttrLoc, diag::err_mode_wrong_type);
3624 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3625 OldElemTy->isSignedIntegerType());
3627 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3629 if (NewElemTy.isNull()) {
3630 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3635 NewElemTy = Context.getComplexType(NewElemTy);
3638 QualType NewTy = NewElemTy;
3639 if (VectorSize.getBoolValue()) {
3640 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3641 VectorType::GenericVector);
3642 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3643 // Complex machine mode does not support base vector types.
3645 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3648 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3649 OldVT->getNumElements() /
3650 Context.getTypeSize(NewElemTy);
3652 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3655 if (NewTy.isNull()) {
3656 Diag(AttrLoc, diag::err_mode_wrong_type);
3660 // Install the new type.
3661 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3662 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3663 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3664 ED->setIntegerType(NewTy);
3666 cast<ValueDecl>(D)->setType(NewTy);
3668 D->addAttr(::new (Context)
3669 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3672 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3673 D->addAttr(::new (S.Context)
3674 NoDebugAttr(Attr.getRange(), S.Context,
3675 Attr.getAttributeSpellingListIndex()));
3678 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3679 IdentifierInfo *Ident,
3680 unsigned AttrSpellingListIndex) {
3681 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3682 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3683 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3687 if (D->hasAttr<AlwaysInlineAttr>())
3690 return ::new (Context) AlwaysInlineAttr(Range, Context,
3691 AttrSpellingListIndex);
3694 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3695 IdentifierInfo *Ident,
3696 unsigned AttrSpellingListIndex) {
3697 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3700 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3703 InternalLinkageAttr *
3704 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3705 IdentifierInfo *Ident,
3706 unsigned AttrSpellingListIndex) {
3707 if (auto VD = dyn_cast<VarDecl>(D)) {
3708 // Attribute applies to Var but not any subclass of it (like ParmVar,
3709 // ImplicitParm or VarTemplateSpecialization).
3710 if (VD->getKind() != Decl::Var) {
3711 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3712 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3713 : ExpectedVariableOrFunction);
3716 // Attribute does not apply to non-static local variables.
3717 if (VD->hasLocalStorage()) {
3718 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3723 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3726 return ::new (Context)
3727 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3730 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3731 unsigned AttrSpellingListIndex) {
3732 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3733 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3734 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3738 if (D->hasAttr<MinSizeAttr>())
3741 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3744 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3745 unsigned AttrSpellingListIndex) {
3746 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3747 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3748 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3749 D->dropAttr<AlwaysInlineAttr>();
3751 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3752 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3753 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3754 D->dropAttr<MinSizeAttr>();
3757 if (D->hasAttr<OptimizeNoneAttr>())
3760 return ::new (Context) OptimizeNoneAttr(Range, Context,
3761 AttrSpellingListIndex);
3764 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3765 const AttributeList &Attr) {
3766 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3770 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3771 D, Attr.getRange(), Attr.getName(),
3772 Attr.getAttributeSpellingListIndex()))
3776 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3777 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3778 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3779 D->addAttr(MinSize);
3782 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3783 const AttributeList &Attr) {
3784 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3785 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3786 D->addAttr(Optnone);
3789 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3790 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
3793 auto *VD = cast<VarDecl>(D);
3794 if (!VD->hasGlobalStorage()) {
3795 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
3798 D->addAttr(::new (S.Context) CUDAConstantAttr(
3799 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3802 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3803 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
3806 auto *VD = cast<VarDecl>(D);
3807 // extern __shared__ is only allowed on arrays with no length (e.g.
3809 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
3810 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
3813 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
3814 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
3815 << S.CurrentCUDATarget())
3817 D->addAttr(::new (S.Context) CUDASharedAttr(
3818 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3821 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3822 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
3824 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
3828 FunctionDecl *FD = cast<FunctionDecl>(D);
3829 if (!FD->getReturnType()->isVoidType()) {
3830 SourceRange RTRange = FD->getReturnTypeSourceRange();
3831 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3833 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3837 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
3838 if (Method->isInstance()) {
3839 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
3843 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
3845 // Only warn for "inline" when compiling for host, to cut down on noise.
3846 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
3847 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
3849 D->addAttr(::new (S.Context)
3850 CUDAGlobalAttr(Attr.getRange(), S.Context,
3851 Attr.getAttributeSpellingListIndex()));
3854 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3855 FunctionDecl *Fn = cast<FunctionDecl>(D);
3856 if (!Fn->isInlineSpecified()) {
3857 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3861 D->addAttr(::new (S.Context)
3862 GNUInlineAttr(Attr.getRange(), S.Context,
3863 Attr.getAttributeSpellingListIndex()));
3866 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3867 if (hasDeclarator(D)) return;
3869 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3870 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3872 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
3875 if (!isa<ObjCMethodDecl>(D)) {
3876 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3877 << Attr.getName() << ExpectedFunctionOrMethod;
3881 switch (Attr.getKind()) {
3882 case AttributeList::AT_FastCall:
3883 D->addAttr(::new (S.Context)
3884 FastCallAttr(Attr.getRange(), S.Context,
3885 Attr.getAttributeSpellingListIndex()));
3887 case AttributeList::AT_StdCall:
3888 D->addAttr(::new (S.Context)
3889 StdCallAttr(Attr.getRange(), S.Context,
3890 Attr.getAttributeSpellingListIndex()));
3892 case AttributeList::AT_ThisCall:
3893 D->addAttr(::new (S.Context)
3894 ThisCallAttr(Attr.getRange(), S.Context,
3895 Attr.getAttributeSpellingListIndex()));
3897 case AttributeList::AT_CDecl:
3898 D->addAttr(::new (S.Context)
3899 CDeclAttr(Attr.getRange(), S.Context,
3900 Attr.getAttributeSpellingListIndex()));
3902 case AttributeList::AT_Pascal:
3903 D->addAttr(::new (S.Context)
3904 PascalAttr(Attr.getRange(), S.Context,
3905 Attr.getAttributeSpellingListIndex()));
3907 case AttributeList::AT_SwiftCall:
3908 D->addAttr(::new (S.Context)
3909 SwiftCallAttr(Attr.getRange(), S.Context,
3910 Attr.getAttributeSpellingListIndex()));
3912 case AttributeList::AT_VectorCall:
3913 D->addAttr(::new (S.Context)
3914 VectorCallAttr(Attr.getRange(), S.Context,
3915 Attr.getAttributeSpellingListIndex()));
3917 case AttributeList::AT_MSABI:
3918 D->addAttr(::new (S.Context)
3919 MSABIAttr(Attr.getRange(), S.Context,
3920 Attr.getAttributeSpellingListIndex()));
3922 case AttributeList::AT_SysVABI:
3923 D->addAttr(::new (S.Context)
3924 SysVABIAttr(Attr.getRange(), S.Context,
3925 Attr.getAttributeSpellingListIndex()));
3927 case AttributeList::AT_RegCall:
3928 D->addAttr(::new (S.Context) RegCallAttr(
3929 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3931 case AttributeList::AT_Pcs: {
3932 PcsAttr::PCSType PCS;
3935 PCS = PcsAttr::AAPCS;
3938 PCS = PcsAttr::AAPCS_VFP;
3941 llvm_unreachable("unexpected calling convention in pcs attribute");
3944 D->addAttr(::new (S.Context)
3945 PcsAttr(Attr.getRange(), S.Context, PCS,
3946 Attr.getAttributeSpellingListIndex()));
3949 case AttributeList::AT_IntelOclBicc:
3950 D->addAttr(::new (S.Context)
3951 IntelOclBiccAttr(Attr.getRange(), S.Context,
3952 Attr.getAttributeSpellingListIndex()));
3954 case AttributeList::AT_PreserveMost:
3955 D->addAttr(::new (S.Context) PreserveMostAttr(
3956 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3958 case AttributeList::AT_PreserveAll:
3959 D->addAttr(::new (S.Context) PreserveAllAttr(
3960 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3963 llvm_unreachable("unexpected attribute kind");
3967 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3968 const FunctionDecl *FD) {
3969 if (attr.isInvalid())
3972 if (attr.hasProcessingCache()) {
3973 CC = (CallingConv) attr.getProcessingCache();
3977 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3978 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3983 // TODO: diagnose uses of these conventions on the wrong target.
3984 switch (attr.getKind()) {
3985 case AttributeList::AT_CDecl: CC = CC_C; break;
3986 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3987 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3988 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3989 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3990 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
3991 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3992 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
3993 case AttributeList::AT_MSABI:
3994 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3997 case AttributeList::AT_SysVABI:
3998 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4001 case AttributeList::AT_Pcs: {
4003 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
4007 if (StrRef == "aapcs") {
4010 } else if (StrRef == "aapcs-vfp") {
4016 Diag(attr.getLoc(), diag::err_invalid_pcs);
4019 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4020 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4021 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4022 default: llvm_unreachable("unexpected attribute kind");
4025 const TargetInfo &TI = Context.getTargetInfo();
4026 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4027 if (A != TargetInfo::CCCR_OK) {
4028 if (A == TargetInfo::CCCR_Warning)
4029 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
4031 // This convention is not valid for the target. Use the default function or
4032 // method calling convention.
4033 bool IsCXXMethod = false, IsVariadic = false;
4035 IsCXXMethod = FD->isCXXInstanceMember();
4036 IsVariadic = FD->isVariadic();
4038 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4041 attr.setProcessingCache((unsigned) CC);
4045 /// Pointer-like types in the default address space.
4046 static bool isValidSwiftContextType(QualType type) {
4047 if (!type->hasPointerRepresentation())
4048 return type->isDependentType();
4049 return type->getPointeeType().getAddressSpace() == 0;
4052 /// Pointers and references in the default address space.
4053 static bool isValidSwiftIndirectResultType(QualType type) {
4054 if (auto ptrType = type->getAs<PointerType>()) {
4055 type = ptrType->getPointeeType();
4056 } else if (auto refType = type->getAs<ReferenceType>()) {
4057 type = refType->getPointeeType();
4059 return type->isDependentType();
4061 return type.getAddressSpace() == 0;
4064 /// Pointers and references to pointers in the default address space.
4065 static bool isValidSwiftErrorResultType(QualType type) {
4066 if (auto ptrType = type->getAs<PointerType>()) {
4067 type = ptrType->getPointeeType();
4068 } else if (auto refType = type->getAs<ReferenceType>()) {
4069 type = refType->getPointeeType();
4071 return type->isDependentType();
4073 if (!type.getQualifiers().empty())
4075 return isValidSwiftContextType(type);
4078 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4080 S.AddParameterABIAttr(attr.getRange(), D, abi,
4081 attr.getAttributeSpellingListIndex());
4084 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4085 unsigned spellingIndex) {
4087 QualType type = cast<ParmVarDecl>(D)->getType();
4089 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4090 if (existingAttr->getABI() != abi) {
4091 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4092 << getParameterABISpelling(abi) << existingAttr;
4093 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4099 case ParameterABI::Ordinary:
4100 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4102 case ParameterABI::SwiftContext:
4103 if (!isValidSwiftContextType(type)) {
4104 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4105 << getParameterABISpelling(abi)
4106 << /*pointer to pointer */ 0 << type;
4108 D->addAttr(::new (Context)
4109 SwiftContextAttr(range, Context, spellingIndex));
4112 case ParameterABI::SwiftErrorResult:
4113 if (!isValidSwiftErrorResultType(type)) {
4114 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4115 << getParameterABISpelling(abi)
4116 << /*pointer to pointer */ 1 << type;
4118 D->addAttr(::new (Context)
4119 SwiftErrorResultAttr(range, Context, spellingIndex));
4122 case ParameterABI::SwiftIndirectResult:
4123 if (!isValidSwiftIndirectResultType(type)) {
4124 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4125 << getParameterABISpelling(abi)
4126 << /*pointer*/ 0 << type;
4128 D->addAttr(::new (Context)
4129 SwiftIndirectResultAttr(range, Context, spellingIndex));
4132 llvm_unreachable("bad parameter ABI attribute");
4135 /// Checks a regparm attribute, returning true if it is ill-formed and
4136 /// otherwise setting numParams to the appropriate value.
4137 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4138 if (Attr.isInvalid())
4141 if (!checkAttributeNumArgs(*this, Attr, 1)) {
4147 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4148 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4153 if (Context.getTargetInfo().getRegParmMax() == 0) {
4154 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4155 << NumParamsExpr->getSourceRange();
4161 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4162 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4163 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4171 // Checks whether an argument of launch_bounds attribute is
4172 // acceptable, performs implicit conversion to Rvalue, and returns
4173 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4174 // and may output an error.
4175 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4176 const CUDALaunchBoundsAttr &Attr,
4177 const unsigned Idx) {
4178 if (S.DiagnoseUnexpandedParameterPack(E))
4181 // Accept template arguments for now as they depend on something else.
4182 // We'll get to check them when they eventually get instantiated.
4183 if (E->isValueDependent())
4187 if (!E->isIntegerConstantExpr(I, S.Context)) {
4188 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4189 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4192 // Make sure we can fit it in 32 bits.
4193 if (!I.isIntN(32)) {
4194 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4195 << 32 << /* Unsigned */ 1;
4199 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4200 << &Attr << Idx << E->getSourceRange();
4202 // We may need to perform implicit conversion of the argument.
4203 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4204 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4205 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4206 assert(!ValArg.isInvalid() &&
4207 "Unexpected PerformCopyInitialization() failure.");
4209 return ValArg.getAs<Expr>();
4212 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4213 Expr *MinBlocks, unsigned SpellingListIndex) {
4214 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4216 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4217 if (MaxThreads == nullptr)
4221 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4222 if (MinBlocks == nullptr)
4226 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4227 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4230 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4231 const AttributeList &Attr) {
4232 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4233 !checkAttributeAtMostNumArgs(S, Attr, 2))
4236 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4237 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4238 Attr.getAttributeSpellingListIndex());
4241 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4242 const AttributeList &Attr) {
4243 if (!Attr.isArgIdent(0)) {
4244 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4245 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4249 if (!checkAttributeNumArgs(S, Attr, 3))
4252 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4254 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4255 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4256 << Attr.getName() << ExpectedFunctionOrMethod;
4260 uint64_t ArgumentIdx;
4261 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4265 uint64_t TypeTagIdx;
4266 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4270 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4272 // Ensure that buffer has a pointer type.
4273 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4274 if (!BufferTy->isPointerType()) {
4275 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4276 << Attr.getName() << 0;
4280 D->addAttr(::new (S.Context)
4281 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4282 ArgumentIdx, TypeTagIdx, IsPointer,
4283 Attr.getAttributeSpellingListIndex()));
4286 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4287 const AttributeList &Attr) {
4288 if (!Attr.isArgIdent(0)) {
4289 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4290 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4294 if (!checkAttributeNumArgs(S, Attr, 1))
4297 if (!isa<VarDecl>(D)) {
4298 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4299 << Attr.getName() << ExpectedVariable;
4303 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4304 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4305 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4306 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4308 D->addAttr(::new (S.Context)
4309 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4311 Attr.getLayoutCompatible(),
4312 Attr.getMustBeNull(),
4313 Attr.getAttributeSpellingListIndex()));
4316 //===----------------------------------------------------------------------===//
4317 // Checker-specific attribute handlers.
4318 //===----------------------------------------------------------------------===//
4320 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4321 return type->isDependentType() ||
4322 type->isObjCRetainableType();
4325 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4326 return type->isDependentType() ||
4327 type->isObjCObjectPointerType() ||
4328 S.Context.isObjCNSObjectType(type);
4331 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4332 return type->isDependentType() ||
4333 type->isPointerType() ||
4334 isValidSubjectOfNSAttribute(S, type);
4337 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4338 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4339 Attr.getKind() == AttributeList::AT_NSConsumed,
4340 /*template instantiation*/ false);
4343 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4344 unsigned spellingIndex, bool isNSConsumed,
4345 bool isTemplateInstantiation) {
4346 ParmVarDecl *param = cast<ParmVarDecl>(D);
4350 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4352 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4356 // These attributes are normally just advisory, but in ARC, ns_consumed
4357 // is significant. Allow non-dependent code to contain inappropriate
4358 // attributes even in ARC, but require template instantiations to be
4359 // set up correctly.
4360 Diag(D->getLocStart(),
4361 (isTemplateInstantiation && isNSConsumed &&
4362 getLangOpts().ObjCAutoRefCount
4363 ? diag::err_ns_attribute_wrong_parameter_type
4364 : diag::warn_ns_attribute_wrong_parameter_type))
4366 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4367 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4372 param->addAttr(::new (Context)
4373 NSConsumedAttr(attrRange, Context, spellingIndex));
4375 param->addAttr(::new (Context)
4376 CFConsumedAttr(attrRange, Context, spellingIndex));
4379 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4380 const AttributeList &Attr) {
4381 QualType returnType;
4383 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4384 returnType = MD->getReturnType();
4385 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4386 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4387 return; // ignore: was handled as a type attribute
4388 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4389 returnType = PD->getType();
4390 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4391 returnType = FD->getReturnType();
4392 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4393 returnType = Param->getType()->getPointeeType();
4394 if (returnType.isNull()) {
4395 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4396 << Attr.getName() << /*pointer-to-CF*/2
4401 AttributeDeclKind ExpectedDeclKind;
4402 switch (Attr.getKind()) {
4403 default: llvm_unreachable("invalid ownership attribute");
4404 case AttributeList::AT_NSReturnsRetained:
4405 case AttributeList::AT_NSReturnsAutoreleased:
4406 case AttributeList::AT_NSReturnsNotRetained:
4407 ExpectedDeclKind = ExpectedFunctionOrMethod;
4410 case AttributeList::AT_CFReturnsRetained:
4411 case AttributeList::AT_CFReturnsNotRetained:
4412 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4415 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4416 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4422 switch (Attr.getKind()) {
4423 default: llvm_unreachable("invalid ownership attribute");
4424 case AttributeList::AT_NSReturnsRetained:
4425 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4429 case AttributeList::AT_NSReturnsAutoreleased:
4430 case AttributeList::AT_NSReturnsNotRetained:
4431 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4435 case AttributeList::AT_CFReturnsRetained:
4436 case AttributeList::AT_CFReturnsNotRetained:
4437 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4443 if (isa<ParmVarDecl>(D)) {
4444 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4445 << Attr.getName() << /*pointer-to-CF*/2
4448 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4453 } SubjectKind = Function;
4454 if (isa<ObjCMethodDecl>(D))
4455 SubjectKind = Method;
4456 else if (isa<ObjCPropertyDecl>(D))
4457 SubjectKind = Property;
4458 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4459 << Attr.getName() << SubjectKind << cf
4465 switch (Attr.getKind()) {
4467 llvm_unreachable("invalid ownership attribute");
4468 case AttributeList::AT_NSReturnsAutoreleased:
4469 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4470 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4472 case AttributeList::AT_CFReturnsNotRetained:
4473 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4474 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4476 case AttributeList::AT_NSReturnsNotRetained:
4477 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4478 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4480 case AttributeList::AT_CFReturnsRetained:
4481 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4482 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4484 case AttributeList::AT_NSReturnsRetained:
4485 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4486 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4491 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4492 const AttributeList &attr) {
4493 const int EP_ObjCMethod = 1;
4494 const int EP_ObjCProperty = 2;
4496 SourceLocation loc = attr.getLoc();
4497 QualType resultType;
4498 if (isa<ObjCMethodDecl>(D))
4499 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4501 resultType = cast<ObjCPropertyDecl>(D)->getType();
4503 if (!resultType->isReferenceType() &&
4504 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4505 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4508 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4509 << /*non-retainable pointer*/ 2;
4511 // Drop the attribute.
4515 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4516 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4519 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4520 const AttributeList &attr) {
4521 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4523 DeclContext *DC = method->getDeclContext();
4524 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4525 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4526 << attr.getName() << 0;
4527 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4530 if (method->getMethodFamily() == OMF_dealloc) {
4531 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4532 << attr.getName() << 1;
4536 method->addAttr(::new (S.Context)
4537 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4538 attr.getAttributeSpellingListIndex()));
4541 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4542 const AttributeList &Attr) {
4543 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4547 D->addAttr(::new (S.Context)
4548 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4549 Attr.getAttributeSpellingListIndex()));
4552 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4553 const AttributeList &Attr) {
4554 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4558 D->addAttr(::new (S.Context)
4559 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4560 Attr.getAttributeSpellingListIndex()));
4563 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4564 const AttributeList &Attr) {
4565 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4568 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4572 // Typedefs only allow objc_bridge(id) and have some additional checking.
4573 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4574 if (!Parm->Ident->isStr("id")) {
4575 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4580 // Only allow 'cv void *'.
4581 QualType T = TD->getUnderlyingType();
4582 if (!T->isVoidPointerType()) {
4583 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4588 D->addAttr(::new (S.Context)
4589 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4590 Attr.getAttributeSpellingListIndex()));
4593 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4594 const AttributeList &Attr) {
4595 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4598 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4602 D->addAttr(::new (S.Context)
4603 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4604 Attr.getAttributeSpellingListIndex()));
4607 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4608 const AttributeList &Attr) {
4609 IdentifierInfo *RelatedClass =
4610 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4611 if (!RelatedClass) {
4612 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4615 IdentifierInfo *ClassMethod =
4616 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4617 IdentifierInfo *InstanceMethod =
4618 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4619 D->addAttr(::new (S.Context)
4620 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4621 ClassMethod, InstanceMethod,
4622 Attr.getAttributeSpellingListIndex()));
4625 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4626 const AttributeList &Attr) {
4627 ObjCInterfaceDecl *IFace;
4628 if (ObjCCategoryDecl *CatDecl =
4629 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4630 IFace = CatDecl->getClassInterface();
4632 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4637 IFace->setHasDesignatedInitializers();
4638 D->addAttr(::new (S.Context)
4639 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4640 Attr.getAttributeSpellingListIndex()));
4643 static void handleObjCRuntimeName(Sema &S, Decl *D,
4644 const AttributeList &Attr) {
4645 StringRef MetaDataName;
4646 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4648 D->addAttr(::new (S.Context)
4649 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4651 Attr.getAttributeSpellingListIndex()));
4654 // When a user wants to use objc_boxable with a union or struct
4655 // but they don't have access to the declaration (legacy/third-party code)
4656 // then they can 'enable' this feature with a typedef:
4657 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4658 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4659 bool notify = false;
4661 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4662 if (RD && RD->getDefinition()) {
4663 RD = RD->getDefinition();
4668 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4669 ObjCBoxableAttr(Attr.getRange(), S.Context,
4670 Attr.getAttributeSpellingListIndex());
4671 RD->addAttr(BoxableAttr);
4673 // we need to notify ASTReader/ASTWriter about
4674 // modification of existing declaration
4675 if (ASTMutationListener *L = S.getASTMutationListener())
4676 L->AddedAttributeToRecord(BoxableAttr, RD);
4681 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4682 const AttributeList &Attr) {
4683 if (hasDeclarator(D)) return;
4685 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4686 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4689 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4690 const AttributeList &Attr) {
4691 ValueDecl *vd = cast<ValueDecl>(D);
4692 QualType type = vd->getType();
4694 if (!type->isDependentType() &&
4695 !type->isObjCLifetimeType()) {
4696 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4701 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4703 // If we have no lifetime yet, check the lifetime we're presumably
4705 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4706 lifetime = type->getObjCARCImplicitLifetime();
4709 case Qualifiers::OCL_None:
4710 assert(type->isDependentType() &&
4711 "didn't infer lifetime for non-dependent type?");
4714 case Qualifiers::OCL_Weak: // meaningful
4715 case Qualifiers::OCL_Strong: // meaningful
4718 case Qualifiers::OCL_ExplicitNone:
4719 case Qualifiers::OCL_Autoreleasing:
4720 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4721 << (lifetime == Qualifiers::OCL_Autoreleasing);
4725 D->addAttr(::new (S.Context)
4726 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4727 Attr.getAttributeSpellingListIndex()));
4730 //===----------------------------------------------------------------------===//
4731 // Microsoft specific attribute handlers.
4732 //===----------------------------------------------------------------------===//
4734 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4735 unsigned AttrSpellingListIndex, StringRef Uuid) {
4736 if (const auto *UA = D->getAttr<UuidAttr>()) {
4737 if (UA->getGuid().equals_lower(Uuid))
4739 Diag(UA->getLocation(), diag::err_mismatched_uuid);
4740 Diag(Range.getBegin(), diag::note_previous_uuid);
4741 D->dropAttr<UuidAttr>();
4744 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
4747 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4748 if (!S.LangOpts.CPlusPlus) {
4749 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4750 << Attr.getName() << AttributeLangSupport::C;
4755 SourceLocation LiteralLoc;
4756 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4759 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4760 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4761 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4762 StrRef = StrRef.drop_front().drop_back();
4764 // Validate GUID length.
4765 if (StrRef.size() != 36) {
4766 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4770 for (unsigned i = 0; i < 36; ++i) {
4771 if (i == 8 || i == 13 || i == 18 || i == 23) {
4772 if (StrRef[i] != '-') {
4773 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4776 } else if (!isHexDigit(StrRef[i])) {
4777 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4782 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
4783 Attr.getAttributeSpellingListIndex(), StrRef);
4788 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4789 if (!S.LangOpts.CPlusPlus) {
4790 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4791 << Attr.getName() << AttributeLangSupport::C;
4794 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
4795 D, Attr.getRange(), /*BestCase=*/true,
4796 Attr.getAttributeSpellingListIndex(),
4797 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
4800 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
4804 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4805 const AttributeList &Attr) {
4806 VarDecl *VD = cast<VarDecl>(D);
4807 if (!S.Context.getTargetInfo().isTLSSupported()) {
4808 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4811 if (VD->getTSCSpec() != TSCS_unspecified) {
4812 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4815 if (VD->hasLocalStorage()) {
4816 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4819 VD->addAttr(::new (S.Context) ThreadAttr(
4820 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4823 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4824 SmallVector<StringRef, 4> Tags;
4825 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4827 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
4829 Tags.push_back(Tag);
4832 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
4833 if (!NS->isInline()) {
4834 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
4837 if (NS->isAnonymousNamespace()) {
4838 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
4841 if (Attr.getNumArgs() == 0)
4842 Tags.push_back(NS->getName());
4843 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4846 // Store tags sorted and without duplicates.
4847 std::sort(Tags.begin(), Tags.end());
4848 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
4850 D->addAttr(::new (S.Context)
4851 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
4852 Attr.getAttributeSpellingListIndex()));
4855 static void handleARMInterruptAttr(Sema &S, Decl *D,
4856 const AttributeList &Attr) {
4857 // Check the attribute arguments.
4858 if (Attr.getNumArgs() > 1) {
4859 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4860 << Attr.getName() << 1;
4865 SourceLocation ArgLoc;
4867 if (Attr.getNumArgs() == 0)
4869 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4872 ARMInterruptAttr::InterruptType Kind;
4873 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4874 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4875 << Attr.getName() << Str << ArgLoc;
4879 unsigned Index = Attr.getAttributeSpellingListIndex();
4880 D->addAttr(::new (S.Context)
4881 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4884 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4885 const AttributeList &Attr) {
4886 if (!checkAttributeNumArgs(S, Attr, 1))
4889 if (!Attr.isArgExpr(0)) {
4890 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4891 << AANT_ArgumentIntegerConstant;
4895 // FIXME: Check for decl - it should be void ()(void).
4897 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4898 llvm::APSInt NumParams(32);
4899 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4900 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4901 << Attr.getName() << AANT_ArgumentIntegerConstant
4902 << NumParamsExpr->getSourceRange();
4906 unsigned Num = NumParams.getLimitedValue(255);
4907 if ((Num & 1) || Num > 30) {
4908 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4909 << Attr.getName() << (int)NumParams.getSExtValue()
4910 << NumParamsExpr->getSourceRange();
4914 D->addAttr(::new (S.Context)
4915 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4916 Attr.getAttributeSpellingListIndex()));
4917 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4920 static void handleMipsInterruptAttr(Sema &S, Decl *D,
4921 const AttributeList &Attr) {
4922 // Only one optional argument permitted.
4923 if (Attr.getNumArgs() > 1) {
4924 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4925 << Attr.getName() << 1;
4930 SourceLocation ArgLoc;
4932 if (Attr.getNumArgs() == 0)
4934 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4937 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
4938 // a) Must be a function.
4939 // b) Must have no parameters.
4940 // c) Must have the 'void' return type.
4941 // d) Cannot have the 'mips16' attribute, as that instruction set
4942 // lacks the 'eret' instruction.
4943 // e) The attribute itself must either have no argument or one of the
4944 // valid interrupt types, see [MipsInterruptDocs].
4946 if (!isFunctionOrMethod(D)) {
4947 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
4948 << "'interrupt'" << ExpectedFunctionOrMethod;
4952 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
4953 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4958 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4959 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4964 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
4968 MipsInterruptAttr::InterruptType Kind;
4969 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4970 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4971 << Attr.getName() << "'" + std::string(Str) + "'";
4975 D->addAttr(::new (S.Context) MipsInterruptAttr(
4976 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
4979 static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
4980 const AttributeList &Attr) {
4981 // Semantic checks for a function with the 'interrupt' attribute.
4982 // a) Must be a function.
4983 // b) Must have the 'void' return type.
4984 // c) Must take 1 or 2 arguments.
4985 // d) The 1st argument must be a pointer.
4986 // e) The 2nd argument (if any) must be an unsigned integer.
4987 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
4988 CXXMethodDecl::isStaticOverloadedOperator(
4989 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
4990 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4991 << Attr.getName() << ExpectedFunctionWithProtoType;
4994 // Interrupt handler must have void return type.
4995 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4996 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
4997 diag::err_anyx86_interrupt_attribute)
4998 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5004 // Interrupt handler must have 1 or 2 parameters.
5005 unsigned NumParams = getFunctionOrMethodNumParams(D);
5006 if (NumParams < 1 || NumParams > 2) {
5007 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5008 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5014 // The first argument must be a pointer.
5015 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5016 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5017 diag::err_anyx86_interrupt_attribute)
5018 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5024 // The second argument, if present, must be an unsigned integer.
5026 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5029 if (NumParams == 2 &&
5030 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5031 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5032 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5033 diag::err_anyx86_interrupt_attribute)
5034 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5037 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5040 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5041 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5042 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5045 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5046 // Dispatch the interrupt attribute based on the current target.
5047 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5048 case llvm::Triple::msp430:
5049 handleMSP430InterruptAttr(S, D, Attr);
5051 case llvm::Triple::mipsel:
5052 case llvm::Triple::mips:
5053 handleMipsInterruptAttr(S, D, Attr);
5055 case llvm::Triple::x86:
5056 case llvm::Triple::x86_64:
5057 handleAnyX86InterruptAttr(S, D, Attr);
5060 handleARMInterruptAttr(S, D, Attr);
5065 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5066 const AttributeList &Attr) {
5068 Expr *MinExpr = Attr.getArgAsExpr(0);
5069 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5073 Expr *MaxExpr = Attr.getArgAsExpr(1);
5074 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5077 if (Min == 0 && Max != 0) {
5078 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5079 << Attr.getName() << 0;
5083 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5084 << Attr.getName() << 1;
5088 D->addAttr(::new (S.Context)
5089 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5090 Attr.getAttributeSpellingListIndex()));
5093 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5094 const AttributeList &Attr) {
5096 Expr *MinExpr = Attr.getArgAsExpr(0);
5097 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5101 if (Attr.getNumArgs() == 2) {
5102 Expr *MaxExpr = Attr.getArgAsExpr(1);
5103 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5107 if (Min == 0 && Max != 0) {
5108 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5109 << Attr.getName() << 0;
5112 if (Max != 0 && Min > Max) {
5113 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5114 << Attr.getName() << 1;
5118 D->addAttr(::new (S.Context)
5119 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5120 Attr.getAttributeSpellingListIndex()));
5123 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5124 const AttributeList &Attr) {
5125 uint32_t NumSGPR = 0;
5126 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5127 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
5130 D->addAttr(::new (S.Context)
5131 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5132 Attr.getAttributeSpellingListIndex()));
5135 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5136 const AttributeList &Attr) {
5137 uint32_t NumVGPR = 0;
5138 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5139 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5142 D->addAttr(::new (S.Context)
5143 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
5144 Attr.getAttributeSpellingListIndex()));
5147 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5148 const AttributeList& Attr) {
5149 // If we try to apply it to a function pointer, don't warn, but don't
5150 // do anything, either. It doesn't matter anyway, because there's nothing
5151 // special about calling a force_align_arg_pointer function.
5152 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5153 if (VD && VD->getType()->isFunctionPointerType())
5155 // Also don't warn on function pointer typedefs.
5156 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5157 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5158 TD->getUnderlyingType()->isFunctionType()))
5160 // Attribute can only be applied to function types.
5161 if (!isa<FunctionDecl>(D)) {
5162 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5163 << Attr.getName() << /* function */0;
5167 D->addAttr(::new (S.Context)
5168 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5169 Attr.getAttributeSpellingListIndex()));
5172 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5174 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5175 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5178 // TODO: Investigate what happens with the next major version of MSVC.
5179 if (Version != LangOptions::MSVC2015) {
5180 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5181 << Attr.getName() << Version << VersionExpr->getSourceRange();
5185 D->addAttr(::new (S.Context)
5186 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5187 Attr.getAttributeSpellingListIndex()));
5190 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5191 unsigned AttrSpellingListIndex) {
5192 if (D->hasAttr<DLLExportAttr>()) {
5193 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5197 if (D->hasAttr<DLLImportAttr>())
5200 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5203 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5204 unsigned AttrSpellingListIndex) {
5205 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5206 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5207 D->dropAttr<DLLImportAttr>();
5210 if (D->hasAttr<DLLExportAttr>())
5213 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5216 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5217 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5218 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5219 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5224 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5225 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5226 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5227 // MinGW doesn't allow dllimport on inline functions.
5228 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5234 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5235 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5236 MD->getParent()->isLambda()) {
5237 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5242 unsigned Index = A.getAttributeSpellingListIndex();
5243 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5244 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5245 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5247 D->addAttr(NewAttr);
5251 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5252 unsigned AttrSpellingListIndex,
5253 MSInheritanceAttr::Spelling SemanticSpelling) {
5254 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5255 if (IA->getSemanticSpelling() == SemanticSpelling)
5257 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5258 << 1 /*previous declaration*/;
5259 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5260 D->dropAttr<MSInheritanceAttr>();
5263 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5264 if (RD->hasDefinition()) {
5265 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5266 SemanticSpelling)) {
5270 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5271 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5272 << 1 /*partial specialization*/;
5275 if (RD->getDescribedClassTemplate()) {
5276 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5277 << 0 /*primary template*/;
5282 return ::new (Context)
5283 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5286 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5287 // The capability attributes take a single string parameter for the name of
5288 // the capability they represent. The lockable attribute does not take any
5289 // parameters. However, semantically, both attributes represent the same
5290 // concept, and so they use the same semantic attribute. Eventually, the
5291 // lockable attribute will be removed.
5293 // For backward compatibility, any capability which has no specified string
5294 // literal will be considered a "mutex."
5295 StringRef N("mutex");
5296 SourceLocation LiteralLoc;
5297 if (Attr.getKind() == AttributeList::AT_Capability &&
5298 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5301 // Currently, there are only two names allowed for a capability: role and
5302 // mutex (case insensitive). Diagnose other capability names.
5303 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5304 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5306 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5307 Attr.getAttributeSpellingListIndex()));
5310 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5311 const AttributeList &Attr) {
5312 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5313 Attr.getArgAsExpr(0),
5314 Attr.getAttributeSpellingListIndex()));
5317 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5318 const AttributeList &Attr) {
5319 SmallVector<Expr*, 1> Args;
5320 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5323 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5325 Args.data(), Args.size(),
5326 Attr.getAttributeSpellingListIndex()));
5329 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5330 const AttributeList &Attr) {
5331 SmallVector<Expr*, 2> Args;
5332 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5335 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5337 Attr.getArgAsExpr(0),
5340 Attr.getAttributeSpellingListIndex()));
5343 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5344 const AttributeList &Attr) {
5345 // Check that all arguments are lockable objects.
5346 SmallVector<Expr *, 1> Args;
5347 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5349 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5350 Attr.getRange(), S.Context, Args.data(), Args.size(),
5351 Attr.getAttributeSpellingListIndex()));
5354 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5355 const AttributeList &Attr) {
5356 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5359 // check that all arguments are lockable objects
5360 SmallVector<Expr*, 1> Args;
5361 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5365 RequiresCapabilityAttr *RCA = ::new (S.Context)
5366 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5367 Args.size(), Attr.getAttributeSpellingListIndex());
5372 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5373 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5374 if (NSD->isAnonymousNamespace()) {
5375 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5376 // Do not want to attach the attribute to the namespace because that will
5377 // cause confusing diagnostic reports for uses of declarations within the
5383 // Handle the cases where the attribute has a text message.
5384 StringRef Str, Replacement;
5385 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5386 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5389 // Only support a single optional message for Declspec and CXX11.
5390 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5391 checkAttributeAtMostNumArgs(S, Attr, 1);
5392 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5393 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5396 if (!S.getLangOpts().CPlusPlus14)
5397 if (Attr.isCXX11Attribute() &&
5398 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5399 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5401 D->addAttr(::new (S.Context)
5402 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5403 Attr.getAttributeSpellingListIndex()));
5406 static bool isGlobalVar(const Decl *D) {
5407 if (const auto *S = dyn_cast<VarDecl>(D))
5408 return S->hasGlobalStorage();
5412 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5413 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5416 std::vector<StringRef> Sanitizers;
5418 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5419 StringRef SanitizerName;
5420 SourceLocation LiteralLoc;
5422 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5425 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5426 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5427 else if (isGlobalVar(D) && SanitizerName != "address")
5428 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5429 << Attr.getName() << ExpectedFunctionOrMethod;
5430 Sanitizers.push_back(SanitizerName);
5433 D->addAttr(::new (S.Context) NoSanitizeAttr(
5434 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5435 Attr.getAttributeSpellingListIndex()));
5438 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5439 const AttributeList &Attr) {
5440 StringRef AttrName = Attr.getName()->getName();
5441 normalizeName(AttrName);
5442 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5443 .Case("no_address_safety_analysis", "address")
5444 .Case("no_sanitize_address", "address")
5445 .Case("no_sanitize_thread", "thread")
5446 .Case("no_sanitize_memory", "memory");
5447 if (isGlobalVar(D) && SanitizerName != "address")
5448 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5449 << Attr.getName() << ExpectedFunction;
5450 D->addAttr(::new (S.Context)
5451 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5452 Attr.getAttributeSpellingListIndex()));
5455 static void handleInternalLinkageAttr(Sema &S, Decl *D,
5456 const AttributeList &Attr) {
5457 if (InternalLinkageAttr *Internal =
5458 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5459 Attr.getAttributeSpellingListIndex()))
5460 D->addAttr(Internal);
5463 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5464 if (S.LangOpts.OpenCLVersion != 200)
5465 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5466 << Attr.getName() << "2.0" << 0;
5468 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5469 << Attr.getName() << "2.0";
5472 /// Handles semantic checking for features that are common to all attributes,
5473 /// such as checking whether a parameter was properly specified, or the correct
5474 /// number of arguments were passed, etc.
5475 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5476 const AttributeList &Attr) {
5477 // Several attributes carry different semantics than the parsing requires, so
5478 // those are opted out of the common handling.
5480 // We also bail on unknown and ignored attributes because those are handled
5481 // as part of the target-specific handling logic.
5482 if (Attr.hasCustomParsing() ||
5483 Attr.getKind() == AttributeList::UnknownAttribute)
5486 // Check whether the attribute requires specific language extensions to be
5488 if (!Attr.diagnoseLangOpts(S))
5491 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5492 // If there are no optional arguments, then checking for the argument count
5494 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5497 // There are optional arguments, so checking is slightly more involved.
5498 if (Attr.getMinArgs() &&
5499 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5501 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5502 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5506 // Check whether the attribute appertains to the given subject.
5507 if (!Attr.diagnoseAppertainsTo(S, D))
5513 static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5514 const AttributeList &Attr) {
5515 if (D->isInvalidDecl())
5518 // Check if there is only one access qualifier.
5519 if (D->hasAttr<OpenCLAccessAttr>()) {
5520 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5521 << D->getSourceRange();
5522 D->setInvalidDecl(true);
5526 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5527 // image object can be read and written.
5528 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5529 // object. Using the read_write (or __read_write) qualifier with the pipe
5530 // qualifier is a compilation error.
5531 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5532 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5533 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5534 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5535 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5536 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5537 D->setInvalidDecl(true);
5543 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5544 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5547 //===----------------------------------------------------------------------===//
5548 // Top Level Sema Entry Points
5549 //===----------------------------------------------------------------------===//
5551 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5552 /// the attribute applies to decls. If the attribute is a type attribute, just
5553 /// silently ignore it if a GNU attribute.
5554 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5555 const AttributeList &Attr,
5556 bool IncludeCXX11Attributes) {
5557 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5560 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5562 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5565 // Unknown attributes are automatically warned on. Target-specific attributes
5566 // which do not apply to the current target architecture are treated as
5567 // though they were unknown attributes.
5568 if (Attr.getKind() == AttributeList::UnknownAttribute ||
5569 !Attr.existsInTarget(S.Context.getTargetInfo())) {
5570 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5571 ? diag::warn_unhandled_ms_attribute_ignored
5572 : diag::warn_unknown_attribute_ignored)
5577 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5580 switch (Attr.getKind()) {
5582 if (!Attr.isStmtAttr()) {
5583 // Type attributes are handled elsewhere; silently move on.
5584 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5587 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5588 << Attr.getName() << D->getLocation();
5590 case AttributeList::AT_Interrupt:
5591 handleInterruptAttr(S, D, Attr);
5593 case AttributeList::AT_X86ForceAlignArgPointer:
5594 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5596 case AttributeList::AT_DLLExport:
5597 case AttributeList::AT_DLLImport:
5598 handleDLLAttr(S, D, Attr);
5600 case AttributeList::AT_Mips16:
5601 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5604 case AttributeList::AT_NoMips16:
5605 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5607 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5608 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5610 case AttributeList::AT_AMDGPUWavesPerEU:
5611 handleAMDGPUWavesPerEUAttr(S, D, Attr);
5613 case AttributeList::AT_AMDGPUNumSGPR:
5614 handleAMDGPUNumSGPRAttr(S, D, Attr);
5616 case AttributeList::AT_AMDGPUNumVGPR:
5617 handleAMDGPUNumVGPRAttr(S, D, Attr);
5619 case AttributeList::AT_IBAction:
5620 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5622 case AttributeList::AT_IBOutlet:
5623 handleIBOutlet(S, D, Attr);
5625 case AttributeList::AT_IBOutletCollection:
5626 handleIBOutletCollection(S, D, Attr);
5628 case AttributeList::AT_IFunc:
5629 handleIFuncAttr(S, D, Attr);
5631 case AttributeList::AT_Alias:
5632 handleAliasAttr(S, D, Attr);
5634 case AttributeList::AT_Aligned:
5635 handleAlignedAttr(S, D, Attr);
5637 case AttributeList::AT_AlignValue:
5638 handleAlignValueAttr(S, D, Attr);
5640 case AttributeList::AT_AllocSize:
5641 handleAllocSizeAttr(S, D, Attr);
5643 case AttributeList::AT_AlwaysInline:
5644 handleAlwaysInlineAttr(S, D, Attr);
5646 case AttributeList::AT_AnalyzerNoReturn:
5647 handleAnalyzerNoReturnAttr(S, D, Attr);
5649 case AttributeList::AT_TLSModel:
5650 handleTLSModelAttr(S, D, Attr);
5652 case AttributeList::AT_Annotate:
5653 handleAnnotateAttr(S, D, Attr);
5655 case AttributeList::AT_Availability:
5656 handleAvailabilityAttr(S, D, Attr);
5658 case AttributeList::AT_CarriesDependency:
5659 handleDependencyAttr(S, scope, D, Attr);
5661 case AttributeList::AT_Common:
5662 handleCommonAttr(S, D, Attr);
5664 case AttributeList::AT_CUDAConstant:
5665 handleConstantAttr(S, D, Attr);
5667 case AttributeList::AT_PassObjectSize:
5668 handlePassObjectSizeAttr(S, D, Attr);
5670 case AttributeList::AT_Constructor:
5671 handleConstructorAttr(S, D, Attr);
5673 case AttributeList::AT_CXX11NoReturn:
5674 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5676 case AttributeList::AT_Deprecated:
5677 handleDeprecatedAttr(S, D, Attr);
5679 case AttributeList::AT_Destructor:
5680 handleDestructorAttr(S, D, Attr);
5682 case AttributeList::AT_EnableIf:
5683 handleEnableIfAttr(S, D, Attr);
5685 case AttributeList::AT_ExtVectorType:
5686 handleExtVectorTypeAttr(S, scope, D, Attr);
5688 case AttributeList::AT_MinSize:
5689 handleMinSizeAttr(S, D, Attr);
5691 case AttributeList::AT_OptimizeNone:
5692 handleOptimizeNoneAttr(S, D, Attr);
5694 case AttributeList::AT_FlagEnum:
5695 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5697 case AttributeList::AT_Flatten:
5698 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5700 case AttributeList::AT_Format:
5701 handleFormatAttr(S, D, Attr);
5703 case AttributeList::AT_FormatArg:
5704 handleFormatArgAttr(S, D, Attr);
5706 case AttributeList::AT_CUDAGlobal:
5707 handleGlobalAttr(S, D, Attr);
5709 case AttributeList::AT_CUDADevice:
5710 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
5713 case AttributeList::AT_CUDAHost:
5714 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
5717 case AttributeList::AT_GNUInline:
5718 handleGNUInlineAttr(S, D, Attr);
5720 case AttributeList::AT_CUDALaunchBounds:
5721 handleLaunchBoundsAttr(S, D, Attr);
5723 case AttributeList::AT_Restrict:
5724 handleRestrictAttr(S, D, Attr);
5726 case AttributeList::AT_MayAlias:
5727 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5729 case AttributeList::AT_Mode:
5730 handleModeAttr(S, D, Attr);
5732 case AttributeList::AT_NoAlias:
5733 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5735 case AttributeList::AT_NoCommon:
5736 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5738 case AttributeList::AT_NoSplitStack:
5739 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5741 case AttributeList::AT_NonNull:
5742 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5743 handleNonNullAttrParameter(S, PVD, Attr);
5745 handleNonNullAttr(S, D, Attr);
5747 case AttributeList::AT_ReturnsNonNull:
5748 handleReturnsNonNullAttr(S, D, Attr);
5750 case AttributeList::AT_AssumeAligned:
5751 handleAssumeAlignedAttr(S, D, Attr);
5753 case AttributeList::AT_Overloadable:
5754 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5756 case AttributeList::AT_Ownership:
5757 handleOwnershipAttr(S, D, Attr);
5759 case AttributeList::AT_Cold:
5760 handleColdAttr(S, D, Attr);
5762 case AttributeList::AT_Hot:
5763 handleHotAttr(S, D, Attr);
5765 case AttributeList::AT_Naked:
5766 handleNakedAttr(S, D, Attr);
5768 case AttributeList::AT_NoReturn:
5769 handleNoReturnAttr(S, D, Attr);
5771 case AttributeList::AT_NoThrow:
5772 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5774 case AttributeList::AT_CUDAShared:
5775 handleSharedAttr(S, D, Attr);
5777 case AttributeList::AT_VecReturn:
5778 handleVecReturnAttr(S, D, Attr);
5780 case AttributeList::AT_ObjCOwnership:
5781 handleObjCOwnershipAttr(S, D, Attr);
5783 case AttributeList::AT_ObjCPreciseLifetime:
5784 handleObjCPreciseLifetimeAttr(S, D, Attr);
5786 case AttributeList::AT_ObjCReturnsInnerPointer:
5787 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5789 case AttributeList::AT_ObjCRequiresSuper:
5790 handleObjCRequiresSuperAttr(S, D, Attr);
5792 case AttributeList::AT_ObjCBridge:
5793 handleObjCBridgeAttr(S, scope, D, Attr);
5795 case AttributeList::AT_ObjCBridgeMutable:
5796 handleObjCBridgeMutableAttr(S, scope, D, Attr);
5798 case AttributeList::AT_ObjCBridgeRelated:
5799 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
5801 case AttributeList::AT_ObjCDesignatedInitializer:
5802 handleObjCDesignatedInitializer(S, D, Attr);
5804 case AttributeList::AT_ObjCRuntimeName:
5805 handleObjCRuntimeName(S, D, Attr);
5807 case AttributeList::AT_ObjCRuntimeVisible:
5808 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
5810 case AttributeList::AT_ObjCBoxable:
5811 handleObjCBoxable(S, D, Attr);
5813 case AttributeList::AT_CFAuditedTransfer:
5814 handleCFAuditedTransferAttr(S, D, Attr);
5816 case AttributeList::AT_CFUnknownTransfer:
5817 handleCFUnknownTransferAttr(S, D, Attr);
5819 case AttributeList::AT_CFConsumed:
5820 case AttributeList::AT_NSConsumed:
5821 handleNSConsumedAttr(S, D, Attr);
5823 case AttributeList::AT_NSConsumesSelf:
5824 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
5826 case AttributeList::AT_NSReturnsAutoreleased:
5827 case AttributeList::AT_NSReturnsNotRetained:
5828 case AttributeList::AT_CFReturnsNotRetained:
5829 case AttributeList::AT_NSReturnsRetained:
5830 case AttributeList::AT_CFReturnsRetained:
5831 handleNSReturnsRetainedAttr(S, D, Attr);
5833 case AttributeList::AT_WorkGroupSizeHint:
5834 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
5836 case AttributeList::AT_ReqdWorkGroupSize:
5837 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
5839 case AttributeList::AT_VecTypeHint:
5840 handleVecTypeHint(S, D, Attr);
5842 case AttributeList::AT_RequireConstantInit:
5843 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
5845 case AttributeList::AT_InitPriority:
5846 handleInitPriorityAttr(S, D, Attr);
5848 case AttributeList::AT_Packed:
5849 handlePackedAttr(S, D, Attr);
5851 case AttributeList::AT_Section:
5852 handleSectionAttr(S, D, Attr);
5854 case AttributeList::AT_Target:
5855 handleTargetAttr(S, D, Attr);
5857 case AttributeList::AT_Unavailable:
5858 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
5860 case AttributeList::AT_ArcWeakrefUnavailable:
5861 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
5863 case AttributeList::AT_ObjCRootClass:
5864 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
5866 case AttributeList::AT_ObjCSubclassingRestricted:
5867 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
5869 case AttributeList::AT_ObjCExplicitProtocolImpl:
5870 handleObjCSuppresProtocolAttr(S, D, Attr);
5872 case AttributeList::AT_ObjCRequiresPropertyDefs:
5873 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
5875 case AttributeList::AT_Unused:
5876 handleUnusedAttr(S, D, Attr);
5878 case AttributeList::AT_ReturnsTwice:
5879 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
5881 case AttributeList::AT_NotTailCalled:
5882 handleNotTailCalledAttr(S, D, Attr);
5884 case AttributeList::AT_DisableTailCalls:
5885 handleDisableTailCallsAttr(S, D, Attr);
5887 case AttributeList::AT_Used:
5888 handleUsedAttr(S, D, Attr);
5890 case AttributeList::AT_Visibility:
5891 handleVisibilityAttr(S, D, Attr, false);
5893 case AttributeList::AT_TypeVisibility:
5894 handleVisibilityAttr(S, D, Attr, true);
5896 case AttributeList::AT_WarnUnused:
5897 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
5899 case AttributeList::AT_WarnUnusedResult:
5900 handleWarnUnusedResult(S, D, Attr);
5902 case AttributeList::AT_Weak:
5903 handleSimpleAttribute<WeakAttr>(S, D, Attr);
5905 case AttributeList::AT_WeakRef:
5906 handleWeakRefAttr(S, D, Attr);
5908 case AttributeList::AT_WeakImport:
5909 handleWeakImportAttr(S, D, Attr);
5911 case AttributeList::AT_TransparentUnion:
5912 handleTransparentUnionAttr(S, D, Attr);
5914 case AttributeList::AT_ObjCException:
5915 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
5917 case AttributeList::AT_ObjCMethodFamily:
5918 handleObjCMethodFamilyAttr(S, D, Attr);
5920 case AttributeList::AT_ObjCNSObject:
5921 handleObjCNSObject(S, D, Attr);
5923 case AttributeList::AT_ObjCIndependentClass:
5924 handleObjCIndependentClass(S, D, Attr);
5926 case AttributeList::AT_Blocks:
5927 handleBlocksAttr(S, D, Attr);
5929 case AttributeList::AT_Sentinel:
5930 handleSentinelAttr(S, D, Attr);
5932 case AttributeList::AT_Const:
5933 handleSimpleAttribute<ConstAttr>(S, D, Attr);
5935 case AttributeList::AT_Pure:
5936 handleSimpleAttribute<PureAttr>(S, D, Attr);
5938 case AttributeList::AT_Cleanup:
5939 handleCleanupAttr(S, D, Attr);
5941 case AttributeList::AT_NoDebug:
5942 handleNoDebugAttr(S, D, Attr);
5944 case AttributeList::AT_NoDuplicate:
5945 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
5947 case AttributeList::AT_Convergent:
5948 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
5950 case AttributeList::AT_NoInline:
5951 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
5953 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
5954 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
5956 case AttributeList::AT_StdCall:
5957 case AttributeList::AT_CDecl:
5958 case AttributeList::AT_FastCall:
5959 case AttributeList::AT_ThisCall:
5960 case AttributeList::AT_Pascal:
5961 case AttributeList::AT_RegCall:
5962 case AttributeList::AT_SwiftCall:
5963 case AttributeList::AT_VectorCall:
5964 case AttributeList::AT_MSABI:
5965 case AttributeList::AT_SysVABI:
5966 case AttributeList::AT_Pcs:
5967 case AttributeList::AT_IntelOclBicc:
5968 case AttributeList::AT_PreserveMost:
5969 case AttributeList::AT_PreserveAll:
5970 handleCallConvAttr(S, D, Attr);
5972 case AttributeList::AT_OpenCLKernel:
5973 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
5975 case AttributeList::AT_OpenCLAccess:
5976 handleOpenCLAccessAttr(S, D, Attr);
5978 case AttributeList::AT_OpenCLNoSVM:
5979 handleOpenCLNoSVMAttr(S, D, Attr);
5981 case AttributeList::AT_SwiftContext:
5982 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
5984 case AttributeList::AT_SwiftErrorResult:
5985 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
5987 case AttributeList::AT_SwiftIndirectResult:
5988 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
5990 case AttributeList::AT_InternalLinkage:
5991 handleInternalLinkageAttr(S, D, Attr);
5993 case AttributeList::AT_LTOVisibilityPublic:
5994 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
5997 // Microsoft attributes:
5998 case AttributeList::AT_EmptyBases:
5999 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6001 case AttributeList::AT_LayoutVersion:
6002 handleLayoutVersion(S, D, Attr);
6004 case AttributeList::AT_MSNoVTable:
6005 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
6007 case AttributeList::AT_MSStruct:
6008 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
6010 case AttributeList::AT_Uuid:
6011 handleUuidAttr(S, D, Attr);
6013 case AttributeList::AT_MSInheritance:
6014 handleMSInheritanceAttr(S, D, Attr);
6016 case AttributeList::AT_SelectAny:
6017 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6019 case AttributeList::AT_Thread:
6020 handleDeclspecThreadAttr(S, D, Attr);
6023 case AttributeList::AT_AbiTag:
6024 handleAbiTagAttr(S, D, Attr);
6027 // Thread safety attributes:
6028 case AttributeList::AT_AssertExclusiveLock:
6029 handleAssertExclusiveLockAttr(S, D, Attr);
6031 case AttributeList::AT_AssertSharedLock:
6032 handleAssertSharedLockAttr(S, D, Attr);
6034 case AttributeList::AT_GuardedVar:
6035 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6037 case AttributeList::AT_PtGuardedVar:
6038 handlePtGuardedVarAttr(S, D, Attr);
6040 case AttributeList::AT_ScopedLockable:
6041 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6043 case AttributeList::AT_NoSanitize:
6044 handleNoSanitizeAttr(S, D, Attr);
6046 case AttributeList::AT_NoSanitizeSpecific:
6047 handleNoSanitizeSpecificAttr(S, D, Attr);
6049 case AttributeList::AT_NoThreadSafetyAnalysis:
6050 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
6052 case AttributeList::AT_GuardedBy:
6053 handleGuardedByAttr(S, D, Attr);
6055 case AttributeList::AT_PtGuardedBy:
6056 handlePtGuardedByAttr(S, D, Attr);
6058 case AttributeList::AT_ExclusiveTrylockFunction:
6059 handleExclusiveTrylockFunctionAttr(S, D, Attr);
6061 case AttributeList::AT_LockReturned:
6062 handleLockReturnedAttr(S, D, Attr);
6064 case AttributeList::AT_LocksExcluded:
6065 handleLocksExcludedAttr(S, D, Attr);
6067 case AttributeList::AT_SharedTrylockFunction:
6068 handleSharedTrylockFunctionAttr(S, D, Attr);
6070 case AttributeList::AT_AcquiredBefore:
6071 handleAcquiredBeforeAttr(S, D, Attr);
6073 case AttributeList::AT_AcquiredAfter:
6074 handleAcquiredAfterAttr(S, D, Attr);
6077 // Capability analysis attributes.
6078 case AttributeList::AT_Capability:
6079 case AttributeList::AT_Lockable:
6080 handleCapabilityAttr(S, D, Attr);
6082 case AttributeList::AT_RequiresCapability:
6083 handleRequiresCapabilityAttr(S, D, Attr);
6086 case AttributeList::AT_AssertCapability:
6087 handleAssertCapabilityAttr(S, D, Attr);
6089 case AttributeList::AT_AcquireCapability:
6090 handleAcquireCapabilityAttr(S, D, Attr);
6092 case AttributeList::AT_ReleaseCapability:
6093 handleReleaseCapabilityAttr(S, D, Attr);
6095 case AttributeList::AT_TryAcquireCapability:
6096 handleTryAcquireCapabilityAttr(S, D, Attr);
6099 // Consumed analysis attributes.
6100 case AttributeList::AT_Consumable:
6101 handleConsumableAttr(S, D, Attr);
6103 case AttributeList::AT_ConsumableAutoCast:
6104 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6106 case AttributeList::AT_ConsumableSetOnRead:
6107 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6109 case AttributeList::AT_CallableWhen:
6110 handleCallableWhenAttr(S, D, Attr);
6112 case AttributeList::AT_ParamTypestate:
6113 handleParamTypestateAttr(S, D, Attr);
6115 case AttributeList::AT_ReturnTypestate:
6116 handleReturnTypestateAttr(S, D, Attr);
6118 case AttributeList::AT_SetTypestate:
6119 handleSetTypestateAttr(S, D, Attr);
6121 case AttributeList::AT_TestTypestate:
6122 handleTestTypestateAttr(S, D, Attr);
6125 // Type safety attributes.
6126 case AttributeList::AT_ArgumentWithTypeTag:
6127 handleArgumentWithTypeTagAttr(S, D, Attr);
6129 case AttributeList::AT_TypeTagForDatatype:
6130 handleTypeTagForDatatypeAttr(S, D, Attr);
6132 case AttributeList::AT_RenderScriptKernel:
6133 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
6136 case AttributeList::AT_XRayInstrument:
6137 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6142 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6143 /// attribute list to the specified decl, ignoring any type attributes.
6144 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
6145 const AttributeList *AttrList,
6146 bool IncludeCXX11Attributes) {
6147 for (const AttributeList* l = AttrList; l; l = l->getNext())
6148 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
6150 // FIXME: We should be able to handle these cases in TableGen.
6152 // static int a9 __attribute__((weakref));
6153 // but that looks really pointless. We reject it.
6154 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
6155 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6156 << cast<NamedDecl>(D);
6157 D->dropAttr<WeakRefAttr>();
6161 // FIXME: We should be able to handle this in TableGen as well. It would be
6162 // good to have a way to specify "these attributes must appear as a group",
6163 // for these. Additionally, it would be good to have a way to specify "these
6164 // attribute must never appear as a group" for attributes like cold and hot.
6165 if (!D->hasAttr<OpenCLKernelAttr>()) {
6166 // These attributes cannot be applied to a non-kernel function.
6167 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
6168 // FIXME: This emits a different error message than
6169 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
6170 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6171 D->setInvalidDecl();
6172 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
6173 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6174 D->setInvalidDecl();
6175 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
6176 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6177 D->setInvalidDecl();
6178 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6179 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6180 << A << ExpectedKernelFunction;
6181 D->setInvalidDecl();
6182 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
6183 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6184 << A << ExpectedKernelFunction;
6185 D->setInvalidDecl();
6186 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6187 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6188 << A << ExpectedKernelFunction;
6189 D->setInvalidDecl();
6190 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6191 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6192 << A << ExpectedKernelFunction;
6193 D->setInvalidDecl();
6198 // Annotation attributes are the only attributes allowed after an access
6200 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6201 const AttributeList *AttrList) {
6202 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6203 if (l->getKind() == AttributeList::AT_Annotate) {
6204 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
6206 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6214 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
6215 /// contains any decl attributes that we should warn about.
6216 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6217 for ( ; A; A = A->getNext()) {
6218 // Only warn if the attribute is an unignored, non-type attribute.
6219 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
6220 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6222 if (A->getKind() == AttributeList::UnknownAttribute) {
6223 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6224 << A->getName() << A->getRange();
6226 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6227 << A->getName() << A->getRange();
6232 /// checkUnusedDeclAttributes - Given a declarator which is not being
6233 /// used to build a declaration, complain about any decl attributes
6234 /// which might be lying around on it.
6235 void Sema::checkUnusedDeclAttributes(Declarator &D) {
6236 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6237 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6238 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6239 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6242 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
6243 /// \#pragma weak needs a non-definition decl and source may not have one.
6244 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6245 SourceLocation Loc) {
6246 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
6247 NamedDecl *NewD = nullptr;
6248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6249 FunctionDecl *NewFD;
6250 // FIXME: Missing call to CheckFunctionDeclaration().
6252 // FIXME: Is the qualifier info correct?
6253 // FIXME: Is the DeclContext correct?
6254 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6255 Loc, Loc, DeclarationName(II),
6256 FD->getType(), FD->getTypeSourceInfo(),
6257 SC_None, false/*isInlineSpecified*/,
6259 false/*isConstexprSpecified*/);
6262 if (FD->getQualifier())
6263 NewFD->setQualifierInfo(FD->getQualifierLoc());
6265 // Fake up parameter variables; they are declared as if this were
6267 QualType FDTy = FD->getType();
6268 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6269 SmallVector<ParmVarDecl*, 16> Params;
6270 for (const auto &AI : FT->param_types()) {
6271 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6272 Param->setScopeInfo(0, Params.size());
6273 Params.push_back(Param);
6275 NewFD->setParams(Params);
6277 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6278 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6279 VD->getInnerLocStart(), VD->getLocation(), II,
6280 VD->getType(), VD->getTypeSourceInfo(),
6281 VD->getStorageClass());
6282 if (VD->getQualifier()) {
6283 VarDecl *NewVD = cast<VarDecl>(NewD);
6284 NewVD->setQualifierInfo(VD->getQualifierLoc());
6290 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6291 /// applied to it, possibly with an alias.
6292 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6293 if (W.getUsed()) return; // only do this once
6295 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6296 IdentifierInfo *NDId = ND->getIdentifier();
6297 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6298 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6300 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6301 WeakTopLevelDecl.push_back(NewD);
6302 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6303 // to insert Decl at TU scope, sorry.
6304 DeclContext *SavedContext = CurContext;
6305 CurContext = Context.getTranslationUnitDecl();
6306 NewD->setDeclContext(CurContext);
6307 NewD->setLexicalDeclContext(CurContext);
6308 PushOnScopeChains(NewD, S);
6309 CurContext = SavedContext;
6310 } else { // just add weak to existing
6311 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6315 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6316 // It's valid to "forward-declare" #pragma weak, in which case we
6318 LoadExternalWeakUndeclaredIdentifiers();
6319 if (!WeakUndeclaredIdentifiers.empty()) {
6320 NamedDecl *ND = nullptr;
6321 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6322 if (VD->isExternC())
6324 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6325 if (FD->isExternC())
6328 if (IdentifierInfo *Id = ND->getIdentifier()) {
6329 auto I = WeakUndeclaredIdentifiers.find(Id);
6330 if (I != WeakUndeclaredIdentifiers.end()) {
6331 WeakInfo W = I->second;
6332 DeclApplyPragmaWeak(S, ND, W);
6333 WeakUndeclaredIdentifiers[Id] = W;
6340 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6341 /// it, apply them to D. This is a bit tricky because PD can have attributes
6342 /// specified in many different places, and we need to find and apply them all.
6343 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6344 // Apply decl attributes from the DeclSpec if present.
6345 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6346 ProcessDeclAttributeList(S, D, Attrs);
6348 // Walk the declarator structure, applying decl attributes that were in a type
6349 // position to the decl itself. This handles cases like:
6350 // int *__attr__(x)** D;
6351 // when X is a decl attribute.
6352 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6353 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6354 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6356 // Finally, apply any attributes on the decl itself.
6357 if (const AttributeList *Attrs = PD.getAttributes())
6358 ProcessDeclAttributeList(S, D, Attrs);
6361 /// Is the given declaration allowed to use a forbidden type?
6362 /// If so, it'll still be annotated with an attribute that makes it
6363 /// illegal to actually use.
6364 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6365 const DelayedDiagnostic &diag,
6366 UnavailableAttr::ImplicitReason &reason) {
6367 // Private ivars are always okay. Unfortunately, people don't
6368 // always properly make their ivars private, even in system headers.
6369 // Plus we need to make fields okay, too.
6370 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6371 !isa<FunctionDecl>(decl))
6374 // Silently accept unsupported uses of __weak in both user and system
6375 // declarations when it's been disabled, for ease of integration with
6376 // -fno-objc-arc files. We do have to take some care against attempts
6377 // to define such things; for now, we've only done that for ivars
6379 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6380 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6381 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6382 reason = UnavailableAttr::IR_ForbiddenWeak;
6387 // Allow all sorts of things in system headers.
6388 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6389 // Currently, all the failures dealt with this way are due to ARC
6391 reason = UnavailableAttr::IR_ARCForbiddenType;
6398 /// Handle a delayed forbidden-type diagnostic.
6399 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6401 auto reason = UnavailableAttr::IR_None;
6402 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6403 assert(reason && "didn't set reason?");
6404 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6408 if (S.getLangOpts().ObjCAutoRefCount)
6409 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6410 // FIXME: we may want to suppress diagnostics for all
6411 // kind of forbidden type messages on unavailable functions.
6412 if (FD->hasAttr<UnavailableAttr>() &&
6413 diag.getForbiddenTypeDiagnostic() ==
6414 diag::err_arc_array_param_no_ownership) {
6415 diag.Triggered = true;
6420 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6421 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6422 diag.Triggered = true;
6425 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6427 // Check each AvailabilityAttr to find the one for this platform.
6428 for (const auto *A : D->attrs()) {
6429 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6430 // FIXME: this is copied from CheckAvailability. We should try to
6433 // Check if this is an App Extension "platform", and if so chop off
6434 // the suffix for matching with the actual platform.
6435 StringRef ActualPlatform = Avail->getPlatform()->getName();
6436 StringRef RealizedPlatform = ActualPlatform;
6437 if (Context.getLangOpts().AppExt) {
6438 size_t suffix = RealizedPlatform.rfind("_app_extension");
6439 if (suffix != StringRef::npos)
6440 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6443 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6445 // Match the platform name.
6446 if (RealizedPlatform == TargetPlatform)
6453 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6454 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6455 /// in a deprecated context, but not the other way around.
6456 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6457 VersionTuple DeclVersion,
6459 assert(K != AR_Available && "Expected an unavailable declaration here!");
6461 // Checks if we should emit the availability diagnostic in the context of C.
6462 auto CheckContext = [&](const Decl *C) {
6463 if (K == AR_NotYetIntroduced) {
6464 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6465 if (AA->getIntroduced() >= DeclVersion)
6467 } else if (K == AR_Deprecated)
6468 if (C->isDeprecated())
6471 if (C->isUnavailable())
6476 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6477 // on nested declarations in an @interface having the availability of the
6478 // interface when they really shouldn't: they are members of the enclosing
6479 // context, and can referenced from there.
6480 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6481 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6482 if (CheckContext(OrigCtx))
6485 // An implementation implicitly has the availability of the interface.
6486 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6487 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6488 if (CheckContext(Interface))
6491 // A category implicitly has the availability of the interface.
6492 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6493 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6494 if (CheckContext(Interface))
6499 if (CheckContext(Ctx))
6502 // An implementation implicitly has the availability of the interface.
6503 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6504 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6505 if (CheckContext(Interface))
6508 // A category implicitly has the availability of the interface.
6509 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6510 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6511 if (CheckContext(Interface))
6513 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6518 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
6519 Decl *Ctx, const NamedDecl *D,
6520 StringRef Message, SourceLocation Loc,
6521 const ObjCInterfaceDecl *UnknownObjCClass,
6522 const ObjCPropertyDecl *ObjCProperty,
6523 bool ObjCPropertyAccess) {
6524 // Diagnostics for deprecated or unavailable.
6525 unsigned diag, diag_message, diag_fwdclass_message;
6526 unsigned diag_available_here = diag::note_availability_specified_here;
6528 // Matches 'diag::note_property_attribute' options.
6529 unsigned property_note_select;
6531 // Matches diag::note_availability_specified_here.
6532 unsigned available_here_select_kind;
6534 VersionTuple DeclVersion;
6535 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6536 DeclVersion = AA->getIntroduced();
6538 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6543 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6544 : diag::warn_property_method_deprecated;
6545 diag_message = diag::warn_deprecated_message;
6546 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6547 property_note_select = /* deprecated */ 0;
6548 available_here_select_kind = /* deprecated */ 2;
6551 case AR_Unavailable:
6552 diag = !ObjCPropertyAccess ? diag::err_unavailable
6553 : diag::err_property_method_unavailable;
6554 diag_message = diag::err_unavailable_message;
6555 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6556 property_note_select = /* unavailable */ 1;
6557 available_here_select_kind = /* unavailable */ 0;
6559 if (auto attr = D->getAttr<UnavailableAttr>()) {
6560 if (attr->isImplicit() && attr->getImplicitReason()) {
6561 // Most of these failures are due to extra restrictions in ARC;
6562 // reflect that in the primary diagnostic when applicable.
6563 auto flagARCError = [&] {
6564 if (S.getLangOpts().ObjCAutoRefCount &&
6565 S.getSourceManager().isInSystemHeader(D->getLocation()))
6566 diag = diag::err_unavailable_in_arc;
6569 switch (attr->getImplicitReason()) {
6570 case UnavailableAttr::IR_None: break;
6572 case UnavailableAttr::IR_ARCForbiddenType:
6574 diag_available_here = diag::note_arc_forbidden_type;
6577 case UnavailableAttr::IR_ForbiddenWeak:
6578 if (S.getLangOpts().ObjCWeakRuntime)
6579 diag_available_here = diag::note_arc_weak_disabled;
6581 diag_available_here = diag::note_arc_weak_no_runtime;
6584 case UnavailableAttr::IR_ARCForbiddenConversion:
6586 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6589 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6591 diag_available_here = diag::note_arc_init_returns_unrelated;
6594 case UnavailableAttr::IR_ARCFieldWithOwnership:
6596 diag_available_here = diag::note_arc_field_with_ownership;
6603 case AR_NotYetIntroduced:
6604 diag = diag::warn_partial_availability;
6605 diag_message = diag::warn_partial_message;
6606 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6607 property_note_select = /* partial */ 2;
6608 available_here_select_kind = /* partial */ 3;
6612 llvm_unreachable("Warning for availability of available declaration?");
6615 CharSourceRange UseRange;
6616 StringRef Replacement;
6617 if (K == AR_Deprecated) {
6618 if (auto attr = D->getAttr<DeprecatedAttr>())
6619 Replacement = attr->getReplacement();
6620 if (auto attr = getAttrForPlatform(S.Context, D))
6621 Replacement = attr->getReplacement();
6623 if (!Replacement.empty())
6625 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6628 if (!Message.empty()) {
6629 S.Diag(Loc, diag_message) << D << Message
6630 << (UseRange.isValid() ?
6631 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6633 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6634 << ObjCProperty->getDeclName() << property_note_select;
6635 } else if (!UnknownObjCClass) {
6636 S.Diag(Loc, diag) << D
6637 << (UseRange.isValid() ?
6638 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6640 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6641 << ObjCProperty->getDeclName() << property_note_select;
6643 S.Diag(Loc, diag_fwdclass_message) << D
6644 << (UseRange.isValid() ?
6645 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6646 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6649 // The declaration can have multiple availability attributes, we are looking
6651 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6652 if (A && A->isInherited()) {
6653 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6654 Redecl = Redecl->getPreviousDecl()) {
6655 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6657 if (AForRedecl && !AForRedecl->isInherited()) {
6658 // If D is a declaration with inherited attributes, the note should
6659 // point to the declaration with actual attributes.
6660 S.Diag(Redecl->getLocation(), diag_available_here) << D
6661 << available_here_select_kind;
6667 S.Diag(D->getLocation(), diag_available_here)
6668 << D << available_here_select_kind;
6670 if (K == AR_NotYetIntroduced)
6671 S.Diag(Loc, diag::note_partial_availability_silence) << D;
6674 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6676 assert(DD.Kind == DelayedDiagnostic::Availability &&
6677 "Expected an availability diagnostic here");
6679 DD.Triggered = true;
6680 DoEmitAvailabilityWarning(
6681 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
6682 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
6683 DD.getObjCProperty(), false);
6686 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
6687 assert(DelayedDiagnostics.getCurrentPool());
6688 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
6689 DelayedDiagnostics.popWithoutEmitting(state);
6691 // When delaying diagnostics to run in the context of a parsed
6692 // declaration, we only want to actually emit anything if parsing
6696 // We emit all the active diagnostics in this pool or any of its
6697 // parents. In general, we'll get one pool for the decl spec
6698 // and a child pool for each declarator; in a decl group like:
6699 // deprecated_typedef foo, *bar, baz();
6700 // only the declarator pops will be passed decls. This is correct;
6701 // we really do need to consider delayed diagnostics from the decl spec
6702 // for each of the different declarations.
6703 const DelayedDiagnosticPool *pool = &poppedPool;
6705 for (DelayedDiagnosticPool::pool_iterator
6706 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
6707 // This const_cast is a bit lame. Really, Triggered should be mutable.
6708 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
6712 switch (diag.Kind) {
6713 case DelayedDiagnostic::Availability:
6714 // Don't bother giving deprecation/unavailable diagnostics if
6715 // the decl is invalid.
6716 if (!decl->isInvalidDecl())
6717 handleDelayedAvailabilityCheck(*this, diag, decl);
6720 case DelayedDiagnostic::Access:
6721 HandleDelayedAccessCheck(diag, decl);
6724 case DelayedDiagnostic::ForbiddenType:
6725 handleDelayedForbiddenType(*this, diag, decl);
6729 } while ((pool = pool->getParent()));
6732 /// Given a set of delayed diagnostics, re-emit them as if they had
6733 /// been delayed in the current context instead of in the given pool.
6734 /// Essentially, this just moves them to the current pool.
6735 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
6736 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
6737 assert(curPool && "re-emitting in undelayed context not supported");
6738 curPool->steal(pool);
6741 void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
6742 NamedDecl *D, StringRef Message,
6744 const ObjCInterfaceDecl *UnknownObjCClass,
6745 const ObjCPropertyDecl *ObjCProperty,
6746 bool ObjCPropertyAccess) {
6747 // Delay if we're currently parsing a declaration.
6748 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
6749 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
6750 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
6751 ObjCPropertyAccess));
6755 Decl *Ctx = cast<Decl>(getCurLexicalContext());
6756 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
6757 ObjCProperty, ObjCPropertyAccess);
6762 /// \brief This class implements -Wunguarded-availability.
6764 /// This is done with a traversal of the AST of a function that makes reference
6765 /// to a partially available declaration. Whenever we encounter an \c if of the
6766 /// form: \c if(@available(...)), we use the version from the condition to visit
6767 /// the then statement.
6768 class DiagnoseUnguardedAvailability
6769 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
6770 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
6775 /// Stack of potentially nested 'if (@available(...))'s.
6776 SmallVector<VersionTuple, 8> AvailabilityStack;
6778 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
6781 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
6782 : SemaRef(SemaRef), Ctx(Ctx) {
6783 AvailabilityStack.push_back(
6784 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
6787 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
6789 bool TraverseIfStmt(IfStmt *If);
6791 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
6792 if (ObjCMethodDecl *D = Msg->getMethodDecl())
6793 DiagnoseDeclAvailability(
6794 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
6798 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
6799 DiagnoseDeclAvailability(DRE->getDecl(),
6800 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
6804 bool VisitMemberExpr(MemberExpr *ME) {
6805 DiagnoseDeclAvailability(ME->getMemberDecl(),
6806 SourceRange(ME->getLocStart(), ME->getLocEnd()));
6810 bool VisitTypeLoc(TypeLoc Ty);
6813 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
6814 NamedDecl *D, SourceRange Range) {
6816 VersionTuple ContextVersion = AvailabilityStack.back();
6817 if (AvailabilityResult Result =
6818 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
6819 // All other diagnostic kinds have already been handled in
6820 // DiagnoseAvailabilityOfDecl.
6821 if (Result != AR_NotYetIntroduced)
6824 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
6825 VersionTuple Introduced = AA->getIntroduced();
6827 if (ContextVersion >= Introduced)
6830 // If the context of this function is less available than D, we should not
6831 // emit a diagnostic.
6832 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
6835 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
6837 << AvailabilityAttr::getPrettyPlatformName(
6838 SemaRef.getASTContext().getTargetInfo().getPlatformName())
6839 << Introduced.getAsString();
6841 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
6842 << D << /* partial */ 3;
6844 // FIXME: Replace this with a fixit diagnostic.
6845 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
6850 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
6851 const Type *TyPtr = Ty.getTypePtr();
6852 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
6854 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
6855 TagDecl *TD = TT->getDecl();
6856 DiagnoseDeclAvailability(TD, Range);
6858 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
6859 TypedefNameDecl *D = TD->getDecl();
6860 DiagnoseDeclAvailability(D, Range);
6862 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
6863 if (NamedDecl *D = ObjCO->getInterface())
6864 DiagnoseDeclAvailability(D, Range);
6870 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
6871 VersionTuple CondVersion;
6872 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
6873 CondVersion = E->getVersion();
6875 // If we're using the '*' case here or if this check is redundant, then we
6876 // use the enclosing version to check both branches.
6877 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
6878 return Base::TraverseStmt(If->getThen()) &&
6879 Base::TraverseStmt(If->getElse());
6881 // This isn't an availability checking 'if', we can just continue.
6882 return Base::TraverseIfStmt(If);
6885 AvailabilityStack.push_back(CondVersion);
6886 bool ShouldContinue = TraverseStmt(If->getThen());
6887 AvailabilityStack.pop_back();
6889 return ShouldContinue && TraverseStmt(If->getElse());
6892 } // end anonymous namespace
6894 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
6895 Stmt *Body = nullptr;
6897 if (auto *FD = D->getAsFunction()) {
6898 // FIXME: We only examine the pattern decl for availability violations now,
6899 // but we should also examine instantiated templates.
6900 if (FD->isTemplateInstantiation())
6903 Body = FD->getBody();
6904 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
6905 Body = MD->getBody();
6907 assert(Body && "Need a body here!");
6909 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);