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/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/AST/ASTMutationListener.h"
24 #include "clang/Basic/CharInfo.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Scope.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/MathExtras.h"
34 using namespace clang;
37 namespace AttributeLangSupport {
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 /// isFunctionOrMethod - Return true if the given decl has function
50 /// type (function or function-typed variable) or an Objective-C
52 static bool isFunctionOrMethod(const Decl *D) {
53 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
55 /// \brief Return true if the given decl has function type (function or
56 /// function-typed variable) or an Objective-C method or a block.
57 static bool isFunctionOrMethodOrBlock(const Decl *D) {
58 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
61 /// Return true if the given decl has a declarator that should have
62 /// been processed by Sema::GetTypeForDeclarator.
63 static bool hasDeclarator(const Decl *D) {
64 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
65 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
66 isa<ObjCPropertyDecl>(D);
69 /// hasFunctionProto - Return true if the given decl has a argument
70 /// information. This decl should have already passed
71 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
72 static bool hasFunctionProto(const Decl *D) {
73 if (const FunctionType *FnTy = D->getFunctionType())
74 return isa<FunctionProtoType>(FnTy);
75 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
78 /// getFunctionOrMethodNumParams - Return number of function or method
79 /// parameters. It is an error to call this on a K&R function (use
80 /// hasFunctionProto first).
81 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
82 if (const FunctionType *FnTy = D->getFunctionType())
83 return cast<FunctionProtoType>(FnTy)->getNumParams();
84 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
85 return BD->getNumParams();
86 return cast<ObjCMethodDecl>(D)->param_size();
89 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
90 if (const FunctionType *FnTy = D->getFunctionType())
91 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
92 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
93 return BD->getParamDecl(Idx)->getType();
95 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
98 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
99 if (const auto *FD = dyn_cast<FunctionDecl>(D))
100 return FD->getParamDecl(Idx)->getSourceRange();
101 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
102 return MD->parameters()[Idx]->getSourceRange();
103 if (const auto *BD = dyn_cast<BlockDecl>(D))
104 return BD->getParamDecl(Idx)->getSourceRange();
105 return SourceRange();
108 static QualType getFunctionOrMethodResultType(const Decl *D) {
109 if (const FunctionType *FnTy = D->getFunctionType())
110 return cast<FunctionType>(FnTy)->getReturnType();
111 return cast<ObjCMethodDecl>(D)->getReturnType();
114 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
115 if (const auto *FD = dyn_cast<FunctionDecl>(D))
116 return FD->getReturnTypeSourceRange();
117 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
118 return MD->getReturnTypeSourceRange();
119 return SourceRange();
122 static bool isFunctionOrMethodVariadic(const Decl *D) {
123 if (const FunctionType *FnTy = D->getFunctionType()) {
124 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
125 return proto->isVariadic();
127 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
128 return BD->isVariadic();
130 return cast<ObjCMethodDecl>(D)->isVariadic();
133 static bool isInstanceMethod(const Decl *D) {
134 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
135 return MethodDecl->isInstance();
139 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
140 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
144 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
148 IdentifierInfo* ClsName = Cls->getIdentifier();
150 // FIXME: Should we walk the chain of classes?
151 return ClsName == &Ctx.Idents.get("NSString") ||
152 ClsName == &Ctx.Idents.get("NSMutableString");
155 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
156 const PointerType *PT = T->getAs<PointerType>();
160 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
164 const RecordDecl *RD = RT->getDecl();
165 if (RD->getTagKind() != TTK_Struct)
168 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
171 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
172 // FIXME: Include the type in the argument list.
173 return Attr.getNumArgs() + Attr.hasParsedType();
176 template <typename Compare>
177 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
178 unsigned Num, unsigned Diag,
180 if (Comp(getNumAttributeArgs(Attr), Num)) {
181 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
188 /// \brief Check if the attribute has exactly as many args as Num. May
190 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
192 return checkAttributeNumArgsImpl(S, Attr, Num,
193 diag::err_attribute_wrong_number_arguments,
194 std::not_equal_to<unsigned>());
197 /// \brief Check if the attribute has at least as many args as Num. May
199 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
201 return checkAttributeNumArgsImpl(S, Attr, Num,
202 diag::err_attribute_too_few_arguments,
203 std::less<unsigned>());
206 /// \brief Check if the attribute has at most as many args as Num. May
208 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
210 return checkAttributeNumArgsImpl(S, Attr, Num,
211 diag::err_attribute_too_many_arguments,
212 std::greater<unsigned>());
215 /// \brief If Expr is a valid integer constant, get the value of the integer
216 /// expression and return success or failure. May output an error.
217 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
218 const Expr *Expr, uint32_t &Val,
219 unsigned Idx = UINT_MAX) {
221 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
222 !Expr->isIntegerConstantExpr(I, S.Context)) {
224 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
225 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
226 << Expr->getSourceRange();
228 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
229 << Attr.getName() << AANT_ArgumentIntegerConstant
230 << Expr->getSourceRange();
235 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
236 << I.toString(10, false) << 32 << /* Unsigned */ 1;
240 Val = (uint32_t)I.getZExtValue();
244 /// \brief Diagnose mutually exclusive attributes when present on a given
245 /// declaration. Returns true if diagnosed.
246 template <typename AttrTy>
247 static bool checkAttrMutualExclusion(Sema &S, Decl *D,
248 const AttributeList &Attr) {
249 if (AttrTy *A = D->getAttr<AttrTy>()) {
250 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
251 << Attr.getName() << A;
257 /// \brief Check if IdxExpr is a valid parameter index for a function or
258 /// instance method D. May output an error.
260 /// \returns true if IdxExpr is a valid index.
261 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
262 const AttributeList &Attr,
266 assert(isFunctionOrMethodOrBlock(D));
268 // In C++ the implicit 'this' function parameter also counts.
269 // Parameters are counted from one.
270 bool HP = hasFunctionProto(D);
271 bool HasImplicitThisParam = isInstanceMethod(D);
272 bool IV = HP && isFunctionOrMethodVariadic(D);
274 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
277 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
278 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
279 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
280 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
281 << IdxExpr->getSourceRange();
285 Idx = IdxInt.getLimitedValue();
286 if (Idx < 1 || (!IV && Idx > NumParams)) {
287 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
288 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
291 Idx--; // Convert to zero-based.
292 if (HasImplicitThisParam) {
294 S.Diag(Attr.getLoc(),
295 diag::err_attribute_invalid_implicit_this_argument)
296 << Attr.getName() << IdxExpr->getSourceRange();
305 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
306 /// If not emit an error and return false. If the argument is an identifier it
307 /// will emit an error with a fixit hint and treat it as if it was a string
309 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
310 unsigned ArgNum, StringRef &Str,
311 SourceLocation *ArgLocation) {
312 // Look for identifiers. If we have one emit a hint to fix it to a literal.
313 if (Attr.isArgIdent(ArgNum)) {
314 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
315 Diag(Loc->Loc, diag::err_attribute_argument_type)
316 << Attr.getName() << AANT_ArgumentString
317 << FixItHint::CreateInsertion(Loc->Loc, "\"")
318 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
319 Str = Loc->Ident->getName();
321 *ArgLocation = Loc->Loc;
325 // Now check for an actual string literal.
326 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
327 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
329 *ArgLocation = ArgExpr->getLocStart();
331 if (!Literal || !Literal->isAscii()) {
332 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
333 << Attr.getName() << AANT_ArgumentString;
337 Str = Literal->getString();
341 /// \brief Applies the given attribute to the Decl without performing any
342 /// additional semantic checking.
343 template <typename AttrType>
344 static void handleSimpleAttribute(Sema &S, Decl *D,
345 const AttributeList &Attr) {
346 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
347 Attr.getAttributeSpellingListIndex()));
350 /// \brief Check if the passed-in expression is of type int or bool.
351 static bool isIntOrBool(Expr *Exp) {
352 QualType QT = Exp->getType();
353 return QT->isBooleanType() || QT->isIntegerType();
357 // Check to see if the type is a smart pointer of some kind. We assume
358 // it's a smart pointer if it defines both operator-> and operator*.
359 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
360 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
361 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
365 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
366 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
373 /// \brief Check if passed in Decl is a pointer type.
374 /// Note that this function may produce an error message.
375 /// \return true if the Decl is a pointer type; false otherwise
376 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
377 const AttributeList &Attr) {
378 const ValueDecl *vd = cast<ValueDecl>(D);
379 QualType QT = vd->getType();
380 if (QT->isAnyPointerType())
383 if (const RecordType *RT = QT->getAs<RecordType>()) {
384 // If it's an incomplete type, it could be a smart pointer; skip it.
385 // (We don't want to force template instantiation if we can avoid it,
386 // since that would alter the order in which templates are instantiated.)
387 if (RT->isIncompleteType())
390 if (threadSafetyCheckIsSmartPointer(S, RT))
394 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
395 << Attr.getName() << QT;
399 /// \brief Checks that the passed in QualType either is of RecordType or points
400 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
401 static const RecordType *getRecordType(QualType QT) {
402 if (const RecordType *RT = QT->getAs<RecordType>())
405 // Now check if we point to record type.
406 if (const PointerType *PT = QT->getAs<PointerType>())
407 return PT->getPointeeType()->getAs<RecordType>();
412 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
413 const RecordType *RT = getRecordType(Ty);
418 // Don't check for the capability if the class hasn't been defined yet.
419 if (RT->isIncompleteType())
422 // Allow smart pointers to be used as capability objects.
423 // FIXME -- Check the type that the smart pointer points to.
424 if (threadSafetyCheckIsSmartPointer(S, RT))
427 // Check if the record itself has a capability.
428 RecordDecl *RD = RT->getDecl();
429 if (RD->hasAttr<CapabilityAttr>())
432 // Else check if any base classes have a capability.
433 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
434 CXXBasePaths BPaths(false, false);
435 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P,
437 return BS->getType()->getAs<RecordType>()
438 ->getDecl()->hasAttr<CapabilityAttr>();
445 static bool checkTypedefTypeForCapability(QualType Ty) {
446 const auto *TD = Ty->getAs<TypedefType>();
450 TypedefNameDecl *TN = TD->getDecl();
454 return TN->hasAttr<CapabilityAttr>();
457 static bool typeHasCapability(Sema &S, QualType Ty) {
458 if (checkTypedefTypeForCapability(Ty))
461 if (checkRecordTypeForCapability(S, Ty))
467 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
468 // Capability expressions are simple expressions involving the boolean logic
469 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
470 // a DeclRefExpr is found, its type should be checked to determine whether it
471 // is a capability or not.
473 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
474 return typeHasCapability(S, E->getType());
475 else if (const auto *E = dyn_cast<CastExpr>(Ex))
476 return isCapabilityExpr(S, E->getSubExpr());
477 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
478 return isCapabilityExpr(S, E->getSubExpr());
479 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
480 if (E->getOpcode() == UO_LNot)
481 return isCapabilityExpr(S, E->getSubExpr());
483 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
484 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
485 return isCapabilityExpr(S, E->getLHS()) &&
486 isCapabilityExpr(S, E->getRHS());
493 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
494 /// a capability object.
495 /// \param Sidx The attribute argument index to start checking with.
496 /// \param ParamIdxOk Whether an argument can be indexing into a function
498 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
499 const AttributeList &Attr,
500 SmallVectorImpl<Expr *> &Args,
502 bool ParamIdxOk = false) {
503 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
504 Expr *ArgExp = Attr.getArgAsExpr(Idx);
506 if (ArgExp->isTypeDependent()) {
507 // FIXME -- need to check this again on template instantiation
508 Args.push_back(ArgExp);
512 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
513 if (StrLit->getLength() == 0 ||
514 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
515 // Pass empty strings to the analyzer without warnings.
516 // Treat "*" as the universal lock.
517 Args.push_back(ArgExp);
521 // We allow constant strings to be used as a placeholder for expressions
522 // that are not valid C++ syntax, but warn that they are ignored.
523 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
525 Args.push_back(ArgExp);
529 QualType ArgTy = ArgExp->getType();
531 // A pointer to member expression of the form &MyClass::mu is treated
532 // specially -- we need to look at the type of the member.
533 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
534 if (UOp->getOpcode() == UO_AddrOf)
535 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
536 if (DRE->getDecl()->isCXXInstanceMember())
537 ArgTy = DRE->getDecl()->getType();
539 // First see if we can just cast to record type, or pointer to record type.
540 const RecordType *RT = getRecordType(ArgTy);
542 // Now check if we index into a record type function param.
543 if(!RT && ParamIdxOk) {
544 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
545 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
547 unsigned int NumParams = FD->getNumParams();
548 llvm::APInt ArgValue = IL->getValue();
549 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
550 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
551 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
552 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
553 << Attr.getName() << Idx + 1 << NumParams;
556 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
560 // If the type does not have a capability, see if the components of the
561 // expression have capabilities. This allows for writing C code where the
562 // capability may be on the type, and the expression is a capability
563 // boolean logic expression. Eg) requires_capability(A || B && !C)
564 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
565 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
566 << Attr.getName() << ArgTy;
568 Args.push_back(ArgExp);
572 //===----------------------------------------------------------------------===//
573 // Attribute Implementations
574 //===----------------------------------------------------------------------===//
576 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
577 const AttributeList &Attr) {
578 if (!threadSafetyCheckIsPointer(S, D, Attr))
581 D->addAttr(::new (S.Context)
582 PtGuardedVarAttr(Attr.getRange(), S.Context,
583 Attr.getAttributeSpellingListIndex()));
586 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
587 const AttributeList &Attr,
589 SmallVector<Expr*, 1> Args;
590 // check that all arguments are lockable objects
591 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
592 unsigned Size = Args.size();
601 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
603 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
606 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
607 Attr.getAttributeSpellingListIndex()));
610 static void handlePtGuardedByAttr(Sema &S, Decl *D,
611 const AttributeList &Attr) {
613 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
616 if (!threadSafetyCheckIsPointer(S, D, Attr))
619 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
621 Attr.getAttributeSpellingListIndex()));
624 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
625 const AttributeList &Attr,
626 SmallVectorImpl<Expr *> &Args) {
627 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
630 // Check that this attribute only applies to lockable types.
631 QualType QT = cast<ValueDecl>(D)->getType();
632 if (!QT->isDependentType()) {
633 const RecordType *RT = getRecordType(QT);
634 if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) {
635 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
641 // Check that all arguments are lockable objects.
642 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
649 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
650 const AttributeList &Attr) {
651 SmallVector<Expr*, 1> Args;
652 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
655 Expr **StartArg = &Args[0];
656 D->addAttr(::new (S.Context)
657 AcquiredAfterAttr(Attr.getRange(), S.Context,
658 StartArg, Args.size(),
659 Attr.getAttributeSpellingListIndex()));
662 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
663 const AttributeList &Attr) {
664 SmallVector<Expr*, 1> Args;
665 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
668 Expr **StartArg = &Args[0];
669 D->addAttr(::new (S.Context)
670 AcquiredBeforeAttr(Attr.getRange(), S.Context,
671 StartArg, Args.size(),
672 Attr.getAttributeSpellingListIndex()));
675 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
676 const AttributeList &Attr,
677 SmallVectorImpl<Expr *> &Args) {
678 // zero or more arguments ok
679 // check that all arguments are lockable objects
680 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
685 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
686 const AttributeList &Attr) {
687 SmallVector<Expr*, 1> Args;
688 if (!checkLockFunAttrCommon(S, D, Attr, Args))
691 unsigned Size = Args.size();
692 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
693 D->addAttr(::new (S.Context)
694 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
695 Attr.getAttributeSpellingListIndex()));
698 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
699 const AttributeList &Attr) {
700 SmallVector<Expr*, 1> Args;
701 if (!checkLockFunAttrCommon(S, D, Attr, Args))
704 unsigned Size = Args.size();
705 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
706 D->addAttr(::new (S.Context)
707 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
709 Attr.getAttributeSpellingListIndex()));
713 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
714 const AttributeList &Attr,
715 SmallVectorImpl<Expr *> &Args) {
716 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
719 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
720 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
721 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
725 // check that all arguments are lockable objects
726 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
731 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
732 const AttributeList &Attr) {
733 SmallVector<Expr*, 2> Args;
734 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
737 D->addAttr(::new (S.Context)
738 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
739 Attr.getArgAsExpr(0),
740 Args.data(), Args.size(),
741 Attr.getAttributeSpellingListIndex()));
744 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
745 const AttributeList &Attr) {
746 SmallVector<Expr*, 2> Args;
747 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
750 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
751 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
752 Args.size(), Attr.getAttributeSpellingListIndex()));
755 static void handleLockReturnedAttr(Sema &S, Decl *D,
756 const AttributeList &Attr) {
757 // check that the argument is lockable object
758 SmallVector<Expr*, 1> Args;
759 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
760 unsigned Size = Args.size();
764 D->addAttr(::new (S.Context)
765 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
766 Attr.getAttributeSpellingListIndex()));
769 static void handleLocksExcludedAttr(Sema &S, Decl *D,
770 const AttributeList &Attr) {
771 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
774 // check that all arguments are lockable objects
775 SmallVector<Expr*, 1> Args;
776 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
777 unsigned Size = Args.size();
780 Expr **StartArg = &Args[0];
782 D->addAttr(::new (S.Context)
783 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
784 Attr.getAttributeSpellingListIndex()));
787 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
788 Expr *Cond = Attr.getArgAsExpr(0);
789 if (!Cond->isTypeDependent()) {
790 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
791 if (Converted.isInvalid())
793 Cond = Converted.get();
797 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
800 SmallVector<PartialDiagnosticAt, 8> Diags;
801 if (!Cond->isValueDependent() &&
802 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
804 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
805 for (int I = 0, N = Diags.size(); I != N; ++I)
806 S.Diag(Diags[I].first, Diags[I].second);
810 D->addAttr(::new (S.Context)
811 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
812 Attr.getAttributeSpellingListIndex()));
815 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
816 ConsumableAttr::ConsumedState DefaultState;
818 if (Attr.isArgIdent(0)) {
819 IdentifierLoc *IL = Attr.getArgAsIdent(0);
820 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
822 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
823 << Attr.getName() << IL->Ident;
827 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
828 << Attr.getName() << AANT_ArgumentIdentifier;
832 D->addAttr(::new (S.Context)
833 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
834 Attr.getAttributeSpellingListIndex()));
838 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
839 const AttributeList &Attr) {
840 ASTContext &CurrContext = S.getASTContext();
841 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
843 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
844 if (!RD->hasAttr<ConsumableAttr>()) {
845 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
846 RD->getNameAsString();
856 static void handleCallableWhenAttr(Sema &S, Decl *D,
857 const AttributeList &Attr) {
858 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
861 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
864 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
865 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
866 CallableWhenAttr::ConsumedState CallableState;
868 StringRef StateString;
870 if (Attr.isArgIdent(ArgIndex)) {
871 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
872 StateString = Ident->Ident->getName();
875 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
879 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
881 S.Diag(Loc, diag::warn_attribute_type_not_supported)
882 << Attr.getName() << StateString;
886 States.push_back(CallableState);
889 D->addAttr(::new (S.Context)
890 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
891 States.size(), Attr.getAttributeSpellingListIndex()));
895 static void handleParamTypestateAttr(Sema &S, Decl *D,
896 const AttributeList &Attr) {
897 ParamTypestateAttr::ConsumedState ParamState;
899 if (Attr.isArgIdent(0)) {
900 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
901 StringRef StateString = Ident->Ident->getName();
903 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
905 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
906 << Attr.getName() << StateString;
910 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
911 Attr.getName() << AANT_ArgumentIdentifier;
915 // FIXME: This check is currently being done in the analysis. It can be
916 // enabled here only after the parser propagates attributes at
917 // template specialization definition, not declaration.
918 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
919 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
921 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
922 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
923 // ReturnType.getAsString();
927 D->addAttr(::new (S.Context)
928 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
929 Attr.getAttributeSpellingListIndex()));
933 static void handleReturnTypestateAttr(Sema &S, Decl *D,
934 const AttributeList &Attr) {
935 ReturnTypestateAttr::ConsumedState ReturnState;
937 if (Attr.isArgIdent(0)) {
938 IdentifierLoc *IL = Attr.getArgAsIdent(0);
939 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
941 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
942 << Attr.getName() << IL->Ident;
946 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
947 Attr.getName() << AANT_ArgumentIdentifier;
951 // FIXME: This check is currently being done in the analysis. It can be
952 // enabled here only after the parser propagates attributes at
953 // template specialization definition, not declaration.
954 //QualType ReturnType;
956 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
957 // ReturnType = Param->getType();
959 //} else if (const CXXConstructorDecl *Constructor =
960 // dyn_cast<CXXConstructorDecl>(D)) {
961 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
965 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
968 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
970 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
971 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
972 // ReturnType.getAsString();
976 D->addAttr(::new (S.Context)
977 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
978 Attr.getAttributeSpellingListIndex()));
982 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
983 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
986 SetTypestateAttr::ConsumedState NewState;
987 if (Attr.isArgIdent(0)) {
988 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
989 StringRef Param = Ident->Ident->getName();
990 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
991 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
992 << Attr.getName() << Param;
996 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
997 Attr.getName() << AANT_ArgumentIdentifier;
1001 D->addAttr(::new (S.Context)
1002 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1003 Attr.getAttributeSpellingListIndex()));
1006 static void handleTestTypestateAttr(Sema &S, Decl *D,
1007 const AttributeList &Attr) {
1008 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1011 TestTypestateAttr::ConsumedState TestState;
1012 if (Attr.isArgIdent(0)) {
1013 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1014 StringRef Param = Ident->Ident->getName();
1015 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1016 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1017 << Attr.getName() << Param;
1021 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1022 Attr.getName() << AANT_ArgumentIdentifier;
1026 D->addAttr(::new (S.Context)
1027 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1028 Attr.getAttributeSpellingListIndex()));
1031 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1032 const AttributeList &Attr) {
1033 // Remember this typedef decl, we will need it later for diagnostics.
1034 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1037 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1038 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1039 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1040 Attr.getAttributeSpellingListIndex()));
1041 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1042 // If the alignment is less than or equal to 8 bits, the packed attribute
1044 if (!FD->getType()->isDependentType() &&
1045 !FD->getType()->isIncompleteType() &&
1046 S.Context.getTypeAlign(FD->getType()) <= 8)
1047 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1048 << Attr.getName() << FD->getType();
1050 FD->addAttr(::new (S.Context)
1051 PackedAttr(Attr.getRange(), S.Context,
1052 Attr.getAttributeSpellingListIndex()));
1054 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1057 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1058 // The IBOutlet/IBOutletCollection attributes only apply to instance
1059 // variables or properties of Objective-C classes. The outlet must also
1060 // have an object reference type.
1061 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1062 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1063 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1064 << Attr.getName() << VD->getType() << 0;
1068 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1069 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1070 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1071 << Attr.getName() << PD->getType() << 1;
1076 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1083 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1084 if (!checkIBOutletCommon(S, D, Attr))
1087 D->addAttr(::new (S.Context)
1088 IBOutletAttr(Attr.getRange(), S.Context,
1089 Attr.getAttributeSpellingListIndex()));
1092 static void handleIBOutletCollection(Sema &S, Decl *D,
1093 const AttributeList &Attr) {
1095 // The iboutletcollection attribute can have zero or one arguments.
1096 if (Attr.getNumArgs() > 1) {
1097 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1098 << Attr.getName() << 1;
1102 if (!checkIBOutletCommon(S, D, Attr))
1107 if (Attr.hasParsedType())
1108 PT = Attr.getTypeArg();
1110 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1111 S.getScopeForContext(D->getDeclContext()->getParent()));
1113 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1118 TypeSourceInfo *QTLoc = nullptr;
1119 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1121 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1123 // Diagnose use of non-object type in iboutletcollection attribute.
1124 // FIXME. Gnu attribute extension ignores use of builtin types in
1125 // attributes. So, __attribute__((iboutletcollection(char))) will be
1126 // treated as __attribute__((iboutletcollection())).
1127 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1128 S.Diag(Attr.getLoc(),
1129 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1130 : diag::err_iboutletcollection_type) << QT;
1134 D->addAttr(::new (S.Context)
1135 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1136 Attr.getAttributeSpellingListIndex()));
1139 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1141 if (T->isReferenceType())
1144 T = T.getNonReferenceType();
1147 // The nonnull attribute, and other similar attributes, can be applied to a
1148 // transparent union that contains a pointer type.
1149 if (const RecordType *UT = T->getAsUnionType()) {
1150 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1151 RecordDecl *UD = UT->getDecl();
1152 for (const auto *I : UD->fields()) {
1153 QualType QT = I->getType();
1154 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1160 return T->isAnyPointerType() || T->isBlockPointerType();
1163 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1164 SourceRange AttrParmRange,
1165 SourceRange TypeRange,
1166 bool isReturnValue = false) {
1167 if (!S.isValidPointerAttrType(T)) {
1168 S.Diag(Attr.getLoc(), isReturnValue
1169 ? diag::warn_attribute_return_pointers_only
1170 : diag::warn_attribute_pointers_only)
1171 << Attr.getName() << AttrParmRange << TypeRange;
1177 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1178 SmallVector<unsigned, 8> NonNullArgs;
1179 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1180 Expr *Ex = Attr.getArgAsExpr(I);
1182 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1185 // Is the function argument a pointer type?
1186 if (Idx < getFunctionOrMethodNumParams(D) &&
1187 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1188 Ex->getSourceRange(),
1189 getFunctionOrMethodParamRange(D, Idx)))
1192 NonNullArgs.push_back(Idx);
1195 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1196 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1197 // check if the attribute came from a macro expansion or a template
1199 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1200 S.ActiveTemplateInstantiations.empty()) {
1201 bool AnyPointers = isFunctionOrMethodVariadic(D);
1202 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1203 I != E && !AnyPointers; ++I) {
1204 QualType T = getFunctionOrMethodParamType(D, I);
1205 if (T->isDependentType() || S.isValidPointerAttrType(T))
1210 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1213 unsigned *Start = NonNullArgs.data();
1214 unsigned Size = NonNullArgs.size();
1215 llvm::array_pod_sort(Start, Start + Size);
1216 D->addAttr(::new (S.Context)
1217 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1218 Attr.getAttributeSpellingListIndex()));
1221 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1222 const AttributeList &Attr) {
1223 if (Attr.getNumArgs() > 0) {
1224 if (D->getFunctionType()) {
1225 handleNonNullAttr(S, D, Attr);
1227 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1228 << D->getSourceRange();
1233 // Is the argument a pointer type?
1234 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1235 D->getSourceRange()))
1238 D->addAttr(::new (S.Context)
1239 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1240 Attr.getAttributeSpellingListIndex()));
1243 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1244 const AttributeList &Attr) {
1245 QualType ResultType = getFunctionOrMethodResultType(D);
1246 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1247 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1248 /* isReturnValue */ true))
1251 D->addAttr(::new (S.Context)
1252 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1253 Attr.getAttributeSpellingListIndex()));
1256 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1257 const AttributeList &Attr) {
1258 Expr *E = Attr.getArgAsExpr(0),
1259 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1260 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1261 Attr.getAttributeSpellingListIndex());
1264 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1265 Expr *OE, unsigned SpellingListIndex) {
1266 QualType ResultType = getFunctionOrMethodResultType(D);
1267 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1269 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1270 SourceLocation AttrLoc = AttrRange.getBegin();
1272 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1273 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1274 << &TmpAttr << AttrRange << SR;
1278 if (!E->isValueDependent()) {
1280 if (!E->isIntegerConstantExpr(I, Context)) {
1282 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1283 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1284 << E->getSourceRange();
1286 Diag(AttrLoc, diag::err_attribute_argument_type)
1287 << &TmpAttr << AANT_ArgumentIntegerConstant
1288 << E->getSourceRange();
1292 if (!I.isPowerOf2()) {
1293 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1294 << E->getSourceRange();
1300 if (!OE->isValueDependent()) {
1302 if (!OE->isIntegerConstantExpr(I, Context)) {
1303 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1304 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1305 << OE->getSourceRange();
1311 D->addAttr(::new (Context)
1312 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1315 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1316 // This attribute must be applied to a function declaration. The first
1317 // argument to the attribute must be an identifier, the name of the resource,
1318 // for example: malloc. The following arguments must be argument indexes, the
1319 // arguments must be of integer type for Returns, otherwise of pointer type.
1320 // The difference between Holds and Takes is that a pointer may still be used
1321 // after being held. free() should be __attribute((ownership_takes)), whereas
1322 // a list append function may well be __attribute((ownership_holds)).
1324 if (!AL.isArgIdent(0)) {
1325 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1326 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1330 // Figure out our Kind.
1331 OwnershipAttr::OwnershipKind K =
1332 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1333 AL.getAttributeSpellingListIndex()).getOwnKind();
1337 case OwnershipAttr::Takes:
1338 case OwnershipAttr::Holds:
1339 if (AL.getNumArgs() < 2) {
1340 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1341 << AL.getName() << 2;
1345 case OwnershipAttr::Returns:
1346 if (AL.getNumArgs() > 2) {
1347 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1348 << AL.getName() << 1;
1354 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1356 // Normalize the argument, __foo__ becomes foo.
1357 StringRef ModuleName = Module->getName();
1358 if (ModuleName.startswith("__") && ModuleName.endswith("__") &&
1359 ModuleName.size() > 4) {
1360 ModuleName = ModuleName.drop_front(2).drop_back(2);
1361 Module = &S.PP.getIdentifierTable().get(ModuleName);
1364 SmallVector<unsigned, 8> OwnershipArgs;
1365 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1366 Expr *Ex = AL.getArgAsExpr(i);
1368 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1371 // Is the function argument a pointer type?
1372 QualType T = getFunctionOrMethodParamType(D, Idx);
1373 int Err = -1; // No error
1375 case OwnershipAttr::Takes:
1376 case OwnershipAttr::Holds:
1377 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1380 case OwnershipAttr::Returns:
1381 if (!T->isIntegerType())
1386 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1387 << Ex->getSourceRange();
1391 // Check we don't have a conflict with another ownership attribute.
1392 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1393 // Cannot have two ownership attributes of different kinds for the same
1395 if (I->getOwnKind() != K && I->args_end() !=
1396 std::find(I->args_begin(), I->args_end(), Idx)) {
1397 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1398 << AL.getName() << I;
1400 } else if (K == OwnershipAttr::Returns &&
1401 I->getOwnKind() == OwnershipAttr::Returns) {
1402 // A returns attribute conflicts with any other returns attribute using
1403 // a different index. Note, diagnostic reporting is 1-based, but stored
1404 // argument indexes are 0-based.
1405 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1406 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1407 << *(I->args_begin()) + 1;
1409 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1410 << (unsigned)Idx + 1 << Ex->getSourceRange();
1415 OwnershipArgs.push_back(Idx);
1418 unsigned* start = OwnershipArgs.data();
1419 unsigned size = OwnershipArgs.size();
1420 llvm::array_pod_sort(start, start + size);
1422 D->addAttr(::new (S.Context)
1423 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1424 AL.getAttributeSpellingListIndex()));
1427 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1428 // Check the attribute arguments.
1429 if (Attr.getNumArgs() > 1) {
1430 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1431 << Attr.getName() << 1;
1435 NamedDecl *nd = cast<NamedDecl>(D);
1439 // static int a __attribute__((weakref ("v2")));
1440 // static int b() __attribute__((weakref ("f3")));
1442 // and ignores the attributes of
1444 // static int a __attribute__((weakref ("v2")));
1447 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1448 if (!Ctx->isFileContext()) {
1449 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1454 // The GCC manual says
1456 // At present, a declaration to which `weakref' is attached can only
1461 // Without a TARGET,
1462 // given as an argument to `weakref' or to `alias', `weakref' is
1463 // equivalent to `weak'.
1465 // gcc 4.4.1 will accept
1466 // int a7 __attribute__((weakref));
1468 // int a7 __attribute__((weak));
1469 // This looks like a bug in gcc. We reject that for now. We should revisit
1470 // it if this behaviour is actually used.
1473 // static ((alias ("y"), weakref)).
1474 // Should we? How to check that weakref is before or after alias?
1476 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1477 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1478 // StringRef parameter it was given anyway.
1480 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1481 // GCC will accept anything as the argument of weakref. Should we
1482 // check for an existing decl?
1483 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1484 Attr.getAttributeSpellingListIndex()));
1486 D->addAttr(::new (S.Context)
1487 WeakRefAttr(Attr.getRange(), S.Context,
1488 Attr.getAttributeSpellingListIndex()));
1491 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1493 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1496 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1497 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1501 // Aliases should be on declarations, not definitions.
1502 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1503 if (FD->isThisDeclarationADefinition()) {
1504 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
1508 const auto *VD = cast<VarDecl>(D);
1509 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1510 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
1515 // FIXME: check if target symbol exists in current file
1517 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1518 Attr.getAttributeSpellingListIndex()));
1521 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1522 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr))
1525 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1526 Attr.getAttributeSpellingListIndex()));
1529 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1530 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr))
1533 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1534 Attr.getAttributeSpellingListIndex()));
1537 static void handleTLSModelAttr(Sema &S, Decl *D,
1538 const AttributeList &Attr) {
1540 SourceLocation LiteralLoc;
1541 // Check that it is a string.
1542 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1545 // Check that the value.
1546 if (Model != "global-dynamic" && Model != "local-dynamic"
1547 && Model != "initial-exec" && Model != "local-exec") {
1548 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1552 D->addAttr(::new (S.Context)
1553 TLSModelAttr(Attr.getRange(), S.Context, Model,
1554 Attr.getAttributeSpellingListIndex()));
1557 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1558 QualType ResultType = getFunctionOrMethodResultType(D);
1559 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1560 D->addAttr(::new (S.Context) RestrictAttr(
1561 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1565 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1566 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1569 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1570 if (S.LangOpts.CPlusPlus) {
1571 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1572 << Attr.getName() << AttributeLangSupport::Cpp;
1576 D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context,
1577 Attr.getAttributeSpellingListIndex()));
1580 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1581 if (hasDeclarator(D)) return;
1583 if (S.CheckNoReturnAttr(attr)) return;
1585 if (!isa<ObjCMethodDecl>(D)) {
1586 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1587 << attr.getName() << ExpectedFunctionOrMethod;
1591 D->addAttr(::new (S.Context)
1592 NoReturnAttr(attr.getRange(), S.Context,
1593 attr.getAttributeSpellingListIndex()));
1596 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1597 if (!checkAttributeNumArgs(*this, attr, 0)) {
1605 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1606 const AttributeList &Attr) {
1608 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1609 // because 'analyzer_noreturn' does not impact the type.
1610 if (!isFunctionOrMethodOrBlock(D)) {
1611 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1612 if (!VD || (!VD->getType()->isBlockPointerType() &&
1613 !VD->getType()->isFunctionPointerType())) {
1614 S.Diag(Attr.getLoc(),
1615 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1616 : diag::warn_attribute_wrong_decl_type)
1617 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1622 D->addAttr(::new (S.Context)
1623 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1624 Attr.getAttributeSpellingListIndex()));
1627 // PS3 PPU-specific.
1628 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1630 Returning a Vector Class in Registers
1632 According to the PPU ABI specifications, a class with a single member of
1633 vector type is returned in memory when used as the return value of a function.
1634 This results in inefficient code when implementing vector classes. To return
1635 the value in a single vector register, add the vecreturn attribute to the
1636 class definition. This attribute is also applicable to struct types.
1642 __vector float xyzw;
1643 } __attribute__((vecreturn));
1645 Vector Add(Vector lhs, Vector rhs)
1648 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1649 return result; // This will be returned in a register
1652 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1653 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1657 RecordDecl *record = cast<RecordDecl>(D);
1660 if (!isa<CXXRecordDecl>(record)) {
1661 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1665 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1666 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1670 for (const auto *I : record->fields()) {
1671 if ((count == 1) || !I->getType()->isVectorType()) {
1672 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1678 D->addAttr(::new (S.Context)
1679 VecReturnAttr(Attr.getRange(), S.Context,
1680 Attr.getAttributeSpellingListIndex()));
1683 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1684 const AttributeList &Attr) {
1685 if (isa<ParmVarDecl>(D)) {
1686 // [[carries_dependency]] can only be applied to a parameter if it is a
1687 // parameter of a function declaration or lambda.
1688 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1689 S.Diag(Attr.getLoc(),
1690 diag::err_carries_dependency_param_not_function_decl);
1695 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1696 Attr.getRange(), S.Context,
1697 Attr.getAttributeSpellingListIndex()));
1700 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1701 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1702 if (VD->hasLocalStorage()) {
1703 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1706 } else if (!isFunctionOrMethod(D)) {
1707 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1708 << Attr.getName() << ExpectedVariableOrFunction;
1712 D->addAttr(::new (S.Context)
1713 UsedAttr(Attr.getRange(), S.Context,
1714 Attr.getAttributeSpellingListIndex()));
1717 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1718 uint32_t priority = ConstructorAttr::DefaultPriority;
1719 if (Attr.getNumArgs() &&
1720 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1723 D->addAttr(::new (S.Context)
1724 ConstructorAttr(Attr.getRange(), S.Context, priority,
1725 Attr.getAttributeSpellingListIndex()));
1728 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1729 uint32_t priority = DestructorAttr::DefaultPriority;
1730 if (Attr.getNumArgs() &&
1731 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1734 D->addAttr(::new (S.Context)
1735 DestructorAttr(Attr.getRange(), S.Context, priority,
1736 Attr.getAttributeSpellingListIndex()));
1739 template <typename AttrTy>
1740 static void handleAttrWithMessage(Sema &S, Decl *D,
1741 const AttributeList &Attr) {
1742 // Handle the case where the attribute has a text message.
1744 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1747 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1748 Attr.getAttributeSpellingListIndex()));
1751 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1752 const AttributeList &Attr) {
1753 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1754 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1755 << Attr.getName() << Attr.getRange();
1759 D->addAttr(::new (S.Context)
1760 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1761 Attr.getAttributeSpellingListIndex()));
1764 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1765 IdentifierInfo *Platform,
1766 VersionTuple Introduced,
1767 VersionTuple Deprecated,
1768 VersionTuple Obsoleted) {
1769 StringRef PlatformName
1770 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1771 if (PlatformName.empty())
1772 PlatformName = Platform->getName();
1774 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1775 // of these steps are needed).
1776 if (!Introduced.empty() && !Deprecated.empty() &&
1777 !(Introduced <= Deprecated)) {
1778 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1779 << 1 << PlatformName << Deprecated.getAsString()
1780 << 0 << Introduced.getAsString();
1784 if (!Introduced.empty() && !Obsoleted.empty() &&
1785 !(Introduced <= Obsoleted)) {
1786 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1787 << 2 << PlatformName << Obsoleted.getAsString()
1788 << 0 << Introduced.getAsString();
1792 if (!Deprecated.empty() && !Obsoleted.empty() &&
1793 !(Deprecated <= Obsoleted)) {
1794 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1795 << 2 << PlatformName << Obsoleted.getAsString()
1796 << 1 << Deprecated.getAsString();
1803 /// \brief Check whether the two versions match.
1805 /// If either version tuple is empty, then they are assumed to match. If
1806 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1807 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1808 bool BeforeIsOkay) {
1809 if (X.empty() || Y.empty())
1815 if (BeforeIsOkay && X < Y)
1821 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1822 IdentifierInfo *Platform,
1823 VersionTuple Introduced,
1824 VersionTuple Deprecated,
1825 VersionTuple Obsoleted,
1829 unsigned AttrSpellingListIndex) {
1830 VersionTuple MergedIntroduced = Introduced;
1831 VersionTuple MergedDeprecated = Deprecated;
1832 VersionTuple MergedObsoleted = Obsoleted;
1833 bool FoundAny = false;
1835 if (D->hasAttrs()) {
1836 AttrVec &Attrs = D->getAttrs();
1837 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1838 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1844 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1845 if (OldPlatform != Platform) {
1851 VersionTuple OldIntroduced = OldAA->getIntroduced();
1852 VersionTuple OldDeprecated = OldAA->getDeprecated();
1853 VersionTuple OldObsoleted = OldAA->getObsoleted();
1854 bool OldIsUnavailable = OldAA->getUnavailable();
1856 if (!versionsMatch(OldIntroduced, Introduced, Override) ||
1857 !versionsMatch(Deprecated, OldDeprecated, Override) ||
1858 !versionsMatch(Obsoleted, OldObsoleted, Override) ||
1859 !(OldIsUnavailable == IsUnavailable ||
1860 (Override && !OldIsUnavailable && IsUnavailable))) {
1863 VersionTuple FirstVersion;
1864 VersionTuple SecondVersion;
1865 if (!versionsMatch(OldIntroduced, Introduced, Override)) {
1867 FirstVersion = OldIntroduced;
1868 SecondVersion = Introduced;
1869 } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
1871 FirstVersion = Deprecated;
1872 SecondVersion = OldDeprecated;
1873 } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
1875 FirstVersion = Obsoleted;
1876 SecondVersion = OldObsoleted;
1880 Diag(OldAA->getLocation(),
1881 diag::warn_mismatched_availability_override_unavail)
1882 << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1884 Diag(OldAA->getLocation(),
1885 diag::warn_mismatched_availability_override)
1887 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1888 << FirstVersion.getAsString() << SecondVersion.getAsString();
1890 Diag(Range.getBegin(), diag::note_overridden_method);
1892 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
1893 Diag(Range.getBegin(), diag::note_previous_attribute);
1896 Attrs.erase(Attrs.begin() + i);
1901 VersionTuple MergedIntroduced2 = MergedIntroduced;
1902 VersionTuple MergedDeprecated2 = MergedDeprecated;
1903 VersionTuple MergedObsoleted2 = MergedObsoleted;
1905 if (MergedIntroduced2.empty())
1906 MergedIntroduced2 = OldIntroduced;
1907 if (MergedDeprecated2.empty())
1908 MergedDeprecated2 = OldDeprecated;
1909 if (MergedObsoleted2.empty())
1910 MergedObsoleted2 = OldObsoleted;
1912 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
1913 MergedIntroduced2, MergedDeprecated2,
1914 MergedObsoleted2)) {
1915 Attrs.erase(Attrs.begin() + i);
1920 MergedIntroduced = MergedIntroduced2;
1921 MergedDeprecated = MergedDeprecated2;
1922 MergedObsoleted = MergedObsoleted2;
1928 MergedIntroduced == Introduced &&
1929 MergedDeprecated == Deprecated &&
1930 MergedObsoleted == Obsoleted)
1933 // Only create a new attribute if !Override, but we want to do
1935 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
1936 MergedDeprecated, MergedObsoleted) &&
1938 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
1939 Introduced, Deprecated,
1940 Obsoleted, IsUnavailable, Message,
1941 AttrSpellingListIndex);
1946 static void handleAvailabilityAttr(Sema &S, Decl *D,
1947 const AttributeList &Attr) {
1948 if (!checkAttributeNumArgs(S, Attr, 1))
1950 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
1951 unsigned Index = Attr.getAttributeSpellingListIndex();
1953 IdentifierInfo *II = Platform->Ident;
1954 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
1955 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
1958 NamedDecl *ND = dyn_cast<NamedDecl>(D);
1960 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1964 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1965 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1966 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1967 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1969 if (const StringLiteral *SE =
1970 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
1971 Str = SE->getString();
1973 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
1981 D->addAttr(NewAttr);
1985 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
1986 typename T::VisibilityType value,
1987 unsigned attrSpellingListIndex) {
1988 T *existingAttr = D->getAttr<T>();
1990 typename T::VisibilityType existingValue = existingAttr->getVisibility();
1991 if (existingValue == value)
1993 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
1994 S.Diag(range.getBegin(), diag::note_previous_attribute);
1997 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2000 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2001 VisibilityAttr::VisibilityType Vis,
2002 unsigned AttrSpellingListIndex) {
2003 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2004 AttrSpellingListIndex);
2007 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2008 TypeVisibilityAttr::VisibilityType Vis,
2009 unsigned AttrSpellingListIndex) {
2010 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2011 AttrSpellingListIndex);
2014 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2015 bool isTypeVisibility) {
2016 // Visibility attributes don't mean anything on a typedef.
2017 if (isa<TypedefNameDecl>(D)) {
2018 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2023 // 'type_visibility' can only go on a type or namespace.
2024 if (isTypeVisibility &&
2025 !(isa<TagDecl>(D) ||
2026 isa<ObjCInterfaceDecl>(D) ||
2027 isa<NamespaceDecl>(D))) {
2028 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2029 << Attr.getName() << ExpectedTypeOrNamespace;
2033 // Check that the argument is a string literal.
2035 SourceLocation LiteralLoc;
2036 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2039 VisibilityAttr::VisibilityType type;
2040 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2041 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2042 << Attr.getName() << TypeStr;
2046 // Complain about attempts to use protected visibility on targets
2047 // (like Darwin) that don't support it.
2048 if (type == VisibilityAttr::Protected &&
2049 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2050 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2051 type = VisibilityAttr::Default;
2054 unsigned Index = Attr.getAttributeSpellingListIndex();
2055 clang::Attr *newAttr;
2056 if (isTypeVisibility) {
2057 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2058 (TypeVisibilityAttr::VisibilityType) type,
2061 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2064 D->addAttr(newAttr);
2067 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2068 const AttributeList &Attr) {
2069 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2070 if (!Attr.isArgIdent(0)) {
2071 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2072 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2076 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2077 ObjCMethodFamilyAttr::FamilyKind F;
2078 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2079 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2084 if (F == ObjCMethodFamilyAttr::OMF_init &&
2085 !method->getReturnType()->isObjCObjectPointerType()) {
2086 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2087 << method->getReturnType();
2088 // Ignore the attribute.
2092 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2094 Attr.getAttributeSpellingListIndex()));
2097 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2098 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2099 QualType T = TD->getUnderlyingType();
2100 if (!T->isCARCBridgableType()) {
2101 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2105 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2106 QualType T = PD->getType();
2107 if (!T->isCARCBridgableType()) {
2108 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2113 // It is okay to include this attribute on properties, e.g.:
2115 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2117 // In this case it follows tradition and suppresses an error in the above
2119 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2121 D->addAttr(::new (S.Context)
2122 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2123 Attr.getAttributeSpellingListIndex()));
2126 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2127 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2128 QualType T = TD->getUnderlyingType();
2129 if (!T->isObjCObjectPointerType()) {
2130 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2134 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2137 D->addAttr(::new (S.Context)
2138 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2139 Attr.getAttributeSpellingListIndex()));
2142 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2143 if (!Attr.isArgIdent(0)) {
2144 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2145 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2149 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2150 BlocksAttr::BlockType type;
2151 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2152 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2153 << Attr.getName() << II;
2157 D->addAttr(::new (S.Context)
2158 BlocksAttr(Attr.getRange(), S.Context, type,
2159 Attr.getAttributeSpellingListIndex()));
2162 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2163 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2164 if (Attr.getNumArgs() > 0) {
2165 Expr *E = Attr.getArgAsExpr(0);
2166 llvm::APSInt Idx(32);
2167 if (E->isTypeDependent() || E->isValueDependent() ||
2168 !E->isIntegerConstantExpr(Idx, S.Context)) {
2169 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2170 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2171 << E->getSourceRange();
2175 if (Idx.isSigned() && Idx.isNegative()) {
2176 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2177 << E->getSourceRange();
2181 sentinel = Idx.getZExtValue();
2184 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2185 if (Attr.getNumArgs() > 1) {
2186 Expr *E = Attr.getArgAsExpr(1);
2187 llvm::APSInt Idx(32);
2188 if (E->isTypeDependent() || E->isValueDependent() ||
2189 !E->isIntegerConstantExpr(Idx, S.Context)) {
2190 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2191 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2192 << E->getSourceRange();
2195 nullPos = Idx.getZExtValue();
2197 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2198 // FIXME: This error message could be improved, it would be nice
2199 // to say what the bounds actually are.
2200 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2201 << E->getSourceRange();
2206 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2207 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2208 if (isa<FunctionNoProtoType>(FT)) {
2209 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2213 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2214 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2217 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2218 if (!MD->isVariadic()) {
2219 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2222 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2223 if (!BD->isVariadic()) {
2224 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2227 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2228 QualType Ty = V->getType();
2229 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2230 const FunctionType *FT = Ty->isFunctionPointerType()
2231 ? D->getFunctionType()
2232 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2233 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2234 int m = Ty->isFunctionPointerType() ? 0 : 1;
2235 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2239 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2240 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2244 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2245 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2248 D->addAttr(::new (S.Context)
2249 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2250 Attr.getAttributeSpellingListIndex()));
2253 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2254 if (D->getFunctionType() &&
2255 D->getFunctionType()->getReturnType()->isVoidType()) {
2256 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2257 << Attr.getName() << 0;
2260 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2261 if (MD->getReturnType()->isVoidType()) {
2262 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2263 << Attr.getName() << 1;
2267 D->addAttr(::new (S.Context)
2268 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2269 Attr.getAttributeSpellingListIndex()));
2272 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2273 // weak_import only applies to variable & function declarations.
2275 if (!D->canBeWeakImported(isDef)) {
2277 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2279 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2280 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2281 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2282 // Nothing to warn about here.
2284 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2285 << Attr.getName() << ExpectedVariableOrFunction;
2290 D->addAttr(::new (S.Context)
2291 WeakImportAttr(Attr.getRange(), S.Context,
2292 Attr.getAttributeSpellingListIndex()));
2295 // Handles reqd_work_group_size and work_group_size_hint.
2296 template <typename WorkGroupAttr>
2297 static void handleWorkGroupSize(Sema &S, Decl *D,
2298 const AttributeList &Attr) {
2300 for (unsigned i = 0; i < 3; ++i) {
2301 const Expr *E = Attr.getArgAsExpr(i);
2302 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2304 if (WGSize[i] == 0) {
2305 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2306 << Attr.getName() << E->getSourceRange();
2311 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2312 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2313 Existing->getYDim() == WGSize[1] &&
2314 Existing->getZDim() == WGSize[2]))
2315 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2317 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2318 WGSize[0], WGSize[1], WGSize[2],
2319 Attr.getAttributeSpellingListIndex()));
2322 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2323 if (!Attr.hasParsedType()) {
2324 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2325 << Attr.getName() << 1;
2329 TypeSourceInfo *ParmTSI = nullptr;
2330 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2331 assert(ParmTSI && "no type source info for attribute argument");
2333 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2334 (ParmType->isBooleanType() ||
2335 !ParmType->isIntegralType(S.getASTContext()))) {
2336 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2341 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2342 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2343 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2348 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2350 Attr.getAttributeSpellingListIndex()));
2353 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2355 unsigned AttrSpellingListIndex) {
2356 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2357 if (ExistingAttr->getName() == Name)
2359 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2360 Diag(Range.getBegin(), diag::note_previous_attribute);
2363 return ::new (Context) SectionAttr(Range, Context, Name,
2364 AttrSpellingListIndex);
2367 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2368 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2369 if (!Error.empty()) {
2370 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2376 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2377 // Make sure that there is a string literal as the sections's single
2380 SourceLocation LiteralLoc;
2381 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2384 if (!S.checkSectionName(LiteralLoc, Str))
2387 // If the target wants to validate the section specifier, make it happen.
2388 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2389 if (!Error.empty()) {
2390 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2395 unsigned Index = Attr.getAttributeSpellingListIndex();
2396 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2398 D->addAttr(NewAttr);
2401 // Check for things we'd like to warn about, no errors or validation for now.
2402 // TODO: Validation should use a backend target library that specifies
2403 // the allowable subtarget features and cpus. We could use something like a
2404 // TargetCodeGenInfo hook here to do validation.
2405 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2406 for (auto Str : {"tune=", "fpmath="})
2407 if (AttrStr.find(Str) != StringRef::npos)
2408 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2411 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2413 SourceLocation LiteralLoc;
2414 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2416 S.checkTargetAttr(LiteralLoc, Str);
2417 unsigned Index = Attr.getAttributeSpellingListIndex();
2418 TargetAttr *NewAttr =
2419 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2420 D->addAttr(NewAttr);
2424 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2425 VarDecl *VD = cast<VarDecl>(D);
2426 if (!VD->hasLocalStorage()) {
2427 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2431 Expr *E = Attr.getArgAsExpr(0);
2432 SourceLocation Loc = E->getExprLoc();
2433 FunctionDecl *FD = nullptr;
2434 DeclarationNameInfo NI;
2436 // gcc only allows for simple identifiers. Since we support more than gcc, we
2437 // will warn the user.
2438 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2439 if (DRE->hasQualifier())
2440 S.Diag(Loc, diag::warn_cleanup_ext);
2441 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2442 NI = DRE->getNameInfo();
2444 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2448 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2449 if (ULE->hasExplicitTemplateArgs())
2450 S.Diag(Loc, diag::warn_cleanup_ext);
2451 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2452 NI = ULE->getNameInfo();
2454 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2456 if (ULE->getType() == S.Context.OverloadTy)
2457 S.NoteAllOverloadCandidates(ULE);
2461 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2465 if (FD->getNumParams() != 1) {
2466 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2471 // We're currently more strict than GCC about what function types we accept.
2472 // If this ever proves to be a problem it should be easy to fix.
2473 QualType Ty = S.Context.getPointerType(VD->getType());
2474 QualType ParamTy = FD->getParamDecl(0)->getType();
2475 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2476 ParamTy, Ty) != Sema::Compatible) {
2477 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2478 << NI.getName() << ParamTy << Ty;
2482 D->addAttr(::new (S.Context)
2483 CleanupAttr(Attr.getRange(), S.Context, FD,
2484 Attr.getAttributeSpellingListIndex()));
2487 /// Handle __attribute__((format_arg((idx)))) attribute based on
2488 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2489 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2490 Expr *IdxExpr = Attr.getArgAsExpr(0);
2492 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2495 // make sure the format string is really a string
2496 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2498 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2499 if (not_nsstring_type &&
2500 !isCFStringType(Ty, S.Context) &&
2501 (!Ty->isPointerType() ||
2502 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2503 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2504 << (not_nsstring_type ? "a string type" : "an NSString")
2505 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2508 Ty = getFunctionOrMethodResultType(D);
2509 if (!isNSStringType(Ty, S.Context) &&
2510 !isCFStringType(Ty, S.Context) &&
2511 (!Ty->isPointerType() ||
2512 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2513 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2514 << (not_nsstring_type ? "string type" : "NSString")
2515 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2519 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2520 // because that has corrected for the implicit this parameter, and is zero-
2521 // based. The attribute expects what the user wrote explicitly.
2523 IdxExpr->EvaluateAsInt(Val, S.Context);
2525 D->addAttr(::new (S.Context)
2526 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2527 Attr.getAttributeSpellingListIndex()));
2530 enum FormatAttrKind {
2539 /// getFormatAttrKind - Map from format attribute names to supported format
2541 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2542 return llvm::StringSwitch<FormatAttrKind>(Format)
2543 // Check for formats that get handled specially.
2544 .Case("NSString", NSStringFormat)
2545 .Case("CFString", CFStringFormat)
2546 .Case("strftime", StrftimeFormat)
2548 // Otherwise, check for supported formats.
2549 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2550 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2551 .Case("kprintf", SupportedFormat) // OpenBSD.
2552 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2553 .Case("os_trace", SupportedFormat)
2555 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2556 .Default(InvalidFormat);
2559 /// Handle __attribute__((init_priority(priority))) attributes based on
2560 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2561 static void handleInitPriorityAttr(Sema &S, Decl *D,
2562 const AttributeList &Attr) {
2563 if (!S.getLangOpts().CPlusPlus) {
2564 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2568 if (S.getCurFunctionOrMethodDecl()) {
2569 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2573 QualType T = cast<VarDecl>(D)->getType();
2574 if (S.Context.getAsArrayType(T))
2575 T = S.Context.getBaseElementType(T);
2576 if (!T->getAs<RecordType>()) {
2577 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2582 Expr *E = Attr.getArgAsExpr(0);
2583 uint32_t prioritynum;
2584 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2589 if (prioritynum < 101 || prioritynum > 65535) {
2590 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2591 << E->getSourceRange();
2595 D->addAttr(::new (S.Context)
2596 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2597 Attr.getAttributeSpellingListIndex()));
2600 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2601 IdentifierInfo *Format, int FormatIdx,
2603 unsigned AttrSpellingListIndex) {
2604 // Check whether we already have an equivalent format attribute.
2605 for (auto *F : D->specific_attrs<FormatAttr>()) {
2606 if (F->getType() == Format &&
2607 F->getFormatIdx() == FormatIdx &&
2608 F->getFirstArg() == FirstArg) {
2609 // If we don't have a valid location for this attribute, adopt the
2611 if (F->getLocation().isInvalid())
2617 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2618 FirstArg, AttrSpellingListIndex);
2621 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2622 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2623 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2624 if (!Attr.isArgIdent(0)) {
2625 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2626 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2630 // In C++ the implicit 'this' function parameter also counts, and they are
2631 // counted from one.
2632 bool HasImplicitThisParam = isInstanceMethod(D);
2633 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2635 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2636 StringRef Format = II->getName();
2638 // Normalize the argument, __foo__ becomes foo.
2639 if (Format.startswith("__") && Format.endswith("__")) {
2640 Format = Format.substr(2, Format.size() - 4);
2641 // If we've modified the string name, we need a new identifier for it.
2642 II = &S.Context.Idents.get(Format);
2645 // Check for supported formats.
2646 FormatAttrKind Kind = getFormatAttrKind(Format);
2648 if (Kind == IgnoredFormat)
2651 if (Kind == InvalidFormat) {
2652 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2653 << Attr.getName() << II->getName();
2657 // checks for the 2nd argument
2658 Expr *IdxExpr = Attr.getArgAsExpr(1);
2660 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2663 if (Idx < 1 || Idx > NumArgs) {
2664 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2665 << Attr.getName() << 2 << IdxExpr->getSourceRange();
2669 // FIXME: Do we need to bounds check?
2670 unsigned ArgIdx = Idx - 1;
2672 if (HasImplicitThisParam) {
2674 S.Diag(Attr.getLoc(),
2675 diag::err_format_attribute_implicit_this_format_string)
2676 << IdxExpr->getSourceRange();
2682 // make sure the format string is really a string
2683 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2685 if (Kind == CFStringFormat) {
2686 if (!isCFStringType(Ty, S.Context)) {
2687 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2688 << "a CFString" << IdxExpr->getSourceRange()
2689 << getFunctionOrMethodParamRange(D, ArgIdx);
2692 } else if (Kind == NSStringFormat) {
2693 // FIXME: do we need to check if the type is NSString*? What are the
2695 if (!isNSStringType(Ty, S.Context)) {
2696 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2697 << "an NSString" << IdxExpr->getSourceRange()
2698 << getFunctionOrMethodParamRange(D, ArgIdx);
2701 } else if (!Ty->isPointerType() ||
2702 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2703 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2704 << "a string type" << IdxExpr->getSourceRange()
2705 << getFunctionOrMethodParamRange(D, ArgIdx);
2709 // check the 3rd argument
2710 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2712 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2715 // check if the function is variadic if the 3rd argument non-zero
2716 if (FirstArg != 0) {
2717 if (isFunctionOrMethodVariadic(D)) {
2718 ++NumArgs; // +1 for ...
2720 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2725 // strftime requires FirstArg to be 0 because it doesn't read from any
2726 // variable the input is just the current time + the format string.
2727 if (Kind == StrftimeFormat) {
2728 if (FirstArg != 0) {
2729 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2730 << FirstArgExpr->getSourceRange();
2733 // if 0 it disables parameter checking (to use with e.g. va_list)
2734 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2735 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2736 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2740 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2742 Attr.getAttributeSpellingListIndex());
2744 D->addAttr(NewAttr);
2747 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2748 const AttributeList &Attr) {
2749 // Try to find the underlying union declaration.
2750 RecordDecl *RD = nullptr;
2751 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2752 if (TD && TD->getUnderlyingType()->isUnionType())
2753 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2755 RD = dyn_cast<RecordDecl>(D);
2757 if (!RD || !RD->isUnion()) {
2758 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2759 << Attr.getName() << ExpectedUnion;
2763 if (!RD->isCompleteDefinition()) {
2764 S.Diag(Attr.getLoc(),
2765 diag::warn_transparent_union_attribute_not_definition);
2769 RecordDecl::field_iterator Field = RD->field_begin(),
2770 FieldEnd = RD->field_end();
2771 if (Field == FieldEnd) {
2772 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2776 FieldDecl *FirstField = *Field;
2777 QualType FirstType = FirstField->getType();
2778 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2779 S.Diag(FirstField->getLocation(),
2780 diag::warn_transparent_union_attribute_floating)
2781 << FirstType->isVectorType() << FirstType;
2785 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2786 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2787 for (; Field != FieldEnd; ++Field) {
2788 QualType FieldType = Field->getType();
2789 // FIXME: this isn't fully correct; we also need to test whether the
2790 // members of the union would all have the same calling convention as the
2791 // first member of the union. Checking just the size and alignment isn't
2792 // sufficient (consider structs passed on the stack instead of in registers
2794 if (S.Context.getTypeSize(FieldType) != FirstSize ||
2795 S.Context.getTypeAlign(FieldType) > FirstAlign) {
2796 // Warn if we drop the attribute.
2797 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2798 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2799 : S.Context.getTypeAlign(FieldType);
2800 S.Diag(Field->getLocation(),
2801 diag::warn_transparent_union_attribute_field_size_align)
2802 << isSize << Field->getDeclName() << FieldBits;
2803 unsigned FirstBits = isSize? FirstSize : FirstAlign;
2804 S.Diag(FirstField->getLocation(),
2805 diag::note_transparent_union_first_field_size_align)
2806 << isSize << FirstBits;
2811 RD->addAttr(::new (S.Context)
2812 TransparentUnionAttr(Attr.getRange(), S.Context,
2813 Attr.getAttributeSpellingListIndex()));
2816 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2817 // Make sure that there is a string literal as the annotation's single
2820 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2823 // Don't duplicate annotations that are already set.
2824 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2825 if (I->getAnnotation() == Str)
2829 D->addAttr(::new (S.Context)
2830 AnnotateAttr(Attr.getRange(), S.Context, Str,
2831 Attr.getAttributeSpellingListIndex()));
2834 static void handleAlignValueAttr(Sema &S, Decl *D,
2835 const AttributeList &Attr) {
2836 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
2837 Attr.getAttributeSpellingListIndex());
2840 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
2841 unsigned SpellingListIndex) {
2842 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
2843 SourceLocation AttrLoc = AttrRange.getBegin();
2846 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2847 T = TD->getUnderlyingType();
2848 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2851 llvm_unreachable("Unknown decl type for align_value");
2853 if (!T->isDependentType() && !T->isAnyPointerType() &&
2854 !T->isReferenceType() && !T->isMemberPointerType()) {
2855 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
2856 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
2860 if (!E->isValueDependent()) {
2861 llvm::APSInt Alignment(32);
2863 = VerifyIntegerConstantExpression(E, &Alignment,
2864 diag::err_align_value_attribute_argument_not_int,
2865 /*AllowFold*/ false);
2866 if (ICE.isInvalid())
2869 if (!Alignment.isPowerOf2()) {
2870 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2871 << E->getSourceRange();
2875 D->addAttr(::new (Context)
2876 AlignValueAttr(AttrRange, Context, ICE.get(),
2877 SpellingListIndex));
2881 // Save dependent expressions in the AST to be instantiated.
2882 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
2886 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2887 // check the attribute arguments.
2888 if (Attr.getNumArgs() > 1) {
2889 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2890 << Attr.getName() << 1;
2894 if (Attr.getNumArgs() == 0) {
2895 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
2896 true, nullptr, Attr.getAttributeSpellingListIndex()));
2900 Expr *E = Attr.getArgAsExpr(0);
2901 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
2902 S.Diag(Attr.getEllipsisLoc(),
2903 diag::err_pack_expansion_without_parameter_packs);
2907 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
2910 if (E->isValueDependent()) {
2911 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
2912 if (!TND->getUnderlyingType()->isDependentType()) {
2913 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
2914 << E->getSourceRange();
2920 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
2921 Attr.isPackExpansion());
2924 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
2925 unsigned SpellingListIndex, bool IsPackExpansion) {
2926 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
2927 SourceLocation AttrLoc = AttrRange.getBegin();
2929 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
2930 if (TmpAttr.isAlignas()) {
2931 // C++11 [dcl.align]p1:
2932 // An alignment-specifier may be applied to a variable or to a class
2933 // data member, but it shall not be applied to a bit-field, a function
2934 // parameter, the formal parameter of a catch clause, or a variable
2935 // declared with the register storage class specifier. An
2936 // alignment-specifier may also be applied to the declaration of a class
2937 // or enumeration type.
2939 // An alignment attribute shall not be specified in a declaration of
2940 // a typedef, or a bit-field, or a function, or a parameter, or an
2941 // object declared with the register storage-class specifier.
2943 if (isa<ParmVarDecl>(D)) {
2945 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2946 if (VD->getStorageClass() == SC_Register)
2948 if (VD->isExceptionVariable())
2950 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
2951 if (FD->isBitField())
2953 } else if (!isa<TagDecl>(D)) {
2954 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
2955 << (TmpAttr.isC11() ? ExpectedVariableOrField
2956 : ExpectedVariableFieldOrTag);
2959 if (DiagKind != -1) {
2960 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
2961 << &TmpAttr << DiagKind;
2966 if (E->isTypeDependent() || E->isValueDependent()) {
2967 // Save dependent expressions in the AST to be instantiated.
2968 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
2969 AA->setPackExpansion(IsPackExpansion);
2974 // FIXME: Cache the number on the Attr object?
2975 llvm::APSInt Alignment(32);
2977 = VerifyIntegerConstantExpression(E, &Alignment,
2978 diag::err_aligned_attribute_argument_not_int,
2979 /*AllowFold*/ false);
2980 if (ICE.isInvalid())
2983 // C++11 [dcl.align]p2:
2984 // -- if the constant expression evaluates to zero, the alignment
2985 // specifier shall have no effect
2987 // An alignment specification of zero has no effect.
2988 if (!(TmpAttr.isAlignas() && !Alignment) &&
2989 !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2990 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
2991 << E->getSourceRange();
2995 // Alignment calculations can wrap around if it's greater than 2**28.
2996 unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456;
2997 if (Alignment.getZExtValue() > MaxValidAlignment) {
2998 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
2999 << E->getSourceRange();
3003 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3004 ICE.get(), SpellingListIndex);
3005 AA->setPackExpansion(IsPackExpansion);
3009 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3010 unsigned SpellingListIndex, bool IsPackExpansion) {
3011 // FIXME: Cache the number on the Attr object if non-dependent?
3012 // FIXME: Perform checking of type validity
3013 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3015 AA->setPackExpansion(IsPackExpansion);
3019 void Sema::CheckAlignasUnderalignment(Decl *D) {
3020 assert(D->hasAttrs() && "no attributes on decl");
3022 QualType UnderlyingTy, DiagTy;
3023 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3024 UnderlyingTy = DiagTy = VD->getType();
3026 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3027 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3028 UnderlyingTy = ED->getIntegerType();
3030 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3033 // C++11 [dcl.align]p5, C11 6.7.5/4:
3034 // The combined effect of all alignment attributes in a declaration shall
3035 // not specify an alignment that is less strict than the alignment that
3036 // would otherwise be required for the entity being declared.
3037 AlignedAttr *AlignasAttr = nullptr;
3039 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3040 if (I->isAlignmentDependent())
3044 Align = std::max(Align, I->getAlignment(Context));
3047 if (AlignasAttr && Align) {
3048 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3049 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3050 if (NaturalAlign > RequestedAlign)
3051 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3052 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3056 bool Sema::checkMSInheritanceAttrOnDefinition(
3057 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3058 MSInheritanceAttr::Spelling SemanticSpelling) {
3059 assert(RD->hasDefinition() && "RD has no definition!");
3061 // We may not have seen base specifiers or any virtual methods yet. We will
3062 // have to wait until the record is defined to catch any mismatches.
3063 if (!RD->getDefinition()->isCompleteDefinition())
3066 // The unspecified model never matches what a definition could need.
3067 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3071 if (RD->calculateInheritanceModel() == SemanticSpelling)
3074 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3078 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3079 << 0 /*definition*/;
3080 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3081 << RD->getNameAsString();
3085 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3088 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3089 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3090 /// HImode, not an intermediate pointer.
3091 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3092 // This attribute isn't documented, but glibc uses it. It changes
3093 // the width of an int or unsigned int to the specified size.
3094 if (!Attr.isArgIdent(0)) {
3095 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3096 << AANT_ArgumentIdentifier;
3100 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3101 StringRef Str = Name->getName();
3103 // Normalize the attribute name, __foo__ becomes foo.
3104 if (Str.startswith("__") && Str.endswith("__"))
3105 Str = Str.substr(2, Str.size() - 4);
3107 unsigned DestWidth = 0;
3108 bool IntegerMode = true;
3109 bool ComplexMode = false;
3110 switch (Str.size()) {
3113 case 'Q': DestWidth = 8; break;
3114 case 'H': DestWidth = 16; break;
3115 case 'S': DestWidth = 32; break;
3116 case 'D': DestWidth = 64; break;
3117 case 'X': DestWidth = 96; break;
3118 case 'T': DestWidth = 128; break;
3120 if (Str[1] == 'F') {
3121 IntegerMode = false;
3122 } else if (Str[1] == 'C') {
3123 IntegerMode = false;
3125 } else if (Str[1] != 'I') {
3130 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3131 // pointer on PIC16 and other embedded platforms.
3133 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3134 else if (Str == "byte")
3135 DestWidth = S.Context.getTargetInfo().getCharWidth();
3138 if (Str == "pointer")
3139 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3142 if (Str == "unwind_word")
3143 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3148 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3149 OldTy = TD->getUnderlyingType();
3150 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3151 OldTy = VD->getType();
3153 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3154 << Attr.getName() << Attr.getRange();
3158 // Base type can also be a vector type (see PR17453).
3159 // Distinguish between base type and base element type.
3160 QualType OldElemTy = OldTy;
3161 if (const VectorType *VT = OldTy->getAs<VectorType>())
3162 OldElemTy = VT->getElementType();
3164 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType())
3165 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3166 else if (IntegerMode) {
3167 if (!OldElemTy->isIntegralOrEnumerationType())
3168 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3169 } else if (ComplexMode) {
3170 if (!OldElemTy->isComplexType())
3171 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3173 if (!OldElemTy->isFloatingType())
3174 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3177 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3178 // and friends, at least with glibc.
3179 // FIXME: Make sure floating-point mappings are accurate
3180 // FIXME: Support XF and TF types
3182 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3189 NewElemTy = S.Context.getIntTypeForBitwidth(
3190 DestWidth, OldElemTy->isSignedIntegerType());
3192 NewElemTy = S.Context.getRealTypeForBitwidth(DestWidth);
3194 if (NewElemTy.isNull()) {
3195 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3200 NewElemTy = S.Context.getComplexType(NewElemTy);
3203 QualType NewTy = NewElemTy;
3204 if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3205 // Complex machine mode does not support base vector types.
3207 S.Diag(Attr.getLoc(), diag::err_complex_mode_vector_type);
3210 unsigned NumElements = S.Context.getTypeSize(OldElemTy) *
3211 OldVT->getNumElements() /
3212 S.Context.getTypeSize(NewElemTy);
3214 S.Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3217 if (NewTy.isNull()) {
3218 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3222 // Install the new type.
3223 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3224 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3226 cast<ValueDecl>(D)->setType(NewTy);
3228 D->addAttr(::new (S.Context)
3229 ModeAttr(Attr.getRange(), S.Context, Name,
3230 Attr.getAttributeSpellingListIndex()));
3233 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3234 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3235 if (!VD->hasGlobalStorage())
3236 S.Diag(Attr.getLoc(),
3237 diag::warn_attribute_requires_functions_or_static_globals)
3239 } else if (!isFunctionOrMethod(D)) {
3240 S.Diag(Attr.getLoc(),
3241 diag::warn_attribute_requires_functions_or_static_globals)
3246 D->addAttr(::new (S.Context)
3247 NoDebugAttr(Attr.getRange(), S.Context,
3248 Attr.getAttributeSpellingListIndex()));
3251 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3252 IdentifierInfo *Ident,
3253 unsigned AttrSpellingListIndex) {
3254 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3255 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3256 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3260 if (D->hasAttr<AlwaysInlineAttr>())
3263 return ::new (Context) AlwaysInlineAttr(Range, Context,
3264 AttrSpellingListIndex);
3267 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3268 unsigned AttrSpellingListIndex) {
3269 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3270 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3271 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3275 if (D->hasAttr<MinSizeAttr>())
3278 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3281 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3282 unsigned AttrSpellingListIndex) {
3283 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3284 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3285 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3286 D->dropAttr<AlwaysInlineAttr>();
3288 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3289 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3290 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3291 D->dropAttr<MinSizeAttr>();
3294 if (D->hasAttr<OptimizeNoneAttr>())
3297 return ::new (Context) OptimizeNoneAttr(Range, Context,
3298 AttrSpellingListIndex);
3301 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3302 const AttributeList &Attr) {
3303 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3304 D, Attr.getRange(), Attr.getName(),
3305 Attr.getAttributeSpellingListIndex()))
3309 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3310 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3311 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3312 D->addAttr(MinSize);
3315 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3316 const AttributeList &Attr) {
3317 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3318 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3319 D->addAttr(Optnone);
3322 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3323 FunctionDecl *FD = cast<FunctionDecl>(D);
3324 if (!FD->getReturnType()->isVoidType()) {
3325 SourceRange RTRange = FD->getReturnTypeSourceRange();
3326 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3328 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3333 D->addAttr(::new (S.Context)
3334 CUDAGlobalAttr(Attr.getRange(), S.Context,
3335 Attr.getAttributeSpellingListIndex()));
3338 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3339 FunctionDecl *Fn = cast<FunctionDecl>(D);
3340 if (!Fn->isInlineSpecified()) {
3341 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3345 D->addAttr(::new (S.Context)
3346 GNUInlineAttr(Attr.getRange(), S.Context,
3347 Attr.getAttributeSpellingListIndex()));
3350 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3351 if (hasDeclarator(D)) return;
3353 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3354 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3356 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
3359 if (!isa<ObjCMethodDecl>(D)) {
3360 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3361 << Attr.getName() << ExpectedFunctionOrMethod;
3365 switch (Attr.getKind()) {
3366 case AttributeList::AT_FastCall:
3367 D->addAttr(::new (S.Context)
3368 FastCallAttr(Attr.getRange(), S.Context,
3369 Attr.getAttributeSpellingListIndex()));
3371 case AttributeList::AT_StdCall:
3372 D->addAttr(::new (S.Context)
3373 StdCallAttr(Attr.getRange(), S.Context,
3374 Attr.getAttributeSpellingListIndex()));
3376 case AttributeList::AT_ThisCall:
3377 D->addAttr(::new (S.Context)
3378 ThisCallAttr(Attr.getRange(), S.Context,
3379 Attr.getAttributeSpellingListIndex()));
3381 case AttributeList::AT_CDecl:
3382 D->addAttr(::new (S.Context)
3383 CDeclAttr(Attr.getRange(), S.Context,
3384 Attr.getAttributeSpellingListIndex()));
3386 case AttributeList::AT_Pascal:
3387 D->addAttr(::new (S.Context)
3388 PascalAttr(Attr.getRange(), S.Context,
3389 Attr.getAttributeSpellingListIndex()));
3391 case AttributeList::AT_VectorCall:
3392 D->addAttr(::new (S.Context)
3393 VectorCallAttr(Attr.getRange(), S.Context,
3394 Attr.getAttributeSpellingListIndex()));
3396 case AttributeList::AT_MSABI:
3397 D->addAttr(::new (S.Context)
3398 MSABIAttr(Attr.getRange(), S.Context,
3399 Attr.getAttributeSpellingListIndex()));
3401 case AttributeList::AT_SysVABI:
3402 D->addAttr(::new (S.Context)
3403 SysVABIAttr(Attr.getRange(), S.Context,
3404 Attr.getAttributeSpellingListIndex()));
3406 case AttributeList::AT_Pcs: {
3407 PcsAttr::PCSType PCS;
3410 PCS = PcsAttr::AAPCS;
3413 PCS = PcsAttr::AAPCS_VFP;
3416 llvm_unreachable("unexpected calling convention in pcs attribute");
3419 D->addAttr(::new (S.Context)
3420 PcsAttr(Attr.getRange(), S.Context, PCS,
3421 Attr.getAttributeSpellingListIndex()));
3424 case AttributeList::AT_IntelOclBicc:
3425 D->addAttr(::new (S.Context)
3426 IntelOclBiccAttr(Attr.getRange(), S.Context,
3427 Attr.getAttributeSpellingListIndex()));
3431 llvm_unreachable("unexpected attribute kind");
3435 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3436 const FunctionDecl *FD) {
3437 if (attr.isInvalid())
3440 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3441 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3446 // TODO: diagnose uses of these conventions on the wrong target.
3447 switch (attr.getKind()) {
3448 case AttributeList::AT_CDecl: CC = CC_C; break;
3449 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3450 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3451 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3452 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3453 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3454 case AttributeList::AT_MSABI:
3455 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3458 case AttributeList::AT_SysVABI:
3459 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3462 case AttributeList::AT_Pcs: {
3464 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3468 if (StrRef == "aapcs") {
3471 } else if (StrRef == "aapcs-vfp") {
3477 Diag(attr.getLoc(), diag::err_invalid_pcs);
3480 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3481 default: llvm_unreachable("unexpected attribute kind");
3484 const TargetInfo &TI = Context.getTargetInfo();
3485 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3486 if (A != TargetInfo::CCCR_OK) {
3487 if (A == TargetInfo::CCCR_Warning)
3488 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3490 // This convention is not valid for the target. Use the default function or
3491 // method calling convention.
3492 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3494 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3495 TargetInfo::CCMT_NonMember;
3496 CC = TI.getDefaultCallingConv(MT);
3502 /// Checks a regparm attribute, returning true if it is ill-formed and
3503 /// otherwise setting numParams to the appropriate value.
3504 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3505 if (Attr.isInvalid())
3508 if (!checkAttributeNumArgs(*this, Attr, 1)) {
3514 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3515 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3520 if (Context.getTargetInfo().getRegParmMax() == 0) {
3521 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3522 << NumParamsExpr->getSourceRange();
3528 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3529 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3530 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3538 // Checks whether an argument of launch_bounds attribute is acceptable
3539 // May output an error.
3540 static bool checkLaunchBoundsArgument(Sema &S, Expr *E,
3541 const CUDALaunchBoundsAttr &Attr,
3542 const unsigned Idx) {
3544 if (S.DiagnoseUnexpandedParameterPack(E))
3547 // Accept template arguments for now as they depend on something else.
3548 // We'll get to check them when they eventually get instantiated.
3549 if (E->isValueDependent())
3553 if (!E->isIntegerConstantExpr(I, S.Context)) {
3554 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
3555 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
3558 // Make sure we can fit it in 32 bits.
3559 if (!I.isIntN(32)) {
3560 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
3561 << 32 << /* Unsigned */ 1;
3565 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
3566 << &Attr << Idx << E->getSourceRange();
3571 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
3572 Expr *MinBlocks, unsigned SpellingListIndex) {
3573 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
3576 if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0))
3579 if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1))
3582 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
3583 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
3586 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3587 const AttributeList &Attr) {
3588 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
3589 !checkAttributeAtMostNumArgs(S, Attr, 2))
3592 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3593 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
3594 Attr.getAttributeSpellingListIndex());
3597 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3598 const AttributeList &Attr) {
3599 if (!Attr.isArgIdent(0)) {
3600 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3601 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3605 if (!checkAttributeNumArgs(S, Attr, 3))
3608 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3610 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3611 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3612 << Attr.getName() << ExpectedFunctionOrMethod;
3616 uint64_t ArgumentIdx;
3617 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3621 uint64_t TypeTagIdx;
3622 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3626 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3628 // Ensure that buffer has a pointer type.
3629 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3630 if (!BufferTy->isPointerType()) {
3631 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3636 D->addAttr(::new (S.Context)
3637 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3638 ArgumentIdx, TypeTagIdx, IsPointer,
3639 Attr.getAttributeSpellingListIndex()));
3642 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3643 const AttributeList &Attr) {
3644 if (!Attr.isArgIdent(0)) {
3645 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3646 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3650 if (!checkAttributeNumArgs(S, Attr, 1))
3653 if (!isa<VarDecl>(D)) {
3654 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3655 << Attr.getName() << ExpectedVariable;
3659 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3660 TypeSourceInfo *MatchingCTypeLoc = nullptr;
3661 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3662 assert(MatchingCTypeLoc && "no type source info for attribute argument");
3664 D->addAttr(::new (S.Context)
3665 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3667 Attr.getLayoutCompatible(),
3668 Attr.getMustBeNull(),
3669 Attr.getAttributeSpellingListIndex()));
3672 //===----------------------------------------------------------------------===//
3673 // Checker-specific attribute handlers.
3674 //===----------------------------------------------------------------------===//
3676 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
3677 return type->isDependentType() ||
3678 type->isObjCRetainableType();
3681 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3682 return type->isDependentType() ||
3683 type->isObjCObjectPointerType() ||
3684 S.Context.isObjCNSObjectType(type);
3686 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3687 return type->isDependentType() ||
3688 type->isPointerType() ||
3689 isValidSubjectOfNSAttribute(S, type);
3692 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3693 ParmVarDecl *param = cast<ParmVarDecl>(D);
3696 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3697 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3700 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3705 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3706 << Attr.getRange() << Attr.getName() << cf;
3711 param->addAttr(::new (S.Context)
3712 CFConsumedAttr(Attr.getRange(), S.Context,
3713 Attr.getAttributeSpellingListIndex()));
3715 param->addAttr(::new (S.Context)
3716 NSConsumedAttr(Attr.getRange(), S.Context,
3717 Attr.getAttributeSpellingListIndex()));
3720 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3721 const AttributeList &Attr) {
3723 QualType returnType;
3725 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3726 returnType = MD->getReturnType();
3727 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3728 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3729 return; // ignore: was handled as a type attribute
3730 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
3731 returnType = PD->getType();
3732 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
3733 returnType = FD->getReturnType();
3734 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
3735 returnType = Param->getType()->getPointeeType();
3736 if (returnType.isNull()) {
3737 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3738 << Attr.getName() << /*pointer-to-CF*/2
3743 AttributeDeclKind ExpectedDeclKind;
3744 switch (Attr.getKind()) {
3745 default: llvm_unreachable("invalid ownership attribute");
3746 case AttributeList::AT_NSReturnsRetained:
3747 case AttributeList::AT_NSReturnsAutoreleased:
3748 case AttributeList::AT_NSReturnsNotRetained:
3749 ExpectedDeclKind = ExpectedFunctionOrMethod;
3752 case AttributeList::AT_CFReturnsRetained:
3753 case AttributeList::AT_CFReturnsNotRetained:
3754 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
3757 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
3758 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
3764 switch (Attr.getKind()) {
3765 default: llvm_unreachable("invalid ownership attribute");
3766 case AttributeList::AT_NSReturnsRetained:
3767 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
3771 case AttributeList::AT_NSReturnsAutoreleased:
3772 case AttributeList::AT_NSReturnsNotRetained:
3773 typeOK = isValidSubjectOfNSAttribute(S, returnType);
3777 case AttributeList::AT_CFReturnsRetained:
3778 case AttributeList::AT_CFReturnsNotRetained:
3779 typeOK = isValidSubjectOfCFAttribute(S, returnType);
3785 if (isa<ParmVarDecl>(D)) {
3786 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3787 << Attr.getName() << /*pointer-to-CF*/2
3790 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
3795 } SubjectKind = Function;
3796 if (isa<ObjCMethodDecl>(D))
3797 SubjectKind = Method;
3798 else if (isa<ObjCPropertyDecl>(D))
3799 SubjectKind = Property;
3800 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3801 << Attr.getName() << SubjectKind << cf
3807 switch (Attr.getKind()) {
3809 llvm_unreachable("invalid ownership attribute");
3810 case AttributeList::AT_NSReturnsAutoreleased:
3811 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
3812 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3814 case AttributeList::AT_CFReturnsNotRetained:
3815 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
3816 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3818 case AttributeList::AT_NSReturnsNotRetained:
3819 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
3820 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3822 case AttributeList::AT_CFReturnsRetained:
3823 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
3824 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3826 case AttributeList::AT_NSReturnsRetained:
3827 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
3828 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3833 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
3834 const AttributeList &attr) {
3835 const int EP_ObjCMethod = 1;
3836 const int EP_ObjCProperty = 2;
3838 SourceLocation loc = attr.getLoc();
3839 QualType resultType;
3840 if (isa<ObjCMethodDecl>(D))
3841 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
3843 resultType = cast<ObjCPropertyDecl>(D)->getType();
3845 if (!resultType->isReferenceType() &&
3846 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
3847 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
3850 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
3851 << /*non-retainable pointer*/ 2;
3853 // Drop the attribute.
3857 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
3858 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
3861 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
3862 const AttributeList &attr) {
3863 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
3865 DeclContext *DC = method->getDeclContext();
3866 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
3867 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3868 << attr.getName() << 0;
3869 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
3872 if (method->getMethodFamily() == OMF_dealloc) {
3873 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
3874 << attr.getName() << 1;
3878 method->addAttr(::new (S.Context)
3879 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
3880 attr.getAttributeSpellingListIndex()));
3883 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
3884 const AttributeList &Attr) {
3885 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr))
3888 D->addAttr(::new (S.Context)
3889 CFAuditedTransferAttr(Attr.getRange(), S.Context,
3890 Attr.getAttributeSpellingListIndex()));
3893 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
3894 const AttributeList &Attr) {
3895 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr))
3898 D->addAttr(::new (S.Context)
3899 CFUnknownTransferAttr(Attr.getRange(), S.Context,
3900 Attr.getAttributeSpellingListIndex()));
3903 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
3904 const AttributeList &Attr) {
3905 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3908 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3912 // Typedefs only allow objc_bridge(id) and have some additional checking.
3913 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
3914 if (!Parm->Ident->isStr("id")) {
3915 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
3920 // Only allow 'cv void *'.
3921 QualType T = TD->getUnderlyingType();
3922 if (!T->isVoidPointerType()) {
3923 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
3928 D->addAttr(::new (S.Context)
3929 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
3930 Attr.getAttributeSpellingListIndex()));
3933 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
3934 const AttributeList &Attr) {
3935 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
3938 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3942 D->addAttr(::new (S.Context)
3943 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
3944 Attr.getAttributeSpellingListIndex()));
3947 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
3948 const AttributeList &Attr) {
3949 IdentifierInfo *RelatedClass =
3950 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
3951 if (!RelatedClass) {
3952 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
3955 IdentifierInfo *ClassMethod =
3956 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
3957 IdentifierInfo *InstanceMethod =
3958 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
3959 D->addAttr(::new (S.Context)
3960 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
3961 ClassMethod, InstanceMethod,
3962 Attr.getAttributeSpellingListIndex()));
3965 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
3966 const AttributeList &Attr) {
3967 ObjCInterfaceDecl *IFace;
3968 if (ObjCCategoryDecl *CatDecl =
3969 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
3970 IFace = CatDecl->getClassInterface();
3972 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
3977 IFace->setHasDesignatedInitializers();
3978 D->addAttr(::new (S.Context)
3979 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
3980 Attr.getAttributeSpellingListIndex()));
3983 static void handleObjCRuntimeName(Sema &S, Decl *D,
3984 const AttributeList &Attr) {
3985 StringRef MetaDataName;
3986 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
3988 D->addAttr(::new (S.Context)
3989 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
3991 Attr.getAttributeSpellingListIndex()));
3994 // when a user wants to use objc_boxable with a union or struct
3995 // but she doesn't have access to the declaration (legacy/third-party code)
3996 // then she can 'enable' this feature via trick with a typedef
3998 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
3999 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4000 bool notify = false;
4002 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4003 if (RD && RD->getDefinition()) {
4004 RD = RD->getDefinition();
4009 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4010 ObjCBoxableAttr(Attr.getRange(), S.Context,
4011 Attr.getAttributeSpellingListIndex());
4012 RD->addAttr(BoxableAttr);
4014 // we need to notify ASTReader/ASTWriter about
4015 // modification of existing declaration
4016 if (ASTMutationListener *L = S.getASTMutationListener())
4017 L->AddedAttributeToRecord(BoxableAttr, RD);
4022 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4023 const AttributeList &Attr) {
4024 if (hasDeclarator(D)) return;
4026 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4027 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4030 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4031 const AttributeList &Attr) {
4032 ValueDecl *vd = cast<ValueDecl>(D);
4033 QualType type = vd->getType();
4035 if (!type->isDependentType() &&
4036 !type->isObjCLifetimeType()) {
4037 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4042 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4044 // If we have no lifetime yet, check the lifetime we're presumably
4046 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4047 lifetime = type->getObjCARCImplicitLifetime();
4050 case Qualifiers::OCL_None:
4051 assert(type->isDependentType() &&
4052 "didn't infer lifetime for non-dependent type?");
4055 case Qualifiers::OCL_Weak: // meaningful
4056 case Qualifiers::OCL_Strong: // meaningful
4059 case Qualifiers::OCL_ExplicitNone:
4060 case Qualifiers::OCL_Autoreleasing:
4061 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4062 << (lifetime == Qualifiers::OCL_Autoreleasing);
4066 D->addAttr(::new (S.Context)
4067 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4068 Attr.getAttributeSpellingListIndex()));
4071 //===----------------------------------------------------------------------===//
4072 // Microsoft specific attribute handlers.
4073 //===----------------------------------------------------------------------===//
4075 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4076 if (!S.LangOpts.CPlusPlus) {
4077 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4078 << Attr.getName() << AttributeLangSupport::C;
4082 if (!isa<CXXRecordDecl>(D)) {
4083 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4084 << Attr.getName() << ExpectedClass;
4089 SourceLocation LiteralLoc;
4090 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4093 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4094 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4095 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4096 StrRef = StrRef.drop_front().drop_back();
4098 // Validate GUID length.
4099 if (StrRef.size() != 36) {
4100 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4104 for (unsigned i = 0; i < 36; ++i) {
4105 if (i == 8 || i == 13 || i == 18 || i == 23) {
4106 if (StrRef[i] != '-') {
4107 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4110 } else if (!isHexDigit(StrRef[i])) {
4111 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4116 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4117 Attr.getAttributeSpellingListIndex()));
4120 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4121 if (!S.LangOpts.CPlusPlus) {
4122 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4123 << Attr.getName() << AttributeLangSupport::C;
4126 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
4127 D, Attr.getRange(), /*BestCase=*/true,
4128 Attr.getAttributeSpellingListIndex(),
4129 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
4134 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4135 const AttributeList &Attr) {
4136 VarDecl *VD = cast<VarDecl>(D);
4137 if (!S.Context.getTargetInfo().isTLSSupported()) {
4138 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4141 if (VD->getTSCSpec() != TSCS_unspecified) {
4142 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4145 if (VD->hasLocalStorage()) {
4146 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4149 VD->addAttr(::new (S.Context) ThreadAttr(
4150 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4153 static void handleARMInterruptAttr(Sema &S, Decl *D,
4154 const AttributeList &Attr) {
4155 // Check the attribute arguments.
4156 if (Attr.getNumArgs() > 1) {
4157 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4158 << Attr.getName() << 1;
4163 SourceLocation ArgLoc;
4165 if (Attr.getNumArgs() == 0)
4167 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4170 ARMInterruptAttr::InterruptType Kind;
4171 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4172 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4173 << Attr.getName() << Str << ArgLoc;
4177 unsigned Index = Attr.getAttributeSpellingListIndex();
4178 D->addAttr(::new (S.Context)
4179 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4182 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4183 const AttributeList &Attr) {
4184 if (!checkAttributeNumArgs(S, Attr, 1))
4187 if (!Attr.isArgExpr(0)) {
4188 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4189 << AANT_ArgumentIntegerConstant;
4193 // FIXME: Check for decl - it should be void ()(void).
4195 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4196 llvm::APSInt NumParams(32);
4197 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4198 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4199 << Attr.getName() << AANT_ArgumentIntegerConstant
4200 << NumParamsExpr->getSourceRange();
4204 unsigned Num = NumParams.getLimitedValue(255);
4205 if ((Num & 1) || Num > 30) {
4206 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4207 << Attr.getName() << (int)NumParams.getSExtValue()
4208 << NumParamsExpr->getSourceRange();
4212 D->addAttr(::new (S.Context)
4213 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4214 Attr.getAttributeSpellingListIndex()));
4215 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4218 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4219 // Dispatch the interrupt attribute based on the current target.
4220 if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
4221 handleMSP430InterruptAttr(S, D, Attr);
4223 handleARMInterruptAttr(S, D, Attr);
4226 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
4227 const AttributeList &Attr) {
4229 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4230 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4233 D->addAttr(::new (S.Context)
4234 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4236 Attr.getAttributeSpellingListIndex()));
4239 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4240 const AttributeList &Attr) {
4242 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4243 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4246 D->addAttr(::new (S.Context)
4247 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4249 Attr.getAttributeSpellingListIndex()));
4252 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4253 const AttributeList& Attr) {
4254 // If we try to apply it to a function pointer, don't warn, but don't
4255 // do anything, either. It doesn't matter anyway, because there's nothing
4256 // special about calling a force_align_arg_pointer function.
4257 ValueDecl *VD = dyn_cast<ValueDecl>(D);
4258 if (VD && VD->getType()->isFunctionPointerType())
4260 // Also don't warn on function pointer typedefs.
4261 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4262 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4263 TD->getUnderlyingType()->isFunctionType()))
4265 // Attribute can only be applied to function types.
4266 if (!isa<FunctionDecl>(D)) {
4267 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4268 << Attr.getName() << /* function */0;
4272 D->addAttr(::new (S.Context)
4273 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4274 Attr.getAttributeSpellingListIndex()));
4277 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4278 unsigned AttrSpellingListIndex) {
4279 if (D->hasAttr<DLLExportAttr>()) {
4280 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
4284 if (D->hasAttr<DLLImportAttr>())
4287 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
4290 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
4291 unsigned AttrSpellingListIndex) {
4292 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
4293 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
4294 D->dropAttr<DLLImportAttr>();
4297 if (D->hasAttr<DLLExportAttr>())
4300 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
4303 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
4304 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
4305 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4306 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
4311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4312 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
4313 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4314 // MinGW doesn't allow dllimport on inline functions.
4315 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
4321 unsigned Index = A.getAttributeSpellingListIndex();
4322 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
4323 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
4324 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
4326 D->addAttr(NewAttr);
4330 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
4331 unsigned AttrSpellingListIndex,
4332 MSInheritanceAttr::Spelling SemanticSpelling) {
4333 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
4334 if (IA->getSemanticSpelling() == SemanticSpelling)
4336 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
4337 << 1 /*previous declaration*/;
4338 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
4339 D->dropAttr<MSInheritanceAttr>();
4342 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
4343 if (RD->hasDefinition()) {
4344 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
4345 SemanticSpelling)) {
4349 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
4350 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4351 << 1 /*partial specialization*/;
4354 if (RD->getDescribedClassTemplate()) {
4355 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4356 << 0 /*primary template*/;
4361 return ::new (Context)
4362 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
4365 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4366 // The capability attributes take a single string parameter for the name of
4367 // the capability they represent. The lockable attribute does not take any
4368 // parameters. However, semantically, both attributes represent the same
4369 // concept, and so they use the same semantic attribute. Eventually, the
4370 // lockable attribute will be removed.
4372 // For backward compatibility, any capability which has no specified string
4373 // literal will be considered a "mutex."
4374 StringRef N("mutex");
4375 SourceLocation LiteralLoc;
4376 if (Attr.getKind() == AttributeList::AT_Capability &&
4377 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
4380 // Currently, there are only two names allowed for a capability: role and
4381 // mutex (case insensitive). Diagnose other capability names.
4382 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
4383 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
4385 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
4386 Attr.getAttributeSpellingListIndex()));
4389 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
4390 const AttributeList &Attr) {
4391 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
4392 Attr.getArgAsExpr(0),
4393 Attr.getAttributeSpellingListIndex()));
4396 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
4397 const AttributeList &Attr) {
4398 SmallVector<Expr*, 1> Args;
4399 if (!checkLockFunAttrCommon(S, D, Attr, Args))
4402 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
4404 Args.data(), Args.size(),
4405 Attr.getAttributeSpellingListIndex()));
4408 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
4409 const AttributeList &Attr) {
4410 SmallVector<Expr*, 2> Args;
4411 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
4414 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
4416 Attr.getArgAsExpr(0),
4419 Attr.getAttributeSpellingListIndex()));
4422 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
4423 const AttributeList &Attr) {
4424 // Check that all arguments are lockable objects.
4425 SmallVector<Expr *, 1> Args;
4426 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
4428 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
4429 Attr.getRange(), S.Context, Args.data(), Args.size(),
4430 Attr.getAttributeSpellingListIndex()));
4433 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
4434 const AttributeList &Attr) {
4435 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4438 // check that all arguments are lockable objects
4439 SmallVector<Expr*, 1> Args;
4440 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
4444 RequiresCapabilityAttr *RCA = ::new (S.Context)
4445 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
4446 Args.size(), Attr.getAttributeSpellingListIndex());
4451 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4452 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
4453 if (NSD->isAnonymousNamespace()) {
4454 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
4455 // Do not want to attach the attribute to the namespace because that will
4456 // cause confusing diagnostic reports for uses of declarations within the
4462 if (!S.getLangOpts().CPlusPlus14)
4463 if (Attr.isCXX11Attribute() &&
4464 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
4465 S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension);
4467 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4470 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4471 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4474 std::vector<std::string> Sanitizers;
4476 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4477 StringRef SanitizerName;
4478 SourceLocation LiteralLoc;
4480 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
4483 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
4484 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
4486 Sanitizers.push_back(SanitizerName);
4489 D->addAttr(::new (S.Context) NoSanitizeAttr(
4490 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
4491 Attr.getAttributeSpellingListIndex()));
4494 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
4495 const AttributeList &Attr) {
4496 std::string SanitizerName =
4497 llvm::StringSwitch<std::string>(Attr.getName()->getName())
4498 .Case("no_address_safety_analysis", "address")
4499 .Case("no_sanitize_address", "address")
4500 .Case("no_sanitize_thread", "thread")
4501 .Case("no_sanitize_memory", "memory");
4502 D->addAttr(::new (S.Context)
4503 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
4504 Attr.getAttributeSpellingListIndex()));
4507 /// Handles semantic checking for features that are common to all attributes,
4508 /// such as checking whether a parameter was properly specified, or the correct
4509 /// number of arguments were passed, etc.
4510 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4511 const AttributeList &Attr) {
4512 // Several attributes carry different semantics than the parsing requires, so
4513 // those are opted out of the common handling.
4515 // We also bail on unknown and ignored attributes because those are handled
4516 // as part of the target-specific handling logic.
4517 if (Attr.hasCustomParsing() ||
4518 Attr.getKind() == AttributeList::UnknownAttribute)
4521 // Check whether the attribute requires specific language extensions to be
4523 if (!Attr.diagnoseLangOpts(S))
4526 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
4527 // If there are no optional arguments, then checking for the argument count
4529 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4532 // There are optional arguments, so checking is slightly more involved.
4533 if (Attr.getMinArgs() &&
4534 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
4536 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
4537 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
4541 // Check whether the attribute appertains to the given subject.
4542 if (!Attr.diagnoseAppertainsTo(S, D))
4548 //===----------------------------------------------------------------------===//
4549 // Top Level Sema Entry Points
4550 //===----------------------------------------------------------------------===//
4552 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4553 /// the attribute applies to decls. If the attribute is a type attribute, just
4554 /// silently ignore it if a GNU attribute.
4555 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4556 const AttributeList &Attr,
4557 bool IncludeCXX11Attributes) {
4558 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4561 // Ignore C++11 attributes on declarator chunks: they appertain to the type
4563 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4566 // Unknown attributes are automatically warned on. Target-specific attributes
4567 // which do not apply to the current target architecture are treated as
4568 // though they were unknown attributes.
4569 if (Attr.getKind() == AttributeList::UnknownAttribute ||
4570 !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) {
4571 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4572 ? diag::warn_unhandled_ms_attribute_ignored
4573 : diag::warn_unknown_attribute_ignored)
4578 if (handleCommonAttributeFeatures(S, scope, D, Attr))
4581 switch (Attr.getKind()) {
4583 // Type attributes are handled elsewhere; silently move on.
4584 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4586 case AttributeList::AT_Interrupt:
4587 handleInterruptAttr(S, D, Attr);
4589 case AttributeList::AT_X86ForceAlignArgPointer:
4590 handleX86ForceAlignArgPointerAttr(S, D, Attr);
4592 case AttributeList::AT_DLLExport:
4593 case AttributeList::AT_DLLImport:
4594 handleDLLAttr(S, D, Attr);
4596 case AttributeList::AT_Mips16:
4597 handleSimpleAttribute<Mips16Attr>(S, D, Attr);
4599 case AttributeList::AT_NoMips16:
4600 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4602 case AttributeList::AT_AMDGPUNumVGPR:
4603 handleAMDGPUNumVGPRAttr(S, D, Attr);
4605 case AttributeList::AT_AMDGPUNumSGPR:
4606 handleAMDGPUNumSGPRAttr(S, D, Attr);
4608 case AttributeList::AT_IBAction:
4609 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4611 case AttributeList::AT_IBOutlet:
4612 handleIBOutlet(S, D, Attr);
4614 case AttributeList::AT_IBOutletCollection:
4615 handleIBOutletCollection(S, D, Attr);
4617 case AttributeList::AT_Alias:
4618 handleAliasAttr(S, D, Attr);
4620 case AttributeList::AT_Aligned:
4621 handleAlignedAttr(S, D, Attr);
4623 case AttributeList::AT_AlignValue:
4624 handleAlignValueAttr(S, D, Attr);
4626 case AttributeList::AT_AlwaysInline:
4627 handleAlwaysInlineAttr(S, D, Attr);
4629 case AttributeList::AT_AnalyzerNoReturn:
4630 handleAnalyzerNoReturnAttr(S, D, Attr);
4632 case AttributeList::AT_TLSModel:
4633 handleTLSModelAttr(S, D, Attr);
4635 case AttributeList::AT_Annotate:
4636 handleAnnotateAttr(S, D, Attr);
4638 case AttributeList::AT_Availability:
4639 handleAvailabilityAttr(S, D, Attr);
4641 case AttributeList::AT_CarriesDependency:
4642 handleDependencyAttr(S, scope, D, Attr);
4644 case AttributeList::AT_Common:
4645 handleCommonAttr(S, D, Attr);
4647 case AttributeList::AT_CUDAConstant:
4648 handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
4650 case AttributeList::AT_Constructor:
4651 handleConstructorAttr(S, D, Attr);
4653 case AttributeList::AT_CXX11NoReturn:
4654 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
4656 case AttributeList::AT_Deprecated:
4657 handleDeprecatedAttr(S, D, Attr);
4659 case AttributeList::AT_Destructor:
4660 handleDestructorAttr(S, D, Attr);
4662 case AttributeList::AT_EnableIf:
4663 handleEnableIfAttr(S, D, Attr);
4665 case AttributeList::AT_ExtVectorType:
4666 handleExtVectorTypeAttr(S, scope, D, Attr);
4668 case AttributeList::AT_MinSize:
4669 handleMinSizeAttr(S, D, Attr);
4671 case AttributeList::AT_OptimizeNone:
4672 handleOptimizeNoneAttr(S, D, Attr);
4674 case AttributeList::AT_FlagEnum:
4675 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
4677 case AttributeList::AT_Flatten:
4678 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
4680 case AttributeList::AT_Format:
4681 handleFormatAttr(S, D, Attr);
4683 case AttributeList::AT_FormatArg:
4684 handleFormatArgAttr(S, D, Attr);
4686 case AttributeList::AT_CUDAGlobal:
4687 handleGlobalAttr(S, D, Attr);
4689 case AttributeList::AT_CUDADevice:
4690 handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
4692 case AttributeList::AT_CUDAHost:
4693 handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
4695 case AttributeList::AT_GNUInline:
4696 handleGNUInlineAttr(S, D, Attr);
4698 case AttributeList::AT_CUDALaunchBounds:
4699 handleLaunchBoundsAttr(S, D, Attr);
4701 case AttributeList::AT_Restrict:
4702 handleRestrictAttr(S, D, Attr);
4704 case AttributeList::AT_MayAlias:
4705 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
4707 case AttributeList::AT_Mode:
4708 handleModeAttr(S, D, Attr);
4710 case AttributeList::AT_NoCommon:
4711 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
4713 case AttributeList::AT_NoSplitStack:
4714 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
4716 case AttributeList::AT_NonNull:
4717 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
4718 handleNonNullAttrParameter(S, PVD, Attr);
4720 handleNonNullAttr(S, D, Attr);
4722 case AttributeList::AT_ReturnsNonNull:
4723 handleReturnsNonNullAttr(S, D, Attr);
4725 case AttributeList::AT_AssumeAligned:
4726 handleAssumeAlignedAttr(S, D, Attr);
4728 case AttributeList::AT_Overloadable:
4729 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
4731 case AttributeList::AT_Ownership:
4732 handleOwnershipAttr(S, D, Attr);
4734 case AttributeList::AT_Cold:
4735 handleColdAttr(S, D, Attr);
4737 case AttributeList::AT_Hot:
4738 handleHotAttr(S, D, Attr);
4740 case AttributeList::AT_Naked:
4741 handleSimpleAttribute<NakedAttr>(S, D, Attr);
4743 case AttributeList::AT_NoReturn:
4744 handleNoReturnAttr(S, D, Attr);
4746 case AttributeList::AT_NoThrow:
4747 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
4749 case AttributeList::AT_CUDAShared:
4750 handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
4752 case AttributeList::AT_VecReturn:
4753 handleVecReturnAttr(S, D, Attr);
4756 case AttributeList::AT_ObjCOwnership:
4757 handleObjCOwnershipAttr(S, D, Attr);
4759 case AttributeList::AT_ObjCPreciseLifetime:
4760 handleObjCPreciseLifetimeAttr(S, D, Attr);
4763 case AttributeList::AT_ObjCReturnsInnerPointer:
4764 handleObjCReturnsInnerPointerAttr(S, D, Attr);
4767 case AttributeList::AT_ObjCRequiresSuper:
4768 handleObjCRequiresSuperAttr(S, D, Attr);
4771 case AttributeList::AT_ObjCBridge:
4772 handleObjCBridgeAttr(S, scope, D, Attr);
4775 case AttributeList::AT_ObjCBridgeMutable:
4776 handleObjCBridgeMutableAttr(S, scope, D, Attr);
4779 case AttributeList::AT_ObjCBridgeRelated:
4780 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
4783 case AttributeList::AT_ObjCDesignatedInitializer:
4784 handleObjCDesignatedInitializer(S, D, Attr);
4787 case AttributeList::AT_ObjCRuntimeName:
4788 handleObjCRuntimeName(S, D, Attr);
4791 case AttributeList::AT_ObjCBoxable:
4792 handleObjCBoxable(S, D, Attr);
4795 case AttributeList::AT_CFAuditedTransfer:
4796 handleCFAuditedTransferAttr(S, D, Attr);
4798 case AttributeList::AT_CFUnknownTransfer:
4799 handleCFUnknownTransferAttr(S, D, Attr);
4802 case AttributeList::AT_CFConsumed:
4803 case AttributeList::AT_NSConsumed:
4804 handleNSConsumedAttr(S, D, Attr);
4806 case AttributeList::AT_NSConsumesSelf:
4807 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
4810 case AttributeList::AT_NSReturnsAutoreleased:
4811 case AttributeList::AT_NSReturnsNotRetained:
4812 case AttributeList::AT_CFReturnsNotRetained:
4813 case AttributeList::AT_NSReturnsRetained:
4814 case AttributeList::AT_CFReturnsRetained:
4815 handleNSReturnsRetainedAttr(S, D, Attr);
4817 case AttributeList::AT_WorkGroupSizeHint:
4818 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
4820 case AttributeList::AT_ReqdWorkGroupSize:
4821 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
4823 case AttributeList::AT_VecTypeHint:
4824 handleVecTypeHint(S, D, Attr);
4827 case AttributeList::AT_InitPriority:
4828 handleInitPriorityAttr(S, D, Attr);
4831 case AttributeList::AT_Packed:
4832 handlePackedAttr(S, D, Attr);
4834 case AttributeList::AT_Section:
4835 handleSectionAttr(S, D, Attr);
4837 case AttributeList::AT_Target:
4838 handleTargetAttr(S, D, Attr);
4840 case AttributeList::AT_Unavailable:
4841 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4843 case AttributeList::AT_ArcWeakrefUnavailable:
4844 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
4846 case AttributeList::AT_ObjCRootClass:
4847 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
4849 case AttributeList::AT_ObjCExplicitProtocolImpl:
4850 handleObjCSuppresProtocolAttr(S, D, Attr);
4852 case AttributeList::AT_ObjCRequiresPropertyDefs:
4853 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
4855 case AttributeList::AT_Unused:
4856 handleSimpleAttribute<UnusedAttr>(S, D, Attr);
4858 case AttributeList::AT_ReturnsTwice:
4859 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
4861 case AttributeList::AT_Used:
4862 handleUsedAttr(S, D, Attr);
4864 case AttributeList::AT_Visibility:
4865 handleVisibilityAttr(S, D, Attr, false);
4867 case AttributeList::AT_TypeVisibility:
4868 handleVisibilityAttr(S, D, Attr, true);
4870 case AttributeList::AT_WarnUnused:
4871 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
4873 case AttributeList::AT_WarnUnusedResult:
4874 handleWarnUnusedResult(S, D, Attr);
4876 case AttributeList::AT_Weak:
4877 handleSimpleAttribute<WeakAttr>(S, D, Attr);
4879 case AttributeList::AT_WeakRef:
4880 handleWeakRefAttr(S, D, Attr);
4882 case AttributeList::AT_WeakImport:
4883 handleWeakImportAttr(S, D, Attr);
4885 case AttributeList::AT_TransparentUnion:
4886 handleTransparentUnionAttr(S, D, Attr);
4888 case AttributeList::AT_ObjCException:
4889 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
4891 case AttributeList::AT_ObjCMethodFamily:
4892 handleObjCMethodFamilyAttr(S, D, Attr);
4894 case AttributeList::AT_ObjCNSObject:
4895 handleObjCNSObject(S, D, Attr);
4897 case AttributeList::AT_ObjCIndependentClass:
4898 handleObjCIndependentClass(S, D, Attr);
4900 case AttributeList::AT_Blocks:
4901 handleBlocksAttr(S, D, Attr);
4903 case AttributeList::AT_Sentinel:
4904 handleSentinelAttr(S, D, Attr);
4906 case AttributeList::AT_Const:
4907 handleSimpleAttribute<ConstAttr>(S, D, Attr);
4909 case AttributeList::AT_Pure:
4910 handleSimpleAttribute<PureAttr>(S, D, Attr);
4912 case AttributeList::AT_Cleanup:
4913 handleCleanupAttr(S, D, Attr);
4915 case AttributeList::AT_NoDebug:
4916 handleNoDebugAttr(S, D, Attr);
4918 case AttributeList::AT_NoDuplicate:
4919 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
4921 case AttributeList::AT_NoInline:
4922 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
4924 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4925 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
4927 case AttributeList::AT_StdCall:
4928 case AttributeList::AT_CDecl:
4929 case AttributeList::AT_FastCall:
4930 case AttributeList::AT_ThisCall:
4931 case AttributeList::AT_Pascal:
4932 case AttributeList::AT_VectorCall:
4933 case AttributeList::AT_MSABI:
4934 case AttributeList::AT_SysVABI:
4935 case AttributeList::AT_Pcs:
4936 case AttributeList::AT_IntelOclBicc:
4937 handleCallConvAttr(S, D, Attr);
4939 case AttributeList::AT_OpenCLKernel:
4940 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
4942 case AttributeList::AT_OpenCLImageAccess:
4943 handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
4946 // Microsoft attributes:
4947 case AttributeList::AT_MSNoVTable:
4948 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
4950 case AttributeList::AT_MSStruct:
4951 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
4953 case AttributeList::AT_Uuid:
4954 handleUuidAttr(S, D, Attr);
4956 case AttributeList::AT_MSInheritance:
4957 handleMSInheritanceAttr(S, D, Attr);
4959 case AttributeList::AT_SelectAny:
4960 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
4962 case AttributeList::AT_Thread:
4963 handleDeclspecThreadAttr(S, D, Attr);
4966 // Thread safety attributes:
4967 case AttributeList::AT_AssertExclusiveLock:
4968 handleAssertExclusiveLockAttr(S, D, Attr);
4970 case AttributeList::AT_AssertSharedLock:
4971 handleAssertSharedLockAttr(S, D, Attr);
4973 case AttributeList::AT_GuardedVar:
4974 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
4976 case AttributeList::AT_PtGuardedVar:
4977 handlePtGuardedVarAttr(S, D, Attr);
4979 case AttributeList::AT_ScopedLockable:
4980 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
4982 case AttributeList::AT_NoSanitize:
4983 handleNoSanitizeAttr(S, D, Attr);
4985 case AttributeList::AT_NoSanitizeSpecific:
4986 handleNoSanitizeSpecificAttr(S, D, Attr);
4988 case AttributeList::AT_NoThreadSafetyAnalysis:
4989 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
4991 case AttributeList::AT_GuardedBy:
4992 handleGuardedByAttr(S, D, Attr);
4994 case AttributeList::AT_PtGuardedBy:
4995 handlePtGuardedByAttr(S, D, Attr);
4997 case AttributeList::AT_ExclusiveTrylockFunction:
4998 handleExclusiveTrylockFunctionAttr(S, D, Attr);
5000 case AttributeList::AT_LockReturned:
5001 handleLockReturnedAttr(S, D, Attr);
5003 case AttributeList::AT_LocksExcluded:
5004 handleLocksExcludedAttr(S, D, Attr);
5006 case AttributeList::AT_SharedTrylockFunction:
5007 handleSharedTrylockFunctionAttr(S, D, Attr);
5009 case AttributeList::AT_AcquiredBefore:
5010 handleAcquiredBeforeAttr(S, D, Attr);
5012 case AttributeList::AT_AcquiredAfter:
5013 handleAcquiredAfterAttr(S, D, Attr);
5016 // Capability analysis attributes.
5017 case AttributeList::AT_Capability:
5018 case AttributeList::AT_Lockable:
5019 handleCapabilityAttr(S, D, Attr);
5021 case AttributeList::AT_RequiresCapability:
5022 handleRequiresCapabilityAttr(S, D, Attr);
5025 case AttributeList::AT_AssertCapability:
5026 handleAssertCapabilityAttr(S, D, Attr);
5028 case AttributeList::AT_AcquireCapability:
5029 handleAcquireCapabilityAttr(S, D, Attr);
5031 case AttributeList::AT_ReleaseCapability:
5032 handleReleaseCapabilityAttr(S, D, Attr);
5034 case AttributeList::AT_TryAcquireCapability:
5035 handleTryAcquireCapabilityAttr(S, D, Attr);
5038 // Consumed analysis attributes.
5039 case AttributeList::AT_Consumable:
5040 handleConsumableAttr(S, D, Attr);
5042 case AttributeList::AT_ConsumableAutoCast:
5043 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
5045 case AttributeList::AT_ConsumableSetOnRead:
5046 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
5048 case AttributeList::AT_CallableWhen:
5049 handleCallableWhenAttr(S, D, Attr);
5051 case AttributeList::AT_ParamTypestate:
5052 handleParamTypestateAttr(S, D, Attr);
5054 case AttributeList::AT_ReturnTypestate:
5055 handleReturnTypestateAttr(S, D, Attr);
5057 case AttributeList::AT_SetTypestate:
5058 handleSetTypestateAttr(S, D, Attr);
5060 case AttributeList::AT_TestTypestate:
5061 handleTestTypestateAttr(S, D, Attr);
5064 // Type safety attributes.
5065 case AttributeList::AT_ArgumentWithTypeTag:
5066 handleArgumentWithTypeTagAttr(S, D, Attr);
5068 case AttributeList::AT_TypeTagForDatatype:
5069 handleTypeTagForDatatypeAttr(S, D, Attr);
5074 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5075 /// attribute list to the specified decl, ignoring any type attributes.
5076 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
5077 const AttributeList *AttrList,
5078 bool IncludeCXX11Attributes) {
5079 for (const AttributeList* l = AttrList; l; l = l->getNext())
5080 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
5082 // FIXME: We should be able to handle these cases in TableGen.
5084 // static int a9 __attribute__((weakref));
5085 // but that looks really pointless. We reject it.
5086 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
5087 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
5088 << cast<NamedDecl>(D);
5089 D->dropAttr<WeakRefAttr>();
5093 // FIXME: We should be able to handle this in TableGen as well. It would be
5094 // good to have a way to specify "these attributes must appear as a group",
5095 // for these. Additionally, it would be good to have a way to specify "these
5096 // attribute must never appear as a group" for attributes like cold and hot.
5097 if (!D->hasAttr<OpenCLKernelAttr>()) {
5098 // These attributes cannot be applied to a non-kernel function.
5099 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
5100 // FIXME: This emits a different error message than
5101 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
5102 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5103 D->setInvalidDecl();
5104 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
5105 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5106 D->setInvalidDecl();
5107 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
5108 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5109 D->setInvalidDecl();
5110 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
5111 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5112 << A << ExpectedKernelFunction;
5113 D->setInvalidDecl();
5114 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
5115 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5116 << A << ExpectedKernelFunction;
5117 D->setInvalidDecl();
5122 // Annotation attributes are the only attributes allowed after an access
5124 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5125 const AttributeList *AttrList) {
5126 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5127 if (l->getKind() == AttributeList::AT_Annotate) {
5128 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
5130 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
5138 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
5139 /// contains any decl attributes that we should warn about.
5140 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
5141 for ( ; A; A = A->getNext()) {
5142 // Only warn if the attribute is an unignored, non-type attribute.
5143 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
5144 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
5146 if (A->getKind() == AttributeList::UnknownAttribute) {
5147 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
5148 << A->getName() << A->getRange();
5150 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
5151 << A->getName() << A->getRange();
5156 /// checkUnusedDeclAttributes - Given a declarator which is not being
5157 /// used to build a declaration, complain about any decl attributes
5158 /// which might be lying around on it.
5159 void Sema::checkUnusedDeclAttributes(Declarator &D) {
5160 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
5161 ::checkUnusedDeclAttributes(*this, D.getAttributes());
5162 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
5163 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
5166 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5167 /// \#pragma weak needs a non-definition decl and source may not have one.
5168 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5169 SourceLocation Loc) {
5170 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
5171 NamedDecl *NewD = nullptr;
5172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5173 FunctionDecl *NewFD;
5174 // FIXME: Missing call to CheckFunctionDeclaration().
5176 // FIXME: Is the qualifier info correct?
5177 // FIXME: Is the DeclContext correct?
5178 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
5179 Loc, Loc, DeclarationName(II),
5180 FD->getType(), FD->getTypeSourceInfo(),
5181 SC_None, false/*isInlineSpecified*/,
5183 false/*isConstexprSpecified*/);
5186 if (FD->getQualifier())
5187 NewFD->setQualifierInfo(FD->getQualifierLoc());
5189 // Fake up parameter variables; they are declared as if this were
5191 QualType FDTy = FD->getType();
5192 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5193 SmallVector<ParmVarDecl*, 16> Params;
5194 for (const auto &AI : FT->param_types()) {
5195 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
5196 Param->setScopeInfo(0, Params.size());
5197 Params.push_back(Param);
5199 NewFD->setParams(Params);
5201 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5202 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
5203 VD->getInnerLocStart(), VD->getLocation(), II,
5204 VD->getType(), VD->getTypeSourceInfo(),
5205 VD->getStorageClass());
5206 if (VD->getQualifier()) {
5207 VarDecl *NewVD = cast<VarDecl>(NewD);
5208 NewVD->setQualifierInfo(VD->getQualifierLoc());
5214 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5215 /// applied to it, possibly with an alias.
5216 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
5217 if (W.getUsed()) return; // only do this once
5219 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5220 IdentifierInfo *NDId = ND->getIdentifier();
5221 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
5222 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
5224 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5225 WeakTopLevelDecl.push_back(NewD);
5226 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5227 // to insert Decl at TU scope, sorry.
5228 DeclContext *SavedContext = CurContext;
5229 CurContext = Context.getTranslationUnitDecl();
5230 NewD->setDeclContext(CurContext);
5231 NewD->setLexicalDeclContext(CurContext);
5232 PushOnScopeChains(NewD, S);
5233 CurContext = SavedContext;
5234 } else { // just add weak to existing
5235 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5239 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
5240 // It's valid to "forward-declare" #pragma weak, in which case we
5242 LoadExternalWeakUndeclaredIdentifiers();
5243 if (!WeakUndeclaredIdentifiers.empty()) {
5244 NamedDecl *ND = nullptr;
5245 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5246 if (VD->isExternC())
5248 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5249 if (FD->isExternC())
5252 if (IdentifierInfo *Id = ND->getIdentifier()) {
5253 auto I = WeakUndeclaredIdentifiers.find(Id);
5254 if (I != WeakUndeclaredIdentifiers.end()) {
5255 WeakInfo W = I->second;
5256 DeclApplyPragmaWeak(S, ND, W);
5257 WeakUndeclaredIdentifiers[Id] = W;
5264 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
5265 /// it, apply them to D. This is a bit tricky because PD can have attributes
5266 /// specified in many different places, and we need to find and apply them all.
5267 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
5268 // Apply decl attributes from the DeclSpec if present.
5269 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
5270 ProcessDeclAttributeList(S, D, Attrs);
5272 // Walk the declarator structure, applying decl attributes that were in a type
5273 // position to the decl itself. This handles cases like:
5274 // int *__attr__(x)** D;
5275 // when X is a decl attribute.
5276 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5277 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5278 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
5280 // Finally, apply any attributes on the decl itself.
5281 if (const AttributeList *Attrs = PD.getAttributes())
5282 ProcessDeclAttributeList(S, D, Attrs);
5285 /// Is the given declaration allowed to use a forbidden type?
5286 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
5287 // Private ivars are always okay. Unfortunately, people don't
5288 // always properly make their ivars private, even in system headers.
5289 // Plus we need to make fields okay, too.
5290 // Function declarations in sys headers will be marked unavailable.
5291 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5292 !isa<FunctionDecl>(decl))
5295 // Require it to be declared in a system header.
5296 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
5299 /// Handle a delayed forbidden-type diagnostic.
5300 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5302 if (decl && isForbiddenTypeAllowed(S, decl)) {
5303 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context,
5304 "this system declaration uses an unsupported type",
5308 if (S.getLangOpts().ObjCAutoRefCount)
5309 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5310 // FIXME: we may want to suppress diagnostics for all
5311 // kind of forbidden type messages on unavailable functions.
5312 if (FD->hasAttr<UnavailableAttr>() &&
5313 diag.getForbiddenTypeDiagnostic() ==
5314 diag::err_arc_array_param_no_ownership) {
5315 diag.Triggered = true;
5320 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5321 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5322 diag.Triggered = true;
5326 static bool isDeclDeprecated(Decl *D) {
5328 if (D->isDeprecated())
5330 // A category implicitly has the availability of the interface.
5331 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5332 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5333 return Interface->isDeprecated();
5334 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5338 static bool isDeclUnavailable(Decl *D) {
5340 if (D->isUnavailable())
5342 // A category implicitly has the availability of the interface.
5343 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5344 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5345 return Interface->isUnavailable();
5346 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5350 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
5351 Decl *Ctx, const NamedDecl *D,
5352 StringRef Message, SourceLocation Loc,
5353 const ObjCInterfaceDecl *UnknownObjCClass,
5354 const ObjCPropertyDecl *ObjCProperty,
5355 bool ObjCPropertyAccess) {
5356 // Diagnostics for deprecated or unavailable.
5357 unsigned diag, diag_message, diag_fwdclass_message;
5359 // Matches 'diag::note_property_attribute' options.
5360 unsigned property_note_select;
5362 // Matches diag::note_availability_specified_here.
5363 unsigned available_here_select_kind;
5365 // Don't warn if our current context is deprecated or unavailable.
5367 case Sema::AD_Deprecation:
5368 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
5370 diag = !ObjCPropertyAccess ? diag::warn_deprecated
5371 : diag::warn_property_method_deprecated;
5372 diag_message = diag::warn_deprecated_message;
5373 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
5374 property_note_select = /* deprecated */ 0;
5375 available_here_select_kind = /* deprecated */ 2;
5378 case Sema::AD_Unavailable:
5379 if (isDeclUnavailable(Ctx))
5381 diag = !ObjCPropertyAccess ? diag::err_unavailable
5382 : diag::err_property_method_unavailable;
5383 diag_message = diag::err_unavailable_message;
5384 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
5385 property_note_select = /* unavailable */ 1;
5386 available_here_select_kind = /* unavailable */ 0;
5389 case Sema::AD_Partial:
5390 diag = diag::warn_partial_availability;
5391 diag_message = diag::warn_partial_message;
5392 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
5393 property_note_select = /* partial */ 2;
5394 available_here_select_kind = /* partial */ 3;
5398 if (!Message.empty()) {
5399 S.Diag(Loc, diag_message) << D << Message;
5401 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5402 << ObjCProperty->getDeclName() << property_note_select;
5403 } else if (!UnknownObjCClass) {
5404 S.Diag(Loc, diag) << D;
5406 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5407 << ObjCProperty->getDeclName() << property_note_select;
5409 S.Diag(Loc, diag_fwdclass_message) << D;
5410 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5413 S.Diag(D->getLocation(), diag::note_availability_specified_here)
5414 << D << available_here_select_kind;
5415 if (K == Sema::AD_Partial)
5416 S.Diag(Loc, diag::note_partial_availability_silence) << D;
5419 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
5421 assert(DD.Kind == DelayedDiagnostic::Deprecation ||
5422 DD.Kind == DelayedDiagnostic::Unavailable);
5423 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
5424 ? Sema::AD_Deprecation
5425 : Sema::AD_Unavailable;
5426 DD.Triggered = true;
5427 DoEmitAvailabilityWarning(
5428 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
5429 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
5432 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5433 assert(DelayedDiagnostics.getCurrentPool());
5434 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5435 DelayedDiagnostics.popWithoutEmitting(state);
5437 // When delaying diagnostics to run in the context of a parsed
5438 // declaration, we only want to actually emit anything if parsing
5442 // We emit all the active diagnostics in this pool or any of its
5443 // parents. In general, we'll get one pool for the decl spec
5444 // and a child pool for each declarator; in a decl group like:
5445 // deprecated_typedef foo, *bar, baz();
5446 // only the declarator pops will be passed decls. This is correct;
5447 // we really do need to consider delayed diagnostics from the decl spec
5448 // for each of the different declarations.
5449 const DelayedDiagnosticPool *pool = &poppedPool;
5451 for (DelayedDiagnosticPool::pool_iterator
5452 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5453 // This const_cast is a bit lame. Really, Triggered should be mutable.
5454 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5458 switch (diag.Kind) {
5459 case DelayedDiagnostic::Deprecation:
5460 case DelayedDiagnostic::Unavailable:
5461 // Don't bother giving deprecation/unavailable diagnostics if
5462 // the decl is invalid.
5463 if (!decl->isInvalidDecl())
5464 handleDelayedAvailabilityCheck(*this, diag, decl);
5467 case DelayedDiagnostic::Access:
5468 HandleDelayedAccessCheck(diag, decl);
5471 case DelayedDiagnostic::ForbiddenType:
5472 handleDelayedForbiddenType(*this, diag, decl);
5476 } while ((pool = pool->getParent()));
5479 /// Given a set of delayed diagnostics, re-emit them as if they had
5480 /// been delayed in the current context instead of in the given pool.
5481 /// Essentially, this just moves them to the current pool.
5482 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5483 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5484 assert(curPool && "re-emitting in undelayed context not supported");
5485 curPool->steal(pool);
5488 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
5489 NamedDecl *D, StringRef Message,
5491 const ObjCInterfaceDecl *UnknownObjCClass,
5492 const ObjCPropertyDecl *ObjCProperty,
5493 bool ObjCPropertyAccess) {
5494 // Delay if we're currently parsing a declaration.
5495 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
5496 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
5497 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
5498 ObjCPropertyAccess));
5502 Decl *Ctx = cast<Decl>(getCurLexicalContext());
5503 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
5504 ObjCProperty, ObjCPropertyAccess);