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, SourceRange Range,
248 IdentifierInfo *Ident) {
249 if (AttrTy *A = D->getAttr<AttrTy>()) {
250 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
252 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
258 /// \brief Check if IdxExpr is a valid parameter index for a function or
259 /// instance method D. May output an error.
261 /// \returns true if IdxExpr is a valid index.
262 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
263 const AttributeList &Attr,
267 assert(isFunctionOrMethodOrBlock(D));
269 // In C++ the implicit 'this' function parameter also counts.
270 // Parameters are counted from one.
271 bool HP = hasFunctionProto(D);
272 bool HasImplicitThisParam = isInstanceMethod(D);
273 bool IV = HP && isFunctionOrMethodVariadic(D);
275 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
278 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
279 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
280 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
281 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
282 << IdxExpr->getSourceRange();
286 Idx = IdxInt.getLimitedValue();
287 if (Idx < 1 || (!IV && Idx > NumParams)) {
288 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
289 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
292 Idx--; // Convert to zero-based.
293 if (HasImplicitThisParam) {
295 S.Diag(Attr.getLoc(),
296 diag::err_attribute_invalid_implicit_this_argument)
297 << Attr.getName() << IdxExpr->getSourceRange();
306 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
307 /// If not emit an error and return false. If the argument is an identifier it
308 /// will emit an error with a fixit hint and treat it as if it was a string
310 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
311 unsigned ArgNum, StringRef &Str,
312 SourceLocation *ArgLocation) {
313 // Look for identifiers. If we have one emit a hint to fix it to a literal.
314 if (Attr.isArgIdent(ArgNum)) {
315 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
316 Diag(Loc->Loc, diag::err_attribute_argument_type)
317 << Attr.getName() << AANT_ArgumentString
318 << FixItHint::CreateInsertion(Loc->Loc, "\"")
319 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
320 Str = Loc->Ident->getName();
322 *ArgLocation = Loc->Loc;
326 // Now check for an actual string literal.
327 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
328 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
330 *ArgLocation = ArgExpr->getLocStart();
332 if (!Literal || !Literal->isAscii()) {
333 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
334 << Attr.getName() << AANT_ArgumentString;
338 Str = Literal->getString();
342 /// \brief Applies the given attribute to the Decl without performing any
343 /// additional semantic checking.
344 template <typename AttrType>
345 static void handleSimpleAttribute(Sema &S, Decl *D,
346 const AttributeList &Attr) {
347 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
348 Attr.getAttributeSpellingListIndex()));
351 /// \brief Check if the passed-in expression is of type int or bool.
352 static bool isIntOrBool(Expr *Exp) {
353 QualType QT = Exp->getType();
354 return QT->isBooleanType() || QT->isIntegerType();
358 // Check to see if the type is a smart pointer of some kind. We assume
359 // it's a smart pointer if it defines both operator-> and operator*.
360 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
361 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
362 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
366 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
367 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
374 /// \brief Check if passed in Decl is a pointer type.
375 /// Note that this function may produce an error message.
376 /// \return true if the Decl is a pointer type; false otherwise
377 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
378 const AttributeList &Attr) {
379 const ValueDecl *vd = cast<ValueDecl>(D);
380 QualType QT = vd->getType();
381 if (QT->isAnyPointerType())
384 if (const RecordType *RT = QT->getAs<RecordType>()) {
385 // If it's an incomplete type, it could be a smart pointer; skip it.
386 // (We don't want to force template instantiation if we can avoid it,
387 // since that would alter the order in which templates are instantiated.)
388 if (RT->isIncompleteType())
391 if (threadSafetyCheckIsSmartPointer(S, RT))
395 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
396 << Attr.getName() << QT;
400 /// \brief Checks that the passed in QualType either is of RecordType or points
401 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
402 static const RecordType *getRecordType(QualType QT) {
403 if (const RecordType *RT = QT->getAs<RecordType>())
406 // Now check if we point to record type.
407 if (const PointerType *PT = QT->getAs<PointerType>())
408 return PT->getPointeeType()->getAs<RecordType>();
413 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
414 const RecordType *RT = getRecordType(Ty);
419 // Don't check for the capability if the class hasn't been defined yet.
420 if (RT->isIncompleteType())
423 // Allow smart pointers to be used as capability objects.
424 // FIXME -- Check the type that the smart pointer points to.
425 if (threadSafetyCheckIsSmartPointer(S, RT))
428 // Check if the record itself has a capability.
429 RecordDecl *RD = RT->getDecl();
430 if (RD->hasAttr<CapabilityAttr>())
433 // Else check if any base classes have a capability.
434 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
435 CXXBasePaths BPaths(false, false);
436 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
437 const auto *Type = BS->getType()->getAs<RecordType>();
438 return Type->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() && !typeHasCapability(S, QT)) {
633 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
638 // Check that all arguments are lockable objects.
639 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
646 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
647 const AttributeList &Attr) {
648 SmallVector<Expr*, 1> Args;
649 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
652 Expr **StartArg = &Args[0];
653 D->addAttr(::new (S.Context)
654 AcquiredAfterAttr(Attr.getRange(), S.Context,
655 StartArg, Args.size(),
656 Attr.getAttributeSpellingListIndex()));
659 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
660 const AttributeList &Attr) {
661 SmallVector<Expr*, 1> Args;
662 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
665 Expr **StartArg = &Args[0];
666 D->addAttr(::new (S.Context)
667 AcquiredBeforeAttr(Attr.getRange(), S.Context,
668 StartArg, Args.size(),
669 Attr.getAttributeSpellingListIndex()));
672 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
673 const AttributeList &Attr,
674 SmallVectorImpl<Expr *> &Args) {
675 // zero or more arguments ok
676 // check that all arguments are lockable objects
677 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
682 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
683 const AttributeList &Attr) {
684 SmallVector<Expr*, 1> Args;
685 if (!checkLockFunAttrCommon(S, D, Attr, Args))
688 unsigned Size = Args.size();
689 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
690 D->addAttr(::new (S.Context)
691 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
692 Attr.getAttributeSpellingListIndex()));
695 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
696 const AttributeList &Attr) {
697 SmallVector<Expr*, 1> Args;
698 if (!checkLockFunAttrCommon(S, D, Attr, Args))
701 unsigned Size = Args.size();
702 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
703 D->addAttr(::new (S.Context)
704 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
706 Attr.getAttributeSpellingListIndex()));
710 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
711 const AttributeList &Attr,
712 SmallVectorImpl<Expr *> &Args) {
713 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
716 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
717 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
718 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
722 // check that all arguments are lockable objects
723 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
728 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
729 const AttributeList &Attr) {
730 SmallVector<Expr*, 2> Args;
731 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
734 D->addAttr(::new (S.Context)
735 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
736 Attr.getArgAsExpr(0),
737 Args.data(), Args.size(),
738 Attr.getAttributeSpellingListIndex()));
741 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
742 const AttributeList &Attr) {
743 SmallVector<Expr*, 2> Args;
744 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
747 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
748 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
749 Args.size(), Attr.getAttributeSpellingListIndex()));
752 static void handleLockReturnedAttr(Sema &S, Decl *D,
753 const AttributeList &Attr) {
754 // check that the argument is lockable object
755 SmallVector<Expr*, 1> Args;
756 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
757 unsigned Size = Args.size();
761 D->addAttr(::new (S.Context)
762 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
763 Attr.getAttributeSpellingListIndex()));
766 static void handleLocksExcludedAttr(Sema &S, Decl *D,
767 const AttributeList &Attr) {
768 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
771 // check that all arguments are lockable objects
772 SmallVector<Expr*, 1> Args;
773 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
774 unsigned Size = Args.size();
777 Expr **StartArg = &Args[0];
779 D->addAttr(::new (S.Context)
780 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
781 Attr.getAttributeSpellingListIndex()));
784 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
785 Expr *Cond = Attr.getArgAsExpr(0);
786 if (!Cond->isTypeDependent()) {
787 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
788 if (Converted.isInvalid())
790 Cond = Converted.get();
794 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
797 SmallVector<PartialDiagnosticAt, 8> Diags;
798 if (!Cond->isValueDependent() &&
799 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
801 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
802 for (int I = 0, N = Diags.size(); I != N; ++I)
803 S.Diag(Diags[I].first, Diags[I].second);
807 D->addAttr(::new (S.Context)
808 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
809 Attr.getAttributeSpellingListIndex()));
812 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
813 const AttributeList &Attr) {
814 if (D->hasAttr<PassObjectSizeAttr>()) {
815 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
820 Expr *E = Attr.getArgAsExpr(0);
822 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
825 // pass_object_size's argument is passed in as the second argument of
826 // __builtin_object_size. So, it has the same constraints as that second
827 // argument; namely, it must be in the range [0, 3].
829 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
830 << Attr.getName() << 0 << 3 << E->getSourceRange();
834 // pass_object_size is only supported on constant pointer parameters; as a
835 // kindness to users, we allow the parameter to be non-const for declarations.
836 // At this point, we have no clue if `D` belongs to a function declaration or
837 // definition, so we defer the constness check until later.
838 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
839 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
840 << Attr.getName() << 1;
844 D->addAttr(::new (S.Context)
845 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
846 Attr.getAttributeSpellingListIndex()));
849 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
850 ConsumableAttr::ConsumedState DefaultState;
852 if (Attr.isArgIdent(0)) {
853 IdentifierLoc *IL = Attr.getArgAsIdent(0);
854 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
856 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
857 << Attr.getName() << IL->Ident;
861 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
862 << Attr.getName() << AANT_ArgumentIdentifier;
866 D->addAttr(::new (S.Context)
867 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
868 Attr.getAttributeSpellingListIndex()));
872 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
873 const AttributeList &Attr) {
874 ASTContext &CurrContext = S.getASTContext();
875 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
877 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
878 if (!RD->hasAttr<ConsumableAttr>()) {
879 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
880 RD->getNameAsString();
890 static void handleCallableWhenAttr(Sema &S, Decl *D,
891 const AttributeList &Attr) {
892 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
895 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
898 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
899 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
900 CallableWhenAttr::ConsumedState CallableState;
902 StringRef StateString;
904 if (Attr.isArgIdent(ArgIndex)) {
905 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
906 StateString = Ident->Ident->getName();
909 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
913 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
915 S.Diag(Loc, diag::warn_attribute_type_not_supported)
916 << Attr.getName() << StateString;
920 States.push_back(CallableState);
923 D->addAttr(::new (S.Context)
924 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
925 States.size(), Attr.getAttributeSpellingListIndex()));
929 static void handleParamTypestateAttr(Sema &S, Decl *D,
930 const AttributeList &Attr) {
931 ParamTypestateAttr::ConsumedState ParamState;
933 if (Attr.isArgIdent(0)) {
934 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
935 StringRef StateString = Ident->Ident->getName();
937 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
939 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
940 << Attr.getName() << StateString;
944 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
945 Attr.getName() << AANT_ArgumentIdentifier;
949 // FIXME: This check is currently being done in the analysis. It can be
950 // enabled here only after the parser propagates attributes at
951 // template specialization definition, not declaration.
952 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
953 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
955 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
956 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
957 // ReturnType.getAsString();
961 D->addAttr(::new (S.Context)
962 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
963 Attr.getAttributeSpellingListIndex()));
967 static void handleReturnTypestateAttr(Sema &S, Decl *D,
968 const AttributeList &Attr) {
969 ReturnTypestateAttr::ConsumedState ReturnState;
971 if (Attr.isArgIdent(0)) {
972 IdentifierLoc *IL = Attr.getArgAsIdent(0);
973 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
975 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
976 << Attr.getName() << IL->Ident;
980 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
981 Attr.getName() << AANT_ArgumentIdentifier;
985 // FIXME: This check is currently being done in the analysis. It can be
986 // enabled here only after the parser propagates attributes at
987 // template specialization definition, not declaration.
988 //QualType ReturnType;
990 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
991 // ReturnType = Param->getType();
993 //} else if (const CXXConstructorDecl *Constructor =
994 // dyn_cast<CXXConstructorDecl>(D)) {
995 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
999 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1002 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1004 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1005 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1006 // ReturnType.getAsString();
1010 D->addAttr(::new (S.Context)
1011 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1012 Attr.getAttributeSpellingListIndex()));
1016 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1017 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1020 SetTypestateAttr::ConsumedState NewState;
1021 if (Attr.isArgIdent(0)) {
1022 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1023 StringRef Param = Ident->Ident->getName();
1024 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1025 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1026 << Attr.getName() << Param;
1030 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1031 Attr.getName() << AANT_ArgumentIdentifier;
1035 D->addAttr(::new (S.Context)
1036 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1037 Attr.getAttributeSpellingListIndex()));
1040 static void handleTestTypestateAttr(Sema &S, Decl *D,
1041 const AttributeList &Attr) {
1042 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1045 TestTypestateAttr::ConsumedState TestState;
1046 if (Attr.isArgIdent(0)) {
1047 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1048 StringRef Param = Ident->Ident->getName();
1049 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1050 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1051 << Attr.getName() << Param;
1055 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1056 Attr.getName() << AANT_ArgumentIdentifier;
1060 D->addAttr(::new (S.Context)
1061 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1062 Attr.getAttributeSpellingListIndex()));
1065 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1066 const AttributeList &Attr) {
1067 // Remember this typedef decl, we will need it later for diagnostics.
1068 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1071 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1072 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1073 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1074 Attr.getAttributeSpellingListIndex()));
1075 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1076 // Report warning about changed offset in the newer compiler versions.
1077 if (!FD->getType()->isDependentType() &&
1078 !FD->getType()->isIncompleteType() && FD->isBitField() &&
1079 S.Context.getTypeAlign(FD->getType()) <= 8)
1080 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1082 FD->addAttr(::new (S.Context) PackedAttr(
1083 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1085 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1088 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1089 // The IBOutlet/IBOutletCollection attributes only apply to instance
1090 // variables or properties of Objective-C classes. The outlet must also
1091 // have an object reference type.
1092 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1093 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1094 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1095 << Attr.getName() << VD->getType() << 0;
1099 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1100 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1101 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1102 << Attr.getName() << PD->getType() << 1;
1107 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1114 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1115 if (!checkIBOutletCommon(S, D, Attr))
1118 D->addAttr(::new (S.Context)
1119 IBOutletAttr(Attr.getRange(), S.Context,
1120 Attr.getAttributeSpellingListIndex()));
1123 static void handleIBOutletCollection(Sema &S, Decl *D,
1124 const AttributeList &Attr) {
1126 // The iboutletcollection attribute can have zero or one arguments.
1127 if (Attr.getNumArgs() > 1) {
1128 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1129 << Attr.getName() << 1;
1133 if (!checkIBOutletCommon(S, D, Attr))
1138 if (Attr.hasParsedType())
1139 PT = Attr.getTypeArg();
1141 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1142 S.getScopeForContext(D->getDeclContext()->getParent()));
1144 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1149 TypeSourceInfo *QTLoc = nullptr;
1150 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1152 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1154 // Diagnose use of non-object type in iboutletcollection attribute.
1155 // FIXME. Gnu attribute extension ignores use of builtin types in
1156 // attributes. So, __attribute__((iboutletcollection(char))) will be
1157 // treated as __attribute__((iboutletcollection())).
1158 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1159 S.Diag(Attr.getLoc(),
1160 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1161 : diag::err_iboutletcollection_type) << QT;
1165 D->addAttr(::new (S.Context)
1166 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1167 Attr.getAttributeSpellingListIndex()));
1170 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1172 if (T->isReferenceType())
1175 T = T.getNonReferenceType();
1178 // The nonnull attribute, and other similar attributes, can be applied to a
1179 // transparent union that contains a pointer type.
1180 if (const RecordType *UT = T->getAsUnionType()) {
1181 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1182 RecordDecl *UD = UT->getDecl();
1183 for (const auto *I : UD->fields()) {
1184 QualType QT = I->getType();
1185 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1191 return T->isAnyPointerType() || T->isBlockPointerType();
1194 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1195 SourceRange AttrParmRange,
1196 SourceRange TypeRange,
1197 bool isReturnValue = false) {
1198 if (!S.isValidPointerAttrType(T)) {
1200 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1201 << Attr.getName() << AttrParmRange << TypeRange;
1203 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1204 << Attr.getName() << AttrParmRange << TypeRange << 0;
1210 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1211 SmallVector<unsigned, 8> NonNullArgs;
1212 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1213 Expr *Ex = Attr.getArgAsExpr(I);
1215 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1218 // Is the function argument a pointer type?
1219 if (Idx < getFunctionOrMethodNumParams(D) &&
1220 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1221 Ex->getSourceRange(),
1222 getFunctionOrMethodParamRange(D, Idx)))
1225 NonNullArgs.push_back(Idx);
1228 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1229 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1230 // check if the attribute came from a macro expansion or a template
1232 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1233 S.ActiveTemplateInstantiations.empty()) {
1234 bool AnyPointers = isFunctionOrMethodVariadic(D);
1235 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1236 I != E && !AnyPointers; ++I) {
1237 QualType T = getFunctionOrMethodParamType(D, I);
1238 if (T->isDependentType() || S.isValidPointerAttrType(T))
1243 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1246 unsigned *Start = NonNullArgs.data();
1247 unsigned Size = NonNullArgs.size();
1248 llvm::array_pod_sort(Start, Start + Size);
1249 D->addAttr(::new (S.Context)
1250 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1251 Attr.getAttributeSpellingListIndex()));
1254 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1255 const AttributeList &Attr) {
1256 if (Attr.getNumArgs() > 0) {
1257 if (D->getFunctionType()) {
1258 handleNonNullAttr(S, D, Attr);
1260 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1261 << D->getSourceRange();
1266 // Is the argument a pointer type?
1267 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1268 D->getSourceRange()))
1271 D->addAttr(::new (S.Context)
1272 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1273 Attr.getAttributeSpellingListIndex()));
1276 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1277 const AttributeList &Attr) {
1278 QualType ResultType = getFunctionOrMethodResultType(D);
1279 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1280 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1281 /* isReturnValue */ true))
1284 D->addAttr(::new (S.Context)
1285 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1286 Attr.getAttributeSpellingListIndex()));
1289 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1290 const AttributeList &Attr) {
1291 Expr *E = Attr.getArgAsExpr(0),
1292 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1293 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1294 Attr.getAttributeSpellingListIndex());
1297 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1298 Expr *OE, unsigned SpellingListIndex) {
1299 QualType ResultType = getFunctionOrMethodResultType(D);
1300 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1302 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1303 SourceLocation AttrLoc = AttrRange.getBegin();
1305 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1306 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1307 << &TmpAttr << AttrRange << SR;
1311 if (!E->isValueDependent()) {
1313 if (!E->isIntegerConstantExpr(I, Context)) {
1315 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1316 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1317 << E->getSourceRange();
1319 Diag(AttrLoc, diag::err_attribute_argument_type)
1320 << &TmpAttr << AANT_ArgumentIntegerConstant
1321 << E->getSourceRange();
1325 if (!I.isPowerOf2()) {
1326 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1327 << E->getSourceRange();
1333 if (!OE->isValueDependent()) {
1335 if (!OE->isIntegerConstantExpr(I, Context)) {
1336 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1337 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1338 << OE->getSourceRange();
1344 D->addAttr(::new (Context)
1345 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1348 /// Normalize the attribute, __foo__ becomes foo.
1349 /// Returns true if normalization was applied.
1350 static bool normalizeName(StringRef &AttrName) {
1351 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1352 AttrName.endswith("__")) {
1353 AttrName = AttrName.drop_front(2).drop_back(2);
1359 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1360 // This attribute must be applied to a function declaration. The first
1361 // argument to the attribute must be an identifier, the name of the resource,
1362 // for example: malloc. The following arguments must be argument indexes, the
1363 // arguments must be of integer type for Returns, otherwise of pointer type.
1364 // The difference between Holds and Takes is that a pointer may still be used
1365 // after being held. free() should be __attribute((ownership_takes)), whereas
1366 // a list append function may well be __attribute((ownership_holds)).
1368 if (!AL.isArgIdent(0)) {
1369 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1370 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1374 // Figure out our Kind.
1375 OwnershipAttr::OwnershipKind K =
1376 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1377 AL.getAttributeSpellingListIndex()).getOwnKind();
1381 case OwnershipAttr::Takes:
1382 case OwnershipAttr::Holds:
1383 if (AL.getNumArgs() < 2) {
1384 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1385 << AL.getName() << 2;
1389 case OwnershipAttr::Returns:
1390 if (AL.getNumArgs() > 2) {
1391 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1392 << AL.getName() << 1;
1398 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1400 StringRef ModuleName = Module->getName();
1401 if (normalizeName(ModuleName)) {
1402 Module = &S.PP.getIdentifierTable().get(ModuleName);
1405 SmallVector<unsigned, 8> OwnershipArgs;
1406 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1407 Expr *Ex = AL.getArgAsExpr(i);
1409 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1412 // Is the function argument a pointer type?
1413 QualType T = getFunctionOrMethodParamType(D, Idx);
1414 int Err = -1; // No error
1416 case OwnershipAttr::Takes:
1417 case OwnershipAttr::Holds:
1418 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1421 case OwnershipAttr::Returns:
1422 if (!T->isIntegerType())
1427 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1428 << Ex->getSourceRange();
1432 // Check we don't have a conflict with another ownership attribute.
1433 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1434 // Cannot have two ownership attributes of different kinds for the same
1436 if (I->getOwnKind() != K && I->args_end() !=
1437 std::find(I->args_begin(), I->args_end(), Idx)) {
1438 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1439 << AL.getName() << I;
1441 } else if (K == OwnershipAttr::Returns &&
1442 I->getOwnKind() == OwnershipAttr::Returns) {
1443 // A returns attribute conflicts with any other returns attribute using
1444 // a different index. Note, diagnostic reporting is 1-based, but stored
1445 // argument indexes are 0-based.
1446 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1447 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1448 << *(I->args_begin()) + 1;
1450 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1451 << (unsigned)Idx + 1 << Ex->getSourceRange();
1456 OwnershipArgs.push_back(Idx);
1459 unsigned* start = OwnershipArgs.data();
1460 unsigned size = OwnershipArgs.size();
1461 llvm::array_pod_sort(start, start + size);
1463 D->addAttr(::new (S.Context)
1464 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1465 AL.getAttributeSpellingListIndex()));
1468 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1469 // Check the attribute arguments.
1470 if (Attr.getNumArgs() > 1) {
1471 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1472 << Attr.getName() << 1;
1476 NamedDecl *nd = cast<NamedDecl>(D);
1480 // static int a __attribute__((weakref ("v2")));
1481 // static int b() __attribute__((weakref ("f3")));
1483 // and ignores the attributes of
1485 // static int a __attribute__((weakref ("v2")));
1488 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1489 if (!Ctx->isFileContext()) {
1490 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1495 // The GCC manual says
1497 // At present, a declaration to which `weakref' is attached can only
1502 // Without a TARGET,
1503 // given as an argument to `weakref' or to `alias', `weakref' is
1504 // equivalent to `weak'.
1506 // gcc 4.4.1 will accept
1507 // int a7 __attribute__((weakref));
1509 // int a7 __attribute__((weak));
1510 // This looks like a bug in gcc. We reject that for now. We should revisit
1511 // it if this behaviour is actually used.
1514 // static ((alias ("y"), weakref)).
1515 // Should we? How to check that weakref is before or after alias?
1517 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1518 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1519 // StringRef parameter it was given anyway.
1521 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1522 // GCC will accept anything as the argument of weakref. Should we
1523 // check for an existing decl?
1524 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1525 Attr.getAttributeSpellingListIndex()));
1527 D->addAttr(::new (S.Context)
1528 WeakRefAttr(Attr.getRange(), S.Context,
1529 Attr.getAttributeSpellingListIndex()));
1532 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1534 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1537 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1538 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1542 // Aliases should be on declarations, not definitions.
1543 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1544 if (FD->isThisDeclarationADefinition()) {
1545 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
1549 const auto *VD = cast<VarDecl>(D);
1550 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1551 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
1556 // FIXME: check if target symbol exists in current file
1558 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1559 Attr.getAttributeSpellingListIndex()));
1562 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1563 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1566 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1567 Attr.getAttributeSpellingListIndex()));
1570 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1571 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1574 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1575 Attr.getAttributeSpellingListIndex()));
1578 static void handleTLSModelAttr(Sema &S, Decl *D,
1579 const AttributeList &Attr) {
1581 SourceLocation LiteralLoc;
1582 // Check that it is a string.
1583 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1586 // Check that the value.
1587 if (Model != "global-dynamic" && Model != "local-dynamic"
1588 && Model != "initial-exec" && Model != "local-exec") {
1589 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1593 D->addAttr(::new (S.Context)
1594 TLSModelAttr(Attr.getRange(), S.Context, Model,
1595 Attr.getAttributeSpellingListIndex()));
1598 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1599 QualType ResultType = getFunctionOrMethodResultType(D);
1600 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1601 D->addAttr(::new (S.Context) RestrictAttr(
1602 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1606 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1607 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1610 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1611 if (S.LangOpts.CPlusPlus) {
1612 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1613 << Attr.getName() << AttributeLangSupport::Cpp;
1617 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1618 Attr.getAttributeSpellingListIndex()))
1622 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1623 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1627 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1628 Attr.getAttributeSpellingListIndex()));
1631 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1632 if (hasDeclarator(D)) return;
1634 if (S.CheckNoReturnAttr(attr)) return;
1636 if (!isa<ObjCMethodDecl>(D)) {
1637 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1638 << attr.getName() << ExpectedFunctionOrMethod;
1642 D->addAttr(::new (S.Context)
1643 NoReturnAttr(attr.getRange(), S.Context,
1644 attr.getAttributeSpellingListIndex()));
1647 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1648 if (!checkAttributeNumArgs(*this, attr, 0)) {
1656 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1657 const AttributeList &Attr) {
1659 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1660 // because 'analyzer_noreturn' does not impact the type.
1661 if (!isFunctionOrMethodOrBlock(D)) {
1662 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1663 if (!VD || (!VD->getType()->isBlockPointerType() &&
1664 !VD->getType()->isFunctionPointerType())) {
1665 S.Diag(Attr.getLoc(),
1666 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1667 : diag::warn_attribute_wrong_decl_type)
1668 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1673 D->addAttr(::new (S.Context)
1674 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1675 Attr.getAttributeSpellingListIndex()));
1678 // PS3 PPU-specific.
1679 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1681 Returning a Vector Class in Registers
1683 According to the PPU ABI specifications, a class with a single member of
1684 vector type is returned in memory when used as the return value of a function.
1685 This results in inefficient code when implementing vector classes. To return
1686 the value in a single vector register, add the vecreturn attribute to the
1687 class definition. This attribute is also applicable to struct types.
1693 __vector float xyzw;
1694 } __attribute__((vecreturn));
1696 Vector Add(Vector lhs, Vector rhs)
1699 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1700 return result; // This will be returned in a register
1703 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1704 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1708 RecordDecl *record = cast<RecordDecl>(D);
1711 if (!isa<CXXRecordDecl>(record)) {
1712 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1716 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1717 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1721 for (const auto *I : record->fields()) {
1722 if ((count == 1) || !I->getType()->isVectorType()) {
1723 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1729 D->addAttr(::new (S.Context)
1730 VecReturnAttr(Attr.getRange(), S.Context,
1731 Attr.getAttributeSpellingListIndex()));
1734 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1735 const AttributeList &Attr) {
1736 if (isa<ParmVarDecl>(D)) {
1737 // [[carries_dependency]] can only be applied to a parameter if it is a
1738 // parameter of a function declaration or lambda.
1739 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1740 S.Diag(Attr.getLoc(),
1741 diag::err_carries_dependency_param_not_function_decl);
1746 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1747 Attr.getRange(), S.Context,
1748 Attr.getAttributeSpellingListIndex()));
1751 static void handleNotTailCalledAttr(Sema &S, Decl *D,
1752 const AttributeList &Attr) {
1753 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1757 D->addAttr(::new (S.Context) NotTailCalledAttr(
1758 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1761 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1762 const AttributeList &Attr) {
1763 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1767 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1768 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1771 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1773 if (VD->hasLocalStorage()) {
1774 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1777 } else if (!isFunctionOrMethod(D)) {
1778 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1779 << Attr.getName() << ExpectedVariableOrFunction;
1783 D->addAttr(::new (S.Context)
1784 UsedAttr(Attr.getRange(), S.Context,
1785 Attr.getAttributeSpellingListIndex()));
1788 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1789 uint32_t priority = ConstructorAttr::DefaultPriority;
1790 if (Attr.getNumArgs() &&
1791 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1794 D->addAttr(::new (S.Context)
1795 ConstructorAttr(Attr.getRange(), S.Context, priority,
1796 Attr.getAttributeSpellingListIndex()));
1799 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1800 uint32_t priority = DestructorAttr::DefaultPriority;
1801 if (Attr.getNumArgs() &&
1802 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1805 D->addAttr(::new (S.Context)
1806 DestructorAttr(Attr.getRange(), S.Context, priority,
1807 Attr.getAttributeSpellingListIndex()));
1810 template <typename AttrTy>
1811 static void handleAttrWithMessage(Sema &S, Decl *D,
1812 const AttributeList &Attr) {
1813 // Handle the case where the attribute has a text message.
1815 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1818 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1819 Attr.getAttributeSpellingListIndex()));
1822 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1823 const AttributeList &Attr) {
1824 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1825 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1826 << Attr.getName() << Attr.getRange();
1830 D->addAttr(::new (S.Context)
1831 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1832 Attr.getAttributeSpellingListIndex()));
1835 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1836 IdentifierInfo *Platform,
1837 VersionTuple Introduced,
1838 VersionTuple Deprecated,
1839 VersionTuple Obsoleted) {
1840 StringRef PlatformName
1841 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1842 if (PlatformName.empty())
1843 PlatformName = Platform->getName();
1845 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1846 // of these steps are needed).
1847 if (!Introduced.empty() && !Deprecated.empty() &&
1848 !(Introduced <= Deprecated)) {
1849 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1850 << 1 << PlatformName << Deprecated.getAsString()
1851 << 0 << Introduced.getAsString();
1855 if (!Introduced.empty() && !Obsoleted.empty() &&
1856 !(Introduced <= Obsoleted)) {
1857 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1858 << 2 << PlatformName << Obsoleted.getAsString()
1859 << 0 << Introduced.getAsString();
1863 if (!Deprecated.empty() && !Obsoleted.empty() &&
1864 !(Deprecated <= Obsoleted)) {
1865 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1866 << 2 << PlatformName << Obsoleted.getAsString()
1867 << 1 << Deprecated.getAsString();
1874 /// \brief Check whether the two versions match.
1876 /// If either version tuple is empty, then they are assumed to match. If
1877 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1878 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1879 bool BeforeIsOkay) {
1880 if (X.empty() || Y.empty())
1886 if (BeforeIsOkay && X < Y)
1892 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1893 IdentifierInfo *Platform,
1894 VersionTuple Introduced,
1895 VersionTuple Deprecated,
1896 VersionTuple Obsoleted,
1899 AvailabilityMergeKind AMK,
1900 unsigned AttrSpellingListIndex) {
1901 VersionTuple MergedIntroduced = Introduced;
1902 VersionTuple MergedDeprecated = Deprecated;
1903 VersionTuple MergedObsoleted = Obsoleted;
1904 bool FoundAny = false;
1905 bool OverrideOrImpl = false;
1908 case AMK_Redeclaration:
1909 OverrideOrImpl = false;
1913 case AMK_ProtocolImplementation:
1914 OverrideOrImpl = true;
1918 if (D->hasAttrs()) {
1919 AttrVec &Attrs = D->getAttrs();
1920 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1921 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1927 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1928 if (OldPlatform != Platform) {
1933 // If there is an existing availability attribute for this platform that
1934 // is explicit and the new one is implicit use the explicit one and
1935 // discard the new implicit attribute.
1936 if (OldAA->getRange().isValid() && Range.isInvalid()) {
1940 // If there is an existing attribute for this platform that is implicit
1941 // and the new attribute is explicit then erase the old one and
1942 // continue processing the attributes.
1943 if (Range.isValid() && OldAA->getRange().isInvalid()) {
1944 Attrs.erase(Attrs.begin() + i);
1950 VersionTuple OldIntroduced = OldAA->getIntroduced();
1951 VersionTuple OldDeprecated = OldAA->getDeprecated();
1952 VersionTuple OldObsoleted = OldAA->getObsoleted();
1953 bool OldIsUnavailable = OldAA->getUnavailable();
1955 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
1956 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
1957 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
1958 !(OldIsUnavailable == IsUnavailable ||
1959 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
1960 if (OverrideOrImpl) {
1962 VersionTuple FirstVersion;
1963 VersionTuple SecondVersion;
1964 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
1966 FirstVersion = OldIntroduced;
1967 SecondVersion = Introduced;
1968 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
1970 FirstVersion = Deprecated;
1971 SecondVersion = OldDeprecated;
1972 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
1974 FirstVersion = Obsoleted;
1975 SecondVersion = OldObsoleted;
1979 Diag(OldAA->getLocation(),
1980 diag::warn_mismatched_availability_override_unavail)
1981 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1982 << (AMK == AMK_Override);
1984 Diag(OldAA->getLocation(),
1985 diag::warn_mismatched_availability_override)
1987 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
1988 << FirstVersion.getAsString() << SecondVersion.getAsString()
1989 << (AMK == AMK_Override);
1991 if (AMK == AMK_Override)
1992 Diag(Range.getBegin(), diag::note_overridden_method);
1994 Diag(Range.getBegin(), diag::note_protocol_method);
1996 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
1997 Diag(Range.getBegin(), diag::note_previous_attribute);
2000 Attrs.erase(Attrs.begin() + i);
2005 VersionTuple MergedIntroduced2 = MergedIntroduced;
2006 VersionTuple MergedDeprecated2 = MergedDeprecated;
2007 VersionTuple MergedObsoleted2 = MergedObsoleted;
2009 if (MergedIntroduced2.empty())
2010 MergedIntroduced2 = OldIntroduced;
2011 if (MergedDeprecated2.empty())
2012 MergedDeprecated2 = OldDeprecated;
2013 if (MergedObsoleted2.empty())
2014 MergedObsoleted2 = OldObsoleted;
2016 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2017 MergedIntroduced2, MergedDeprecated2,
2018 MergedObsoleted2)) {
2019 Attrs.erase(Attrs.begin() + i);
2024 MergedIntroduced = MergedIntroduced2;
2025 MergedDeprecated = MergedDeprecated2;
2026 MergedObsoleted = MergedObsoleted2;
2032 MergedIntroduced == Introduced &&
2033 MergedDeprecated == Deprecated &&
2034 MergedObsoleted == Obsoleted)
2037 // Only create a new attribute if !OverrideOrImpl, but we want to do
2039 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2040 MergedDeprecated, MergedObsoleted) &&
2042 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
2043 Introduced, Deprecated,
2044 Obsoleted, IsUnavailable, Message,
2045 AttrSpellingListIndex);
2050 static void handleAvailabilityAttr(Sema &S, Decl *D,
2051 const AttributeList &Attr) {
2052 if (!checkAttributeNumArgs(S, Attr, 1))
2054 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2055 unsigned Index = Attr.getAttributeSpellingListIndex();
2057 IdentifierInfo *II = Platform->Ident;
2058 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2059 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2062 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2064 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2068 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2069 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2070 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2071 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2073 if (const StringLiteral *SE =
2074 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2075 Str = SE->getString();
2077 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2085 D->addAttr(NewAttr);
2087 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2088 // matches before the start of the watchOS platform.
2089 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2090 IdentifierInfo *NewII = nullptr;
2091 if (II->getName() == "ios")
2092 NewII = &S.Context.Idents.get("watchos");
2093 else if (II->getName() == "ios_app_extension")
2094 NewII = &S.Context.Idents.get("watchos_app_extension");
2097 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2098 if (Version.empty())
2100 auto Major = Version.getMajor();
2101 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2102 if (NewMajor >= 2) {
2103 if (Version.getMinor().hasValue()) {
2104 if (Version.getSubminor().hasValue())
2105 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2106 Version.getSubminor().getValue());
2108 return VersionTuple(NewMajor, Version.getMinor().getValue());
2112 return VersionTuple(2, 0);
2115 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2116 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2117 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2119 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2129 D->addAttr(NewAttr);
2131 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2132 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2133 // matches before the start of the tvOS platform.
2134 IdentifierInfo *NewII = nullptr;
2135 if (II->getName() == "ios")
2136 NewII = &S.Context.Idents.get("tvos");
2137 else if (II->getName() == "ios_app_extension")
2138 NewII = &S.Context.Idents.get("tvos_app_extension");
2141 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2151 D->addAttr(NewAttr);
2157 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2158 typename T::VisibilityType value,
2159 unsigned attrSpellingListIndex) {
2160 T *existingAttr = D->getAttr<T>();
2162 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2163 if (existingValue == value)
2165 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2166 S.Diag(range.getBegin(), diag::note_previous_attribute);
2169 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2172 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2173 VisibilityAttr::VisibilityType Vis,
2174 unsigned AttrSpellingListIndex) {
2175 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2176 AttrSpellingListIndex);
2179 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2180 TypeVisibilityAttr::VisibilityType Vis,
2181 unsigned AttrSpellingListIndex) {
2182 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2183 AttrSpellingListIndex);
2186 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2187 bool isTypeVisibility) {
2188 // Visibility attributes don't mean anything on a typedef.
2189 if (isa<TypedefNameDecl>(D)) {
2190 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2195 // 'type_visibility' can only go on a type or namespace.
2196 if (isTypeVisibility &&
2197 !(isa<TagDecl>(D) ||
2198 isa<ObjCInterfaceDecl>(D) ||
2199 isa<NamespaceDecl>(D))) {
2200 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2201 << Attr.getName() << ExpectedTypeOrNamespace;
2205 // Check that the argument is a string literal.
2207 SourceLocation LiteralLoc;
2208 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2211 VisibilityAttr::VisibilityType type;
2212 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2213 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2214 << Attr.getName() << TypeStr;
2218 // Complain about attempts to use protected visibility on targets
2219 // (like Darwin) that don't support it.
2220 if (type == VisibilityAttr::Protected &&
2221 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2222 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2223 type = VisibilityAttr::Default;
2226 unsigned Index = Attr.getAttributeSpellingListIndex();
2227 clang::Attr *newAttr;
2228 if (isTypeVisibility) {
2229 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2230 (TypeVisibilityAttr::VisibilityType) type,
2233 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2236 D->addAttr(newAttr);
2239 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2240 const AttributeList &Attr) {
2241 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2242 if (!Attr.isArgIdent(0)) {
2243 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2244 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2248 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2249 ObjCMethodFamilyAttr::FamilyKind F;
2250 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2251 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2256 if (F == ObjCMethodFamilyAttr::OMF_init &&
2257 !method->getReturnType()->isObjCObjectPointerType()) {
2258 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2259 << method->getReturnType();
2260 // Ignore the attribute.
2264 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2266 Attr.getAttributeSpellingListIndex()));
2269 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2270 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2271 QualType T = TD->getUnderlyingType();
2272 if (!T->isCARCBridgableType()) {
2273 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2277 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2278 QualType T = PD->getType();
2279 if (!T->isCARCBridgableType()) {
2280 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2285 // It is okay to include this attribute on properties, e.g.:
2287 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2289 // In this case it follows tradition and suppresses an error in the above
2291 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2293 D->addAttr(::new (S.Context)
2294 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2295 Attr.getAttributeSpellingListIndex()));
2298 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2299 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2300 QualType T = TD->getUnderlyingType();
2301 if (!T->isObjCObjectPointerType()) {
2302 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2306 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2309 D->addAttr(::new (S.Context)
2310 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2311 Attr.getAttributeSpellingListIndex()));
2314 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2315 if (!Attr.isArgIdent(0)) {
2316 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2317 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2321 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2322 BlocksAttr::BlockType type;
2323 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2324 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2325 << Attr.getName() << II;
2329 D->addAttr(::new (S.Context)
2330 BlocksAttr(Attr.getRange(), S.Context, type,
2331 Attr.getAttributeSpellingListIndex()));
2334 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2335 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2336 if (Attr.getNumArgs() > 0) {
2337 Expr *E = Attr.getArgAsExpr(0);
2338 llvm::APSInt Idx(32);
2339 if (E->isTypeDependent() || E->isValueDependent() ||
2340 !E->isIntegerConstantExpr(Idx, S.Context)) {
2341 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2342 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2343 << E->getSourceRange();
2347 if (Idx.isSigned() && Idx.isNegative()) {
2348 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2349 << E->getSourceRange();
2353 sentinel = Idx.getZExtValue();
2356 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2357 if (Attr.getNumArgs() > 1) {
2358 Expr *E = Attr.getArgAsExpr(1);
2359 llvm::APSInt Idx(32);
2360 if (E->isTypeDependent() || E->isValueDependent() ||
2361 !E->isIntegerConstantExpr(Idx, S.Context)) {
2362 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2363 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2364 << E->getSourceRange();
2367 nullPos = Idx.getZExtValue();
2369 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2370 // FIXME: This error message could be improved, it would be nice
2371 // to say what the bounds actually are.
2372 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2373 << E->getSourceRange();
2378 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2379 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2380 if (isa<FunctionNoProtoType>(FT)) {
2381 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2385 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2386 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2389 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2390 if (!MD->isVariadic()) {
2391 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2394 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2395 if (!BD->isVariadic()) {
2396 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2399 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2400 QualType Ty = V->getType();
2401 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2402 const FunctionType *FT = Ty->isFunctionPointerType()
2403 ? D->getFunctionType()
2404 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2405 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2406 int m = Ty->isFunctionPointerType() ? 0 : 1;
2407 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2411 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2412 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2416 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2417 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2420 D->addAttr(::new (S.Context)
2421 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2422 Attr.getAttributeSpellingListIndex()));
2425 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2426 if (D->getFunctionType() &&
2427 D->getFunctionType()->getReturnType()->isVoidType()) {
2428 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2429 << Attr.getName() << 0;
2432 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2433 if (MD->getReturnType()->isVoidType()) {
2434 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2435 << Attr.getName() << 1;
2439 D->addAttr(::new (S.Context)
2440 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2441 Attr.getAttributeSpellingListIndex()));
2444 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2445 // weak_import only applies to variable & function declarations.
2447 if (!D->canBeWeakImported(isDef)) {
2449 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2451 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2452 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2453 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2454 // Nothing to warn about here.
2456 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2457 << Attr.getName() << ExpectedVariableOrFunction;
2462 D->addAttr(::new (S.Context)
2463 WeakImportAttr(Attr.getRange(), S.Context,
2464 Attr.getAttributeSpellingListIndex()));
2467 // Handles reqd_work_group_size and work_group_size_hint.
2468 template <typename WorkGroupAttr>
2469 static void handleWorkGroupSize(Sema &S, Decl *D,
2470 const AttributeList &Attr) {
2472 for (unsigned i = 0; i < 3; ++i) {
2473 const Expr *E = Attr.getArgAsExpr(i);
2474 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2476 if (WGSize[i] == 0) {
2477 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2478 << Attr.getName() << E->getSourceRange();
2483 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2484 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2485 Existing->getYDim() == WGSize[1] &&
2486 Existing->getZDim() == WGSize[2]))
2487 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2489 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2490 WGSize[0], WGSize[1], WGSize[2],
2491 Attr.getAttributeSpellingListIndex()));
2494 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2495 if (!Attr.hasParsedType()) {
2496 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2497 << Attr.getName() << 1;
2501 TypeSourceInfo *ParmTSI = nullptr;
2502 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2503 assert(ParmTSI && "no type source info for attribute argument");
2505 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2506 (ParmType->isBooleanType() ||
2507 !ParmType->isIntegralType(S.getASTContext()))) {
2508 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2513 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2514 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2515 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2520 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2522 Attr.getAttributeSpellingListIndex()));
2525 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2527 unsigned AttrSpellingListIndex) {
2528 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2529 if (ExistingAttr->getName() == Name)
2531 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2532 Diag(Range.getBegin(), diag::note_previous_attribute);
2535 return ::new (Context) SectionAttr(Range, Context, Name,
2536 AttrSpellingListIndex);
2539 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2540 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2541 if (!Error.empty()) {
2542 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2548 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2549 // Make sure that there is a string literal as the sections's single
2552 SourceLocation LiteralLoc;
2553 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2556 if (!S.checkSectionName(LiteralLoc, Str))
2559 // If the target wants to validate the section specifier, make it happen.
2560 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2561 if (!Error.empty()) {
2562 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2567 unsigned Index = Attr.getAttributeSpellingListIndex();
2568 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2570 D->addAttr(NewAttr);
2573 // Check for things we'd like to warn about, no errors or validation for now.
2574 // TODO: Validation should use a backend target library that specifies
2575 // the allowable subtarget features and cpus. We could use something like a
2576 // TargetCodeGenInfo hook here to do validation.
2577 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2578 for (auto Str : {"tune=", "fpmath="})
2579 if (AttrStr.find(Str) != StringRef::npos)
2580 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2583 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2585 SourceLocation LiteralLoc;
2586 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2588 S.checkTargetAttr(LiteralLoc, Str);
2589 unsigned Index = Attr.getAttributeSpellingListIndex();
2590 TargetAttr *NewAttr =
2591 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2592 D->addAttr(NewAttr);
2596 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2597 VarDecl *VD = cast<VarDecl>(D);
2598 if (!VD->hasLocalStorage()) {
2599 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2603 Expr *E = Attr.getArgAsExpr(0);
2604 SourceLocation Loc = E->getExprLoc();
2605 FunctionDecl *FD = nullptr;
2606 DeclarationNameInfo NI;
2608 // gcc only allows for simple identifiers. Since we support more than gcc, we
2609 // will warn the user.
2610 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2611 if (DRE->hasQualifier())
2612 S.Diag(Loc, diag::warn_cleanup_ext);
2613 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2614 NI = DRE->getNameInfo();
2616 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2620 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2621 if (ULE->hasExplicitTemplateArgs())
2622 S.Diag(Loc, diag::warn_cleanup_ext);
2623 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2624 NI = ULE->getNameInfo();
2626 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2628 if (ULE->getType() == S.Context.OverloadTy)
2629 S.NoteAllOverloadCandidates(ULE);
2633 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2637 if (FD->getNumParams() != 1) {
2638 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2643 // We're currently more strict than GCC about what function types we accept.
2644 // If this ever proves to be a problem it should be easy to fix.
2645 QualType Ty = S.Context.getPointerType(VD->getType());
2646 QualType ParamTy = FD->getParamDecl(0)->getType();
2647 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2648 ParamTy, Ty) != Sema::Compatible) {
2649 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2650 << NI.getName() << ParamTy << Ty;
2654 D->addAttr(::new (S.Context)
2655 CleanupAttr(Attr.getRange(), S.Context, FD,
2656 Attr.getAttributeSpellingListIndex()));
2659 /// Handle __attribute__((format_arg((idx)))) attribute based on
2660 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2661 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2662 Expr *IdxExpr = Attr.getArgAsExpr(0);
2664 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2667 // Make sure the format string is really a string.
2668 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2670 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2671 if (NotNSStringTy &&
2672 !isCFStringType(Ty, S.Context) &&
2673 (!Ty->isPointerType() ||
2674 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2675 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2676 << "a string type" << IdxExpr->getSourceRange()
2677 << getFunctionOrMethodParamRange(D, 0);
2680 Ty = getFunctionOrMethodResultType(D);
2681 if (!isNSStringType(Ty, S.Context) &&
2682 !isCFStringType(Ty, S.Context) &&
2683 (!Ty->isPointerType() ||
2684 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2685 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2686 << (NotNSStringTy ? "string type" : "NSString")
2687 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2691 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2692 // because that has corrected for the implicit this parameter, and is zero-
2693 // based. The attribute expects what the user wrote explicitly.
2695 IdxExpr->EvaluateAsInt(Val, S.Context);
2697 D->addAttr(::new (S.Context)
2698 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2699 Attr.getAttributeSpellingListIndex()));
2702 enum FormatAttrKind {
2711 /// getFormatAttrKind - Map from format attribute names to supported format
2713 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2714 return llvm::StringSwitch<FormatAttrKind>(Format)
2715 // Check for formats that get handled specially.
2716 .Case("NSString", NSStringFormat)
2717 .Case("CFString", CFStringFormat)
2718 .Case("strftime", StrftimeFormat)
2720 // Otherwise, check for supported formats.
2721 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2722 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2723 .Case("kprintf", SupportedFormat) // OpenBSD.
2724 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2725 .Case("os_trace", SupportedFormat)
2727 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2728 .Default(InvalidFormat);
2731 /// Handle __attribute__((init_priority(priority))) attributes based on
2732 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2733 static void handleInitPriorityAttr(Sema &S, Decl *D,
2734 const AttributeList &Attr) {
2735 if (!S.getLangOpts().CPlusPlus) {
2736 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2740 if (S.getCurFunctionOrMethodDecl()) {
2741 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2745 QualType T = cast<VarDecl>(D)->getType();
2746 if (S.Context.getAsArrayType(T))
2747 T = S.Context.getBaseElementType(T);
2748 if (!T->getAs<RecordType>()) {
2749 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2754 Expr *E = Attr.getArgAsExpr(0);
2755 uint32_t prioritynum;
2756 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2761 if (prioritynum < 101 || prioritynum > 65535) {
2762 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2763 << E->getSourceRange() << Attr.getName() << 101 << 65535;
2767 D->addAttr(::new (S.Context)
2768 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2769 Attr.getAttributeSpellingListIndex()));
2772 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2773 IdentifierInfo *Format, int FormatIdx,
2775 unsigned AttrSpellingListIndex) {
2776 // Check whether we already have an equivalent format attribute.
2777 for (auto *F : D->specific_attrs<FormatAttr>()) {
2778 if (F->getType() == Format &&
2779 F->getFormatIdx() == FormatIdx &&
2780 F->getFirstArg() == FirstArg) {
2781 // If we don't have a valid location for this attribute, adopt the
2783 if (F->getLocation().isInvalid())
2789 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2790 FirstArg, AttrSpellingListIndex);
2793 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2794 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2795 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2796 if (!Attr.isArgIdent(0)) {
2797 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2798 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2802 // In C++ the implicit 'this' function parameter also counts, and they are
2803 // counted from one.
2804 bool HasImplicitThisParam = isInstanceMethod(D);
2805 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2807 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2808 StringRef Format = II->getName();
2810 if (normalizeName(Format)) {
2811 // If we've modified the string name, we need a new identifier for it.
2812 II = &S.Context.Idents.get(Format);
2815 // Check for supported formats.
2816 FormatAttrKind Kind = getFormatAttrKind(Format);
2818 if (Kind == IgnoredFormat)
2821 if (Kind == InvalidFormat) {
2822 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2823 << Attr.getName() << II->getName();
2827 // checks for the 2nd argument
2828 Expr *IdxExpr = Attr.getArgAsExpr(1);
2830 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2833 if (Idx < 1 || Idx > NumArgs) {
2834 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2835 << Attr.getName() << 2 << IdxExpr->getSourceRange();
2839 // FIXME: Do we need to bounds check?
2840 unsigned ArgIdx = Idx - 1;
2842 if (HasImplicitThisParam) {
2844 S.Diag(Attr.getLoc(),
2845 diag::err_format_attribute_implicit_this_format_string)
2846 << IdxExpr->getSourceRange();
2852 // make sure the format string is really a string
2853 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2855 if (Kind == CFStringFormat) {
2856 if (!isCFStringType(Ty, S.Context)) {
2857 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2858 << "a CFString" << IdxExpr->getSourceRange()
2859 << getFunctionOrMethodParamRange(D, ArgIdx);
2862 } else if (Kind == NSStringFormat) {
2863 // FIXME: do we need to check if the type is NSString*? What are the
2865 if (!isNSStringType(Ty, S.Context)) {
2866 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2867 << "an NSString" << IdxExpr->getSourceRange()
2868 << getFunctionOrMethodParamRange(D, ArgIdx);
2871 } else if (!Ty->isPointerType() ||
2872 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2873 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2874 << "a string type" << IdxExpr->getSourceRange()
2875 << getFunctionOrMethodParamRange(D, ArgIdx);
2879 // check the 3rd argument
2880 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2882 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2885 // check if the function is variadic if the 3rd argument non-zero
2886 if (FirstArg != 0) {
2887 if (isFunctionOrMethodVariadic(D)) {
2888 ++NumArgs; // +1 for ...
2890 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2895 // strftime requires FirstArg to be 0 because it doesn't read from any
2896 // variable the input is just the current time + the format string.
2897 if (Kind == StrftimeFormat) {
2898 if (FirstArg != 0) {
2899 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2900 << FirstArgExpr->getSourceRange();
2903 // if 0 it disables parameter checking (to use with e.g. va_list)
2904 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2905 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2906 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2910 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2912 Attr.getAttributeSpellingListIndex());
2914 D->addAttr(NewAttr);
2917 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2918 const AttributeList &Attr) {
2919 // Try to find the underlying union declaration.
2920 RecordDecl *RD = nullptr;
2921 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2922 if (TD && TD->getUnderlyingType()->isUnionType())
2923 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2925 RD = dyn_cast<RecordDecl>(D);
2927 if (!RD || !RD->isUnion()) {
2928 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2929 << Attr.getName() << ExpectedUnion;
2933 if (!RD->isCompleteDefinition()) {
2934 S.Diag(Attr.getLoc(),
2935 diag::warn_transparent_union_attribute_not_definition);
2939 RecordDecl::field_iterator Field = RD->field_begin(),
2940 FieldEnd = RD->field_end();
2941 if (Field == FieldEnd) {
2942 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2946 FieldDecl *FirstField = *Field;
2947 QualType FirstType = FirstField->getType();
2948 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2949 S.Diag(FirstField->getLocation(),
2950 diag::warn_transparent_union_attribute_floating)
2951 << FirstType->isVectorType() << FirstType;
2955 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2956 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2957 for (; Field != FieldEnd; ++Field) {
2958 QualType FieldType = Field->getType();
2959 // FIXME: this isn't fully correct; we also need to test whether the
2960 // members of the union would all have the same calling convention as the
2961 // first member of the union. Checking just the size and alignment isn't
2962 // sufficient (consider structs passed on the stack instead of in registers
2964 if (S.Context.getTypeSize(FieldType) != FirstSize ||
2965 S.Context.getTypeAlign(FieldType) > FirstAlign) {
2966 // Warn if we drop the attribute.
2967 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2968 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2969 : S.Context.getTypeAlign(FieldType);
2970 S.Diag(Field->getLocation(),
2971 diag::warn_transparent_union_attribute_field_size_align)
2972 << isSize << Field->getDeclName() << FieldBits;
2973 unsigned FirstBits = isSize? FirstSize : FirstAlign;
2974 S.Diag(FirstField->getLocation(),
2975 diag::note_transparent_union_first_field_size_align)
2976 << isSize << FirstBits;
2981 RD->addAttr(::new (S.Context)
2982 TransparentUnionAttr(Attr.getRange(), S.Context,
2983 Attr.getAttributeSpellingListIndex()));
2986 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2987 // Make sure that there is a string literal as the annotation's single
2990 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2993 // Don't duplicate annotations that are already set.
2994 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
2995 if (I->getAnnotation() == Str)
2999 D->addAttr(::new (S.Context)
3000 AnnotateAttr(Attr.getRange(), S.Context, Str,
3001 Attr.getAttributeSpellingListIndex()));
3004 static void handleAlignValueAttr(Sema &S, Decl *D,
3005 const AttributeList &Attr) {
3006 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3007 Attr.getAttributeSpellingListIndex());
3010 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3011 unsigned SpellingListIndex) {
3012 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3013 SourceLocation AttrLoc = AttrRange.getBegin();
3016 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3017 T = TD->getUnderlyingType();
3018 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3021 llvm_unreachable("Unknown decl type for align_value");
3023 if (!T->isDependentType() && !T->isAnyPointerType() &&
3024 !T->isReferenceType() && !T->isMemberPointerType()) {
3025 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3026 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3030 if (!E->isValueDependent()) {
3031 llvm::APSInt Alignment;
3033 = VerifyIntegerConstantExpression(E, &Alignment,
3034 diag::err_align_value_attribute_argument_not_int,
3035 /*AllowFold*/ false);
3036 if (ICE.isInvalid())
3039 if (!Alignment.isPowerOf2()) {
3040 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3041 << E->getSourceRange();
3045 D->addAttr(::new (Context)
3046 AlignValueAttr(AttrRange, Context, ICE.get(),
3047 SpellingListIndex));
3051 // Save dependent expressions in the AST to be instantiated.
3052 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3056 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3057 // check the attribute arguments.
3058 if (Attr.getNumArgs() > 1) {
3059 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3060 << Attr.getName() << 1;
3064 if (Attr.getNumArgs() == 0) {
3065 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3066 true, nullptr, Attr.getAttributeSpellingListIndex()));
3070 Expr *E = Attr.getArgAsExpr(0);
3071 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3072 S.Diag(Attr.getEllipsisLoc(),
3073 diag::err_pack_expansion_without_parameter_packs);
3077 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3080 if (E->isValueDependent()) {
3081 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3082 if (!TND->getUnderlyingType()->isDependentType()) {
3083 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3084 << E->getSourceRange();
3090 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3091 Attr.isPackExpansion());
3094 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3095 unsigned SpellingListIndex, bool IsPackExpansion) {
3096 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3097 SourceLocation AttrLoc = AttrRange.getBegin();
3099 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3100 if (TmpAttr.isAlignas()) {
3101 // C++11 [dcl.align]p1:
3102 // An alignment-specifier may be applied to a variable or to a class
3103 // data member, but it shall not be applied to a bit-field, a function
3104 // parameter, the formal parameter of a catch clause, or a variable
3105 // declared with the register storage class specifier. An
3106 // alignment-specifier may also be applied to the declaration of a class
3107 // or enumeration type.
3109 // An alignment attribute shall not be specified in a declaration of
3110 // a typedef, or a bit-field, or a function, or a parameter, or an
3111 // object declared with the register storage-class specifier.
3113 if (isa<ParmVarDecl>(D)) {
3115 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3116 if (VD->getStorageClass() == SC_Register)
3118 if (VD->isExceptionVariable())
3120 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3121 if (FD->isBitField())
3123 } else if (!isa<TagDecl>(D)) {
3124 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3125 << (TmpAttr.isC11() ? ExpectedVariableOrField
3126 : ExpectedVariableFieldOrTag);
3129 if (DiagKind != -1) {
3130 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3131 << &TmpAttr << DiagKind;
3136 if (E->isTypeDependent() || E->isValueDependent()) {
3137 // Save dependent expressions in the AST to be instantiated.
3138 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3139 AA->setPackExpansion(IsPackExpansion);
3144 // FIXME: Cache the number on the Attr object?
3145 llvm::APSInt Alignment;
3147 = VerifyIntegerConstantExpression(E, &Alignment,
3148 diag::err_aligned_attribute_argument_not_int,
3149 /*AllowFold*/ false);
3150 if (ICE.isInvalid())
3153 uint64_t AlignVal = Alignment.getZExtValue();
3155 // C++11 [dcl.align]p2:
3156 // -- if the constant expression evaluates to zero, the alignment
3157 // specifier shall have no effect
3159 // An alignment specification of zero has no effect.
3160 if (!(TmpAttr.isAlignas() && !Alignment)) {
3161 if (!llvm::isPowerOf2_64(AlignVal)) {
3162 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3163 << E->getSourceRange();
3168 // Alignment calculations can wrap around if it's greater than 2**28.
3169 unsigned MaxValidAlignment =
3170 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3172 if (AlignVal > MaxValidAlignment) {
3173 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3174 << E->getSourceRange();
3178 if (Context.getTargetInfo().isTLSSupported()) {
3179 unsigned MaxTLSAlign =
3180 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3182 auto *VD = dyn_cast<VarDecl>(D);
3183 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3184 VD->getTLSKind() != VarDecl::TLS_None) {
3185 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3186 << (unsigned)AlignVal << VD << MaxTLSAlign;
3191 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3192 ICE.get(), SpellingListIndex);
3193 AA->setPackExpansion(IsPackExpansion);
3197 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3198 unsigned SpellingListIndex, bool IsPackExpansion) {
3199 // FIXME: Cache the number on the Attr object if non-dependent?
3200 // FIXME: Perform checking of type validity
3201 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3203 AA->setPackExpansion(IsPackExpansion);
3207 void Sema::CheckAlignasUnderalignment(Decl *D) {
3208 assert(D->hasAttrs() && "no attributes on decl");
3210 QualType UnderlyingTy, DiagTy;
3211 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3212 UnderlyingTy = DiagTy = VD->getType();
3214 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3215 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3216 UnderlyingTy = ED->getIntegerType();
3218 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3221 // C++11 [dcl.align]p5, C11 6.7.5/4:
3222 // The combined effect of all alignment attributes in a declaration shall
3223 // not specify an alignment that is less strict than the alignment that
3224 // would otherwise be required for the entity being declared.
3225 AlignedAttr *AlignasAttr = nullptr;
3227 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3228 if (I->isAlignmentDependent())
3232 Align = std::max(Align, I->getAlignment(Context));
3235 if (AlignasAttr && Align) {
3236 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3237 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3238 if (NaturalAlign > RequestedAlign)
3239 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3240 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3244 bool Sema::checkMSInheritanceAttrOnDefinition(
3245 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3246 MSInheritanceAttr::Spelling SemanticSpelling) {
3247 assert(RD->hasDefinition() && "RD has no definition!");
3249 // We may not have seen base specifiers or any virtual methods yet. We will
3250 // have to wait until the record is defined to catch any mismatches.
3251 if (!RD->getDefinition()->isCompleteDefinition())
3254 // The unspecified model never matches what a definition could need.
3255 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3259 if (RD->calculateInheritanceModel() == SemanticSpelling)
3262 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3266 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3267 << 0 /*definition*/;
3268 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3269 << RD->getNameAsString();
3273 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3275 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3276 bool &IntegerMode, bool &ComplexMode) {
3277 switch (Str.size()) {
3299 if (Str[1] == 'F') {
3300 IntegerMode = false;
3301 } else if (Str[1] == 'C') {
3302 IntegerMode = false;
3304 } else if (Str[1] != 'I') {
3309 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3310 // pointer on PIC16 and other embedded platforms.
3312 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3313 else if (Str == "byte")
3314 DestWidth = S.Context.getTargetInfo().getCharWidth();
3317 if (Str == "pointer")
3318 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3321 if (Str == "unwind_word")
3322 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3327 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3330 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3331 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3332 /// HImode, not an intermediate pointer.
3333 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3334 // This attribute isn't documented, but glibc uses it. It changes
3335 // the width of an int or unsigned int to the specified size.
3336 if (!Attr.isArgIdent(0)) {
3337 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3338 << AANT_ArgumentIdentifier;
3342 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3343 StringRef Str = Name->getName();
3347 unsigned DestWidth = 0;
3348 bool IntegerMode = true;
3349 bool ComplexMode = false;
3350 llvm::APInt VectorSize(64, 0);
3351 if (Str.size() >= 4 && Str[0] == 'V') {
3352 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3353 size_t StrSize = Str.size();
3354 size_t VectorStringLength = 0;
3355 while ((VectorStringLength + 1) < StrSize &&
3356 isdigit(Str[VectorStringLength + 1]))
3357 ++VectorStringLength;
3358 if (VectorStringLength &&
3359 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3360 VectorSize.isPowerOf2()) {
3361 parseModeAttrArg(S, Str.substr(VectorStringLength + 1), DestWidth,
3362 IntegerMode, ComplexMode);
3363 S.Diag(Attr.getLoc(), diag::warn_vector_mode_deprecated);
3370 parseModeAttrArg(S, Str, DestWidth, IntegerMode, ComplexMode);
3373 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3374 OldTy = TD->getUnderlyingType();
3375 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3376 OldTy = VD->getType();
3378 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3379 << Attr.getName() << Attr.getRange();
3383 // Base type can also be a vector type (see PR17453).
3384 // Distinguish between base type and base element type.
3385 QualType OldElemTy = OldTy;
3386 if (const VectorType *VT = OldTy->getAs<VectorType>())
3387 OldElemTy = VT->getElementType();
3389 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType())
3390 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3391 else if (IntegerMode) {
3392 if (!OldElemTy->isIntegralOrEnumerationType())
3393 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3394 } else if (ComplexMode) {
3395 if (!OldElemTy->isComplexType())
3396 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3398 if (!OldElemTy->isFloatingType())
3399 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3402 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3403 // and friends, at least with glibc.
3404 // FIXME: Make sure floating-point mappings are accurate
3405 // FIXME: Support XF and TF types
3407 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3414 NewElemTy = S.Context.getIntTypeForBitwidth(
3415 DestWidth, OldElemTy->isSignedIntegerType());
3417 NewElemTy = S.Context.getRealTypeForBitwidth(DestWidth);
3419 if (NewElemTy.isNull()) {
3420 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3425 NewElemTy = S.Context.getComplexType(NewElemTy);
3428 QualType NewTy = NewElemTy;
3429 if (VectorSize.getBoolValue()) {
3430 NewTy = S.Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3431 VectorType::GenericVector);
3432 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3433 // Complex machine mode does not support base vector types.
3435 S.Diag(Attr.getLoc(), diag::err_complex_mode_vector_type);
3438 unsigned NumElements = S.Context.getTypeSize(OldElemTy) *
3439 OldVT->getNumElements() /
3440 S.Context.getTypeSize(NewElemTy);
3442 S.Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3445 if (NewTy.isNull()) {
3446 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3450 // Install the new type.
3451 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3452 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3454 cast<ValueDecl>(D)->setType(NewTy);
3456 D->addAttr(::new (S.Context)
3457 ModeAttr(Attr.getRange(), S.Context, Name,
3458 Attr.getAttributeSpellingListIndex()));
3461 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3462 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3463 if (!VD->hasGlobalStorage())
3464 S.Diag(Attr.getLoc(),
3465 diag::warn_attribute_requires_functions_or_static_globals)
3467 } else if (!isFunctionOrMethod(D)) {
3468 S.Diag(Attr.getLoc(),
3469 diag::warn_attribute_requires_functions_or_static_globals)
3474 D->addAttr(::new (S.Context)
3475 NoDebugAttr(Attr.getRange(), S.Context,
3476 Attr.getAttributeSpellingListIndex()));
3479 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3480 IdentifierInfo *Ident,
3481 unsigned AttrSpellingListIndex) {
3482 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3483 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3484 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3488 if (D->hasAttr<AlwaysInlineAttr>())
3491 return ::new (Context) AlwaysInlineAttr(Range, Context,
3492 AttrSpellingListIndex);
3495 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3496 IdentifierInfo *Ident,
3497 unsigned AttrSpellingListIndex) {
3498 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3501 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3504 InternalLinkageAttr *
3505 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3506 IdentifierInfo *Ident,
3507 unsigned AttrSpellingListIndex) {
3508 if (auto VD = dyn_cast<VarDecl>(D)) {
3509 // Attribute applies to Var but not any subclass of it (like ParmVar,
3510 // ImplicitParm or VarTemplateSpecialization).
3511 if (VD->getKind() != Decl::Var) {
3512 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3513 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3514 : ExpectedVariableOrFunction);
3517 // Attribute does not apply to non-static local variables.
3518 if (VD->hasLocalStorage()) {
3519 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3524 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3527 return ::new (Context)
3528 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3531 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3532 unsigned AttrSpellingListIndex) {
3533 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3534 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3535 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3539 if (D->hasAttr<MinSizeAttr>())
3542 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3545 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3546 unsigned AttrSpellingListIndex) {
3547 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3548 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3549 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3550 D->dropAttr<AlwaysInlineAttr>();
3552 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3553 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3554 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3555 D->dropAttr<MinSizeAttr>();
3558 if (D->hasAttr<OptimizeNoneAttr>())
3561 return ::new (Context) OptimizeNoneAttr(Range, Context,
3562 AttrSpellingListIndex);
3565 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3566 const AttributeList &Attr) {
3567 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3571 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3572 D, Attr.getRange(), Attr.getName(),
3573 Attr.getAttributeSpellingListIndex()))
3577 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3578 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3579 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3580 D->addAttr(MinSize);
3583 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3584 const AttributeList &Attr) {
3585 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3586 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3587 D->addAttr(Optnone);
3590 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3591 FunctionDecl *FD = cast<FunctionDecl>(D);
3592 if (!FD->getReturnType()->isVoidType()) {
3593 SourceRange RTRange = FD->getReturnTypeSourceRange();
3594 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3596 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3601 D->addAttr(::new (S.Context)
3602 CUDAGlobalAttr(Attr.getRange(), S.Context,
3603 Attr.getAttributeSpellingListIndex()));
3607 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3608 FunctionDecl *Fn = cast<FunctionDecl>(D);
3609 if (!Fn->isInlineSpecified()) {
3610 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3614 D->addAttr(::new (S.Context)
3615 GNUInlineAttr(Attr.getRange(), S.Context,
3616 Attr.getAttributeSpellingListIndex()));
3619 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3620 if (hasDeclarator(D)) return;
3622 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3623 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3625 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
3628 if (!isa<ObjCMethodDecl>(D)) {
3629 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3630 << Attr.getName() << ExpectedFunctionOrMethod;
3634 switch (Attr.getKind()) {
3635 case AttributeList::AT_FastCall:
3636 D->addAttr(::new (S.Context)
3637 FastCallAttr(Attr.getRange(), S.Context,
3638 Attr.getAttributeSpellingListIndex()));
3640 case AttributeList::AT_StdCall:
3641 D->addAttr(::new (S.Context)
3642 StdCallAttr(Attr.getRange(), S.Context,
3643 Attr.getAttributeSpellingListIndex()));
3645 case AttributeList::AT_ThisCall:
3646 D->addAttr(::new (S.Context)
3647 ThisCallAttr(Attr.getRange(), S.Context,
3648 Attr.getAttributeSpellingListIndex()));
3650 case AttributeList::AT_CDecl:
3651 D->addAttr(::new (S.Context)
3652 CDeclAttr(Attr.getRange(), S.Context,
3653 Attr.getAttributeSpellingListIndex()));
3655 case AttributeList::AT_Pascal:
3656 D->addAttr(::new (S.Context)
3657 PascalAttr(Attr.getRange(), S.Context,
3658 Attr.getAttributeSpellingListIndex()));
3660 case AttributeList::AT_VectorCall:
3661 D->addAttr(::new (S.Context)
3662 VectorCallAttr(Attr.getRange(), S.Context,
3663 Attr.getAttributeSpellingListIndex()));
3665 case AttributeList::AT_MSABI:
3666 D->addAttr(::new (S.Context)
3667 MSABIAttr(Attr.getRange(), S.Context,
3668 Attr.getAttributeSpellingListIndex()));
3670 case AttributeList::AT_SysVABI:
3671 D->addAttr(::new (S.Context)
3672 SysVABIAttr(Attr.getRange(), S.Context,
3673 Attr.getAttributeSpellingListIndex()));
3675 case AttributeList::AT_Pcs: {
3676 PcsAttr::PCSType PCS;
3679 PCS = PcsAttr::AAPCS;
3682 PCS = PcsAttr::AAPCS_VFP;
3685 llvm_unreachable("unexpected calling convention in pcs attribute");
3688 D->addAttr(::new (S.Context)
3689 PcsAttr(Attr.getRange(), S.Context, PCS,
3690 Attr.getAttributeSpellingListIndex()));
3693 case AttributeList::AT_IntelOclBicc:
3694 D->addAttr(::new (S.Context)
3695 IntelOclBiccAttr(Attr.getRange(), S.Context,
3696 Attr.getAttributeSpellingListIndex()));
3700 llvm_unreachable("unexpected attribute kind");
3704 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3705 const FunctionDecl *FD) {
3706 if (attr.isInvalid())
3709 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3710 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3715 // TODO: diagnose uses of these conventions on the wrong target.
3716 switch (attr.getKind()) {
3717 case AttributeList::AT_CDecl: CC = CC_C; break;
3718 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3719 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3720 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3721 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3722 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3723 case AttributeList::AT_MSABI:
3724 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3727 case AttributeList::AT_SysVABI:
3728 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3731 case AttributeList::AT_Pcs: {
3733 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3737 if (StrRef == "aapcs") {
3740 } else if (StrRef == "aapcs-vfp") {
3746 Diag(attr.getLoc(), diag::err_invalid_pcs);
3749 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3750 default: llvm_unreachable("unexpected attribute kind");
3753 const TargetInfo &TI = Context.getTargetInfo();
3754 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3755 if (A != TargetInfo::CCCR_OK) {
3756 if (A == TargetInfo::CCCR_Warning)
3757 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3759 // This convention is not valid for the target. Use the default function or
3760 // method calling convention.
3761 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3763 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3764 TargetInfo::CCMT_NonMember;
3765 CC = TI.getDefaultCallingConv(MT);
3771 /// Checks a regparm attribute, returning true if it is ill-formed and
3772 /// otherwise setting numParams to the appropriate value.
3773 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3774 if (Attr.isInvalid())
3777 if (!checkAttributeNumArgs(*this, Attr, 1)) {
3783 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3784 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3789 if (Context.getTargetInfo().getRegParmMax() == 0) {
3790 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3791 << NumParamsExpr->getSourceRange();
3797 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3798 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3799 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3807 // Checks whether an argument of launch_bounds attribute is acceptable
3808 // May output an error.
3809 static bool checkLaunchBoundsArgument(Sema &S, Expr *E,
3810 const CUDALaunchBoundsAttr &Attr,
3811 const unsigned Idx) {
3813 if (S.DiagnoseUnexpandedParameterPack(E))
3816 // Accept template arguments for now as they depend on something else.
3817 // We'll get to check them when they eventually get instantiated.
3818 if (E->isValueDependent())
3822 if (!E->isIntegerConstantExpr(I, S.Context)) {
3823 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
3824 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
3827 // Make sure we can fit it in 32 bits.
3828 if (!I.isIntN(32)) {
3829 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
3830 << 32 << /* Unsigned */ 1;
3834 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
3835 << &Attr << Idx << E->getSourceRange();
3840 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
3841 Expr *MinBlocks, unsigned SpellingListIndex) {
3842 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
3845 if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0))
3848 if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1))
3851 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
3852 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
3855 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3856 const AttributeList &Attr) {
3857 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
3858 !checkAttributeAtMostNumArgs(S, Attr, 2))
3861 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3862 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
3863 Attr.getAttributeSpellingListIndex());
3866 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3867 const AttributeList &Attr) {
3868 if (!Attr.isArgIdent(0)) {
3869 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3870 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3874 if (!checkAttributeNumArgs(S, Attr, 3))
3877 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3879 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3880 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3881 << Attr.getName() << ExpectedFunctionOrMethod;
3885 uint64_t ArgumentIdx;
3886 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3890 uint64_t TypeTagIdx;
3891 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3895 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3897 // Ensure that buffer has a pointer type.
3898 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3899 if (!BufferTy->isPointerType()) {
3900 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3901 << Attr.getName() << 0;
3905 D->addAttr(::new (S.Context)
3906 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3907 ArgumentIdx, TypeTagIdx, IsPointer,
3908 Attr.getAttributeSpellingListIndex()));
3911 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3912 const AttributeList &Attr) {
3913 if (!Attr.isArgIdent(0)) {
3914 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3915 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3919 if (!checkAttributeNumArgs(S, Attr, 1))
3922 if (!isa<VarDecl>(D)) {
3923 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3924 << Attr.getName() << ExpectedVariable;
3928 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3929 TypeSourceInfo *MatchingCTypeLoc = nullptr;
3930 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3931 assert(MatchingCTypeLoc && "no type source info for attribute argument");
3933 D->addAttr(::new (S.Context)
3934 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3936 Attr.getLayoutCompatible(),
3937 Attr.getMustBeNull(),
3938 Attr.getAttributeSpellingListIndex()));
3941 //===----------------------------------------------------------------------===//
3942 // Checker-specific attribute handlers.
3943 //===----------------------------------------------------------------------===//
3945 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
3946 return type->isDependentType() ||
3947 type->isObjCRetainableType();
3950 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3951 return type->isDependentType() ||
3952 type->isObjCObjectPointerType() ||
3953 S.Context.isObjCNSObjectType(type);
3955 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3956 return type->isDependentType() ||
3957 type->isPointerType() ||
3958 isValidSubjectOfNSAttribute(S, type);
3961 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3962 ParmVarDecl *param = cast<ParmVarDecl>(D);
3965 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3966 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3969 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3974 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
3975 << Attr.getRange() << Attr.getName() << cf;
3980 param->addAttr(::new (S.Context)
3981 CFConsumedAttr(Attr.getRange(), S.Context,
3982 Attr.getAttributeSpellingListIndex()));
3984 param->addAttr(::new (S.Context)
3985 NSConsumedAttr(Attr.getRange(), S.Context,
3986 Attr.getAttributeSpellingListIndex()));
3989 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
3990 const AttributeList &Attr) {
3992 QualType returnType;
3994 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
3995 returnType = MD->getReturnType();
3996 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
3997 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
3998 return; // ignore: was handled as a type attribute
3999 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4000 returnType = PD->getType();
4001 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4002 returnType = FD->getReturnType();
4003 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4004 returnType = Param->getType()->getPointeeType();
4005 if (returnType.isNull()) {
4006 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4007 << Attr.getName() << /*pointer-to-CF*/2
4012 AttributeDeclKind ExpectedDeclKind;
4013 switch (Attr.getKind()) {
4014 default: llvm_unreachable("invalid ownership attribute");
4015 case AttributeList::AT_NSReturnsRetained:
4016 case AttributeList::AT_NSReturnsAutoreleased:
4017 case AttributeList::AT_NSReturnsNotRetained:
4018 ExpectedDeclKind = ExpectedFunctionOrMethod;
4021 case AttributeList::AT_CFReturnsRetained:
4022 case AttributeList::AT_CFReturnsNotRetained:
4023 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4026 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4027 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4033 switch (Attr.getKind()) {
4034 default: llvm_unreachable("invalid ownership attribute");
4035 case AttributeList::AT_NSReturnsRetained:
4036 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4040 case AttributeList::AT_NSReturnsAutoreleased:
4041 case AttributeList::AT_NSReturnsNotRetained:
4042 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4046 case AttributeList::AT_CFReturnsRetained:
4047 case AttributeList::AT_CFReturnsNotRetained:
4048 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4054 if (isa<ParmVarDecl>(D)) {
4055 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4056 << Attr.getName() << /*pointer-to-CF*/2
4059 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4064 } SubjectKind = Function;
4065 if (isa<ObjCMethodDecl>(D))
4066 SubjectKind = Method;
4067 else if (isa<ObjCPropertyDecl>(D))
4068 SubjectKind = Property;
4069 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4070 << Attr.getName() << SubjectKind << cf
4076 switch (Attr.getKind()) {
4078 llvm_unreachable("invalid ownership attribute");
4079 case AttributeList::AT_NSReturnsAutoreleased:
4080 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4081 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4083 case AttributeList::AT_CFReturnsNotRetained:
4084 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4085 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4087 case AttributeList::AT_NSReturnsNotRetained:
4088 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4089 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4091 case AttributeList::AT_CFReturnsRetained:
4092 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4093 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4095 case AttributeList::AT_NSReturnsRetained:
4096 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4097 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4102 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4103 const AttributeList &attr) {
4104 const int EP_ObjCMethod = 1;
4105 const int EP_ObjCProperty = 2;
4107 SourceLocation loc = attr.getLoc();
4108 QualType resultType;
4109 if (isa<ObjCMethodDecl>(D))
4110 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4112 resultType = cast<ObjCPropertyDecl>(D)->getType();
4114 if (!resultType->isReferenceType() &&
4115 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4116 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4119 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4120 << /*non-retainable pointer*/ 2;
4122 // Drop the attribute.
4126 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4127 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4130 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4131 const AttributeList &attr) {
4132 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4134 DeclContext *DC = method->getDeclContext();
4135 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4136 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4137 << attr.getName() << 0;
4138 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4141 if (method->getMethodFamily() == OMF_dealloc) {
4142 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4143 << attr.getName() << 1;
4147 method->addAttr(::new (S.Context)
4148 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4149 attr.getAttributeSpellingListIndex()));
4152 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4153 const AttributeList &Attr) {
4154 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4158 D->addAttr(::new (S.Context)
4159 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4160 Attr.getAttributeSpellingListIndex()));
4163 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4164 const AttributeList &Attr) {
4165 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4169 D->addAttr(::new (S.Context)
4170 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4171 Attr.getAttributeSpellingListIndex()));
4174 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4175 const AttributeList &Attr) {
4176 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4179 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4183 // Typedefs only allow objc_bridge(id) and have some additional checking.
4184 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4185 if (!Parm->Ident->isStr("id")) {
4186 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4191 // Only allow 'cv void *'.
4192 QualType T = TD->getUnderlyingType();
4193 if (!T->isVoidPointerType()) {
4194 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4199 D->addAttr(::new (S.Context)
4200 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4201 Attr.getAttributeSpellingListIndex()));
4204 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4205 const AttributeList &Attr) {
4206 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4209 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4213 D->addAttr(::new (S.Context)
4214 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4215 Attr.getAttributeSpellingListIndex()));
4218 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4219 const AttributeList &Attr) {
4220 IdentifierInfo *RelatedClass =
4221 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4222 if (!RelatedClass) {
4223 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4226 IdentifierInfo *ClassMethod =
4227 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4228 IdentifierInfo *InstanceMethod =
4229 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4230 D->addAttr(::new (S.Context)
4231 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4232 ClassMethod, InstanceMethod,
4233 Attr.getAttributeSpellingListIndex()));
4236 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4237 const AttributeList &Attr) {
4238 ObjCInterfaceDecl *IFace;
4239 if (ObjCCategoryDecl *CatDecl =
4240 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4241 IFace = CatDecl->getClassInterface();
4243 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4248 IFace->setHasDesignatedInitializers();
4249 D->addAttr(::new (S.Context)
4250 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4251 Attr.getAttributeSpellingListIndex()));
4254 static void handleObjCRuntimeName(Sema &S, Decl *D,
4255 const AttributeList &Attr) {
4256 StringRef MetaDataName;
4257 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4259 D->addAttr(::new (S.Context)
4260 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4262 Attr.getAttributeSpellingListIndex()));
4265 // when a user wants to use objc_boxable with a union or struct
4266 // but she doesn't have access to the declaration (legacy/third-party code)
4267 // then she can 'enable' this feature via trick with a typedef
4269 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4270 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4271 bool notify = false;
4273 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4274 if (RD && RD->getDefinition()) {
4275 RD = RD->getDefinition();
4280 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4281 ObjCBoxableAttr(Attr.getRange(), S.Context,
4282 Attr.getAttributeSpellingListIndex());
4283 RD->addAttr(BoxableAttr);
4285 // we need to notify ASTReader/ASTWriter about
4286 // modification of existing declaration
4287 if (ASTMutationListener *L = S.getASTMutationListener())
4288 L->AddedAttributeToRecord(BoxableAttr, RD);
4293 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4294 const AttributeList &Attr) {
4295 if (hasDeclarator(D)) return;
4297 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4298 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4301 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4302 const AttributeList &Attr) {
4303 ValueDecl *vd = cast<ValueDecl>(D);
4304 QualType type = vd->getType();
4306 if (!type->isDependentType() &&
4307 !type->isObjCLifetimeType()) {
4308 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4313 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4315 // If we have no lifetime yet, check the lifetime we're presumably
4317 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4318 lifetime = type->getObjCARCImplicitLifetime();
4321 case Qualifiers::OCL_None:
4322 assert(type->isDependentType() &&
4323 "didn't infer lifetime for non-dependent type?");
4326 case Qualifiers::OCL_Weak: // meaningful
4327 case Qualifiers::OCL_Strong: // meaningful
4330 case Qualifiers::OCL_ExplicitNone:
4331 case Qualifiers::OCL_Autoreleasing:
4332 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4333 << (lifetime == Qualifiers::OCL_Autoreleasing);
4337 D->addAttr(::new (S.Context)
4338 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4339 Attr.getAttributeSpellingListIndex()));
4342 //===----------------------------------------------------------------------===//
4343 // Microsoft specific attribute handlers.
4344 //===----------------------------------------------------------------------===//
4346 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4347 if (!S.LangOpts.CPlusPlus) {
4348 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4349 << Attr.getName() << AttributeLangSupport::C;
4353 if (!isa<CXXRecordDecl>(D)) {
4354 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4355 << Attr.getName() << ExpectedClass;
4360 SourceLocation LiteralLoc;
4361 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4364 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4365 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4366 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4367 StrRef = StrRef.drop_front().drop_back();
4369 // Validate GUID length.
4370 if (StrRef.size() != 36) {
4371 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4375 for (unsigned i = 0; i < 36; ++i) {
4376 if (i == 8 || i == 13 || i == 18 || i == 23) {
4377 if (StrRef[i] != '-') {
4378 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4381 } else if (!isHexDigit(StrRef[i])) {
4382 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4387 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4388 Attr.getAttributeSpellingListIndex()));
4391 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4392 if (!S.LangOpts.CPlusPlus) {
4393 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4394 << Attr.getName() << AttributeLangSupport::C;
4397 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
4398 D, Attr.getRange(), /*BestCase=*/true,
4399 Attr.getAttributeSpellingListIndex(),
4400 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
4405 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4406 const AttributeList &Attr) {
4407 VarDecl *VD = cast<VarDecl>(D);
4408 if (!S.Context.getTargetInfo().isTLSSupported()) {
4409 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4412 if (VD->getTSCSpec() != TSCS_unspecified) {
4413 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4416 if (VD->hasLocalStorage()) {
4417 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4420 VD->addAttr(::new (S.Context) ThreadAttr(
4421 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4424 static void handleARMInterruptAttr(Sema &S, Decl *D,
4425 const AttributeList &Attr) {
4426 // Check the attribute arguments.
4427 if (Attr.getNumArgs() > 1) {
4428 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4429 << Attr.getName() << 1;
4434 SourceLocation ArgLoc;
4436 if (Attr.getNumArgs() == 0)
4438 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4441 ARMInterruptAttr::InterruptType Kind;
4442 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4443 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4444 << Attr.getName() << Str << ArgLoc;
4448 unsigned Index = Attr.getAttributeSpellingListIndex();
4449 D->addAttr(::new (S.Context)
4450 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4453 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4454 const AttributeList &Attr) {
4455 if (!checkAttributeNumArgs(S, Attr, 1))
4458 if (!Attr.isArgExpr(0)) {
4459 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4460 << AANT_ArgumentIntegerConstant;
4464 // FIXME: Check for decl - it should be void ()(void).
4466 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4467 llvm::APSInt NumParams(32);
4468 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4469 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4470 << Attr.getName() << AANT_ArgumentIntegerConstant
4471 << NumParamsExpr->getSourceRange();
4475 unsigned Num = NumParams.getLimitedValue(255);
4476 if ((Num & 1) || Num > 30) {
4477 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4478 << Attr.getName() << (int)NumParams.getSExtValue()
4479 << NumParamsExpr->getSourceRange();
4483 D->addAttr(::new (S.Context)
4484 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4485 Attr.getAttributeSpellingListIndex()));
4486 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4489 static void handleMipsInterruptAttr(Sema &S, Decl *D,
4490 const AttributeList &Attr) {
4491 // Only one optional argument permitted.
4492 if (Attr.getNumArgs() > 1) {
4493 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4494 << Attr.getName() << 1;
4499 SourceLocation ArgLoc;
4501 if (Attr.getNumArgs() == 0)
4503 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4506 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
4507 // a) Must be a function.
4508 // b) Must have no parameters.
4509 // c) Must have the 'void' return type.
4510 // d) Cannot have the 'mips16' attribute, as that instruction set
4511 // lacks the 'eret' instruction.
4512 // e) The attribute itself must either have no argument or one of the
4513 // valid interrupt types, see [MipsInterruptDocs].
4515 if (!isFunctionOrMethod(D)) {
4516 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
4517 << "'interrupt'" << ExpectedFunctionOrMethod;
4521 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
4522 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4527 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4528 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4533 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
4537 MipsInterruptAttr::InterruptType Kind;
4538 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4539 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4540 << Attr.getName() << "'" + std::string(Str) + "'";
4544 D->addAttr(::new (S.Context) MipsInterruptAttr(
4545 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
4548 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4549 // Dispatch the interrupt attribute based on the current target.
4550 if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
4551 handleMSP430InterruptAttr(S, D, Attr);
4552 else if (S.Context.getTargetInfo().getTriple().getArch() ==
4553 llvm::Triple::mipsel ||
4554 S.Context.getTargetInfo().getTriple().getArch() ==
4556 handleMipsInterruptAttr(S, D, Attr);
4558 handleARMInterruptAttr(S, D, Attr);
4561 static void handleMips16Attribute(Sema &S, Decl *D, const AttributeList &Attr) {
4562 if (checkAttrMutualExclusion<MipsInterruptAttr>(S, D, Attr.getRange(),
4566 handleSimpleAttribute<Mips16Attr>(S, D, Attr);
4569 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
4570 const AttributeList &Attr) {
4572 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4573 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4576 D->addAttr(::new (S.Context)
4577 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4579 Attr.getAttributeSpellingListIndex()));
4582 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4583 const AttributeList &Attr) {
4585 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4586 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4589 D->addAttr(::new (S.Context)
4590 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4592 Attr.getAttributeSpellingListIndex()));
4595 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4596 const AttributeList& Attr) {
4597 // If we try to apply it to a function pointer, don't warn, but don't
4598 // do anything, either. It doesn't matter anyway, because there's nothing
4599 // special about calling a force_align_arg_pointer function.
4600 ValueDecl *VD = dyn_cast<ValueDecl>(D);
4601 if (VD && VD->getType()->isFunctionPointerType())
4603 // Also don't warn on function pointer typedefs.
4604 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4605 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4606 TD->getUnderlyingType()->isFunctionType()))
4608 // Attribute can only be applied to function types.
4609 if (!isa<FunctionDecl>(D)) {
4610 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4611 << Attr.getName() << /* function */0;
4615 D->addAttr(::new (S.Context)
4616 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4617 Attr.getAttributeSpellingListIndex()));
4620 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4621 unsigned AttrSpellingListIndex) {
4622 if (D->hasAttr<DLLExportAttr>()) {
4623 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
4627 if (D->hasAttr<DLLImportAttr>())
4630 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
4633 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
4634 unsigned AttrSpellingListIndex) {
4635 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
4636 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
4637 D->dropAttr<DLLImportAttr>();
4640 if (D->hasAttr<DLLExportAttr>())
4643 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
4646 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
4647 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
4648 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4649 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
4654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4655 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
4656 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4657 // MinGW doesn't allow dllimport on inline functions.
4658 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
4664 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4665 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4666 MD->getParent()->isLambda()) {
4667 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
4672 unsigned Index = A.getAttributeSpellingListIndex();
4673 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
4674 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
4675 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
4677 D->addAttr(NewAttr);
4681 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
4682 unsigned AttrSpellingListIndex,
4683 MSInheritanceAttr::Spelling SemanticSpelling) {
4684 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
4685 if (IA->getSemanticSpelling() == SemanticSpelling)
4687 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
4688 << 1 /*previous declaration*/;
4689 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
4690 D->dropAttr<MSInheritanceAttr>();
4693 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
4694 if (RD->hasDefinition()) {
4695 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
4696 SemanticSpelling)) {
4700 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
4701 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4702 << 1 /*partial specialization*/;
4705 if (RD->getDescribedClassTemplate()) {
4706 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4707 << 0 /*primary template*/;
4712 return ::new (Context)
4713 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
4716 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4717 // The capability attributes take a single string parameter for the name of
4718 // the capability they represent. The lockable attribute does not take any
4719 // parameters. However, semantically, both attributes represent the same
4720 // concept, and so they use the same semantic attribute. Eventually, the
4721 // lockable attribute will be removed.
4723 // For backward compatibility, any capability which has no specified string
4724 // literal will be considered a "mutex."
4725 StringRef N("mutex");
4726 SourceLocation LiteralLoc;
4727 if (Attr.getKind() == AttributeList::AT_Capability &&
4728 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
4731 // Currently, there are only two names allowed for a capability: role and
4732 // mutex (case insensitive). Diagnose other capability names.
4733 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
4734 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
4736 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
4737 Attr.getAttributeSpellingListIndex()));
4740 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
4741 const AttributeList &Attr) {
4742 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
4743 Attr.getArgAsExpr(0),
4744 Attr.getAttributeSpellingListIndex()));
4747 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
4748 const AttributeList &Attr) {
4749 SmallVector<Expr*, 1> Args;
4750 if (!checkLockFunAttrCommon(S, D, Attr, Args))
4753 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
4755 Args.data(), Args.size(),
4756 Attr.getAttributeSpellingListIndex()));
4759 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
4760 const AttributeList &Attr) {
4761 SmallVector<Expr*, 2> Args;
4762 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
4765 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
4767 Attr.getArgAsExpr(0),
4770 Attr.getAttributeSpellingListIndex()));
4773 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
4774 const AttributeList &Attr) {
4775 // Check that all arguments are lockable objects.
4776 SmallVector<Expr *, 1> Args;
4777 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
4779 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
4780 Attr.getRange(), S.Context, Args.data(), Args.size(),
4781 Attr.getAttributeSpellingListIndex()));
4784 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
4785 const AttributeList &Attr) {
4786 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4789 // check that all arguments are lockable objects
4790 SmallVector<Expr*, 1> Args;
4791 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
4795 RequiresCapabilityAttr *RCA = ::new (S.Context)
4796 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
4797 Args.size(), Attr.getAttributeSpellingListIndex());
4802 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4803 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
4804 if (NSD->isAnonymousNamespace()) {
4805 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
4806 // Do not want to attach the attribute to the namespace because that will
4807 // cause confusing diagnostic reports for uses of declarations within the
4813 if (!S.getLangOpts().CPlusPlus14)
4814 if (Attr.isCXX11Attribute() &&
4815 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
4816 S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension);
4818 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4821 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4822 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4825 std::vector<std::string> Sanitizers;
4827 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4828 StringRef SanitizerName;
4829 SourceLocation LiteralLoc;
4831 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
4834 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
4835 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
4837 Sanitizers.push_back(SanitizerName);
4840 D->addAttr(::new (S.Context) NoSanitizeAttr(
4841 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
4842 Attr.getAttributeSpellingListIndex()));
4845 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
4846 const AttributeList &Attr) {
4847 StringRef AttrName = Attr.getName()->getName();
4848 normalizeName(AttrName);
4849 std::string SanitizerName =
4850 llvm::StringSwitch<std::string>(AttrName)
4851 .Case("no_address_safety_analysis", "address")
4852 .Case("no_sanitize_address", "address")
4853 .Case("no_sanitize_thread", "thread")
4854 .Case("no_sanitize_memory", "memory");
4855 D->addAttr(::new (S.Context)
4856 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
4857 Attr.getAttributeSpellingListIndex()));
4860 static void handleInternalLinkageAttr(Sema &S, Decl *D,
4861 const AttributeList &Attr) {
4862 if (InternalLinkageAttr *Internal =
4863 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
4864 Attr.getAttributeSpellingListIndex()))
4865 D->addAttr(Internal);
4868 /// Handles semantic checking for features that are common to all attributes,
4869 /// such as checking whether a parameter was properly specified, or the correct
4870 /// number of arguments were passed, etc.
4871 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4872 const AttributeList &Attr) {
4873 // Several attributes carry different semantics than the parsing requires, so
4874 // those are opted out of the common handling.
4876 // We also bail on unknown and ignored attributes because those are handled
4877 // as part of the target-specific handling logic.
4878 if (Attr.hasCustomParsing() ||
4879 Attr.getKind() == AttributeList::UnknownAttribute)
4882 // Check whether the attribute requires specific language extensions to be
4884 if (!Attr.diagnoseLangOpts(S))
4887 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
4888 // If there are no optional arguments, then checking for the argument count
4890 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4893 // There are optional arguments, so checking is slightly more involved.
4894 if (Attr.getMinArgs() &&
4895 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
4897 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
4898 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
4902 // Check whether the attribute appertains to the given subject.
4903 if (!Attr.diagnoseAppertainsTo(S, D))
4909 //===----------------------------------------------------------------------===//
4910 // Top Level Sema Entry Points
4911 //===----------------------------------------------------------------------===//
4913 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4914 /// the attribute applies to decls. If the attribute is a type attribute, just
4915 /// silently ignore it if a GNU attribute.
4916 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4917 const AttributeList &Attr,
4918 bool IncludeCXX11Attributes) {
4919 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4922 // Ignore C++11 attributes on declarator chunks: they appertain to the type
4924 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4927 // Unknown attributes are automatically warned on. Target-specific attributes
4928 // which do not apply to the current target architecture are treated as
4929 // though they were unknown attributes.
4930 if (Attr.getKind() == AttributeList::UnknownAttribute ||
4931 !Attr.existsInTarget(S.Context.getTargetInfo())) {
4932 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4933 ? diag::warn_unhandled_ms_attribute_ignored
4934 : diag::warn_unknown_attribute_ignored)
4939 if (handleCommonAttributeFeatures(S, scope, D, Attr))
4942 switch (Attr.getKind()) {
4944 // Type attributes are handled elsewhere; silently move on.
4945 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4947 case AttributeList::AT_Interrupt:
4948 handleInterruptAttr(S, D, Attr);
4950 case AttributeList::AT_X86ForceAlignArgPointer:
4951 handleX86ForceAlignArgPointerAttr(S, D, Attr);
4953 case AttributeList::AT_DLLExport:
4954 case AttributeList::AT_DLLImport:
4955 handleDLLAttr(S, D, Attr);
4957 case AttributeList::AT_Mips16:
4958 handleMips16Attribute(S, D, Attr);
4960 case AttributeList::AT_NoMips16:
4961 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4963 case AttributeList::AT_AMDGPUNumVGPR:
4964 handleAMDGPUNumVGPRAttr(S, D, Attr);
4966 case AttributeList::AT_AMDGPUNumSGPR:
4967 handleAMDGPUNumSGPRAttr(S, D, Attr);
4969 case AttributeList::AT_IBAction:
4970 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4972 case AttributeList::AT_IBOutlet:
4973 handleIBOutlet(S, D, Attr);
4975 case AttributeList::AT_IBOutletCollection:
4976 handleIBOutletCollection(S, D, Attr);
4978 case AttributeList::AT_Alias:
4979 handleAliasAttr(S, D, Attr);
4981 case AttributeList::AT_Aligned:
4982 handleAlignedAttr(S, D, Attr);
4984 case AttributeList::AT_AlignValue:
4985 handleAlignValueAttr(S, D, Attr);
4987 case AttributeList::AT_AlwaysInline:
4988 handleAlwaysInlineAttr(S, D, Attr);
4990 case AttributeList::AT_AnalyzerNoReturn:
4991 handleAnalyzerNoReturnAttr(S, D, Attr);
4993 case AttributeList::AT_TLSModel:
4994 handleTLSModelAttr(S, D, Attr);
4996 case AttributeList::AT_Annotate:
4997 handleAnnotateAttr(S, D, Attr);
4999 case AttributeList::AT_Availability:
5000 handleAvailabilityAttr(S, D, Attr);
5002 case AttributeList::AT_CarriesDependency:
5003 handleDependencyAttr(S, scope, D, Attr);
5005 case AttributeList::AT_Common:
5006 handleCommonAttr(S, D, Attr);
5008 case AttributeList::AT_CUDAConstant:
5009 handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr);
5011 case AttributeList::AT_PassObjectSize:
5012 handlePassObjectSizeAttr(S, D, Attr);
5014 case AttributeList::AT_Constructor:
5015 handleConstructorAttr(S, D, Attr);
5017 case AttributeList::AT_CXX11NoReturn:
5018 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5020 case AttributeList::AT_Deprecated:
5021 handleDeprecatedAttr(S, D, Attr);
5023 case AttributeList::AT_Destructor:
5024 handleDestructorAttr(S, D, Attr);
5026 case AttributeList::AT_EnableIf:
5027 handleEnableIfAttr(S, D, Attr);
5029 case AttributeList::AT_ExtVectorType:
5030 handleExtVectorTypeAttr(S, scope, D, Attr);
5032 case AttributeList::AT_MinSize:
5033 handleMinSizeAttr(S, D, Attr);
5035 case AttributeList::AT_OptimizeNone:
5036 handleOptimizeNoneAttr(S, D, Attr);
5038 case AttributeList::AT_FlagEnum:
5039 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5041 case AttributeList::AT_Flatten:
5042 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5044 case AttributeList::AT_Format:
5045 handleFormatAttr(S, D, Attr);
5047 case AttributeList::AT_FormatArg:
5048 handleFormatArgAttr(S, D, Attr);
5050 case AttributeList::AT_CUDAGlobal:
5051 handleGlobalAttr(S, D, Attr);
5053 case AttributeList::AT_CUDADevice:
5054 handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr);
5056 case AttributeList::AT_CUDAHost:
5057 handleSimpleAttribute<CUDAHostAttr>(S, D, Attr);
5059 case AttributeList::AT_GNUInline:
5060 handleGNUInlineAttr(S, D, Attr);
5062 case AttributeList::AT_CUDALaunchBounds:
5063 handleLaunchBoundsAttr(S, D, Attr);
5065 case AttributeList::AT_Restrict:
5066 handleRestrictAttr(S, D, Attr);
5068 case AttributeList::AT_MayAlias:
5069 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5071 case AttributeList::AT_Mode:
5072 handleModeAttr(S, D, Attr);
5074 case AttributeList::AT_NoAlias:
5075 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5077 case AttributeList::AT_NoCommon:
5078 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5080 case AttributeList::AT_NoSplitStack:
5081 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5083 case AttributeList::AT_NonNull:
5084 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5085 handleNonNullAttrParameter(S, PVD, Attr);
5087 handleNonNullAttr(S, D, Attr);
5089 case AttributeList::AT_ReturnsNonNull:
5090 handleReturnsNonNullAttr(S, D, Attr);
5092 case AttributeList::AT_AssumeAligned:
5093 handleAssumeAlignedAttr(S, D, Attr);
5095 case AttributeList::AT_Overloadable:
5096 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5098 case AttributeList::AT_Ownership:
5099 handleOwnershipAttr(S, D, Attr);
5101 case AttributeList::AT_Cold:
5102 handleColdAttr(S, D, Attr);
5104 case AttributeList::AT_Hot:
5105 handleHotAttr(S, D, Attr);
5107 case AttributeList::AT_Naked:
5108 handleNakedAttr(S, D, Attr);
5110 case AttributeList::AT_NoReturn:
5111 handleNoReturnAttr(S, D, Attr);
5113 case AttributeList::AT_NoThrow:
5114 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5116 case AttributeList::AT_CUDAShared:
5117 handleSimpleAttribute<CUDASharedAttr>(S, D, Attr);
5119 case AttributeList::AT_VecReturn:
5120 handleVecReturnAttr(S, D, Attr);
5123 case AttributeList::AT_ObjCOwnership:
5124 handleObjCOwnershipAttr(S, D, Attr);
5126 case AttributeList::AT_ObjCPreciseLifetime:
5127 handleObjCPreciseLifetimeAttr(S, D, Attr);
5130 case AttributeList::AT_ObjCReturnsInnerPointer:
5131 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5134 case AttributeList::AT_ObjCRequiresSuper:
5135 handleObjCRequiresSuperAttr(S, D, Attr);
5138 case AttributeList::AT_ObjCBridge:
5139 handleObjCBridgeAttr(S, scope, D, Attr);
5142 case AttributeList::AT_ObjCBridgeMutable:
5143 handleObjCBridgeMutableAttr(S, scope, D, Attr);
5146 case AttributeList::AT_ObjCBridgeRelated:
5147 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
5150 case AttributeList::AT_ObjCDesignatedInitializer:
5151 handleObjCDesignatedInitializer(S, D, Attr);
5154 case AttributeList::AT_ObjCRuntimeName:
5155 handleObjCRuntimeName(S, D, Attr);
5158 case AttributeList::AT_ObjCBoxable:
5159 handleObjCBoxable(S, D, Attr);
5162 case AttributeList::AT_CFAuditedTransfer:
5163 handleCFAuditedTransferAttr(S, D, Attr);
5165 case AttributeList::AT_CFUnknownTransfer:
5166 handleCFUnknownTransferAttr(S, D, Attr);
5169 case AttributeList::AT_CFConsumed:
5170 case AttributeList::AT_NSConsumed:
5171 handleNSConsumedAttr(S, D, Attr);
5173 case AttributeList::AT_NSConsumesSelf:
5174 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
5177 case AttributeList::AT_NSReturnsAutoreleased:
5178 case AttributeList::AT_NSReturnsNotRetained:
5179 case AttributeList::AT_CFReturnsNotRetained:
5180 case AttributeList::AT_NSReturnsRetained:
5181 case AttributeList::AT_CFReturnsRetained:
5182 handleNSReturnsRetainedAttr(S, D, Attr);
5184 case AttributeList::AT_WorkGroupSizeHint:
5185 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
5187 case AttributeList::AT_ReqdWorkGroupSize:
5188 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
5190 case AttributeList::AT_VecTypeHint:
5191 handleVecTypeHint(S, D, Attr);
5194 case AttributeList::AT_InitPriority:
5195 handleInitPriorityAttr(S, D, Attr);
5198 case AttributeList::AT_Packed:
5199 handlePackedAttr(S, D, Attr);
5201 case AttributeList::AT_Section:
5202 handleSectionAttr(S, D, Attr);
5204 case AttributeList::AT_Target:
5205 handleTargetAttr(S, D, Attr);
5207 case AttributeList::AT_Unavailable:
5208 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
5210 case AttributeList::AT_ArcWeakrefUnavailable:
5211 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
5213 case AttributeList::AT_ObjCRootClass:
5214 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
5216 case AttributeList::AT_ObjCExplicitProtocolImpl:
5217 handleObjCSuppresProtocolAttr(S, D, Attr);
5219 case AttributeList::AT_ObjCRequiresPropertyDefs:
5220 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
5222 case AttributeList::AT_Unused:
5223 handleSimpleAttribute<UnusedAttr>(S, D, Attr);
5225 case AttributeList::AT_ReturnsTwice:
5226 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
5228 case AttributeList::AT_NotTailCalled:
5229 handleNotTailCalledAttr(S, D, Attr);
5231 case AttributeList::AT_DisableTailCalls:
5232 handleDisableTailCallsAttr(S, D, Attr);
5234 case AttributeList::AT_Used:
5235 handleUsedAttr(S, D, Attr);
5237 case AttributeList::AT_Visibility:
5238 handleVisibilityAttr(S, D, Attr, false);
5240 case AttributeList::AT_TypeVisibility:
5241 handleVisibilityAttr(S, D, Attr, true);
5243 case AttributeList::AT_WarnUnused:
5244 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
5246 case AttributeList::AT_WarnUnusedResult:
5247 handleWarnUnusedResult(S, D, Attr);
5249 case AttributeList::AT_Weak:
5250 handleSimpleAttribute<WeakAttr>(S, D, Attr);
5252 case AttributeList::AT_WeakRef:
5253 handleWeakRefAttr(S, D, Attr);
5255 case AttributeList::AT_WeakImport:
5256 handleWeakImportAttr(S, D, Attr);
5258 case AttributeList::AT_TransparentUnion:
5259 handleTransparentUnionAttr(S, D, Attr);
5261 case AttributeList::AT_ObjCException:
5262 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
5264 case AttributeList::AT_ObjCMethodFamily:
5265 handleObjCMethodFamilyAttr(S, D, Attr);
5267 case AttributeList::AT_ObjCNSObject:
5268 handleObjCNSObject(S, D, Attr);
5270 case AttributeList::AT_ObjCIndependentClass:
5271 handleObjCIndependentClass(S, D, Attr);
5273 case AttributeList::AT_Blocks:
5274 handleBlocksAttr(S, D, Attr);
5276 case AttributeList::AT_Sentinel:
5277 handleSentinelAttr(S, D, Attr);
5279 case AttributeList::AT_Const:
5280 handleSimpleAttribute<ConstAttr>(S, D, Attr);
5282 case AttributeList::AT_Pure:
5283 handleSimpleAttribute<PureAttr>(S, D, Attr);
5285 case AttributeList::AT_Cleanup:
5286 handleCleanupAttr(S, D, Attr);
5288 case AttributeList::AT_NoDebug:
5289 handleNoDebugAttr(S, D, Attr);
5291 case AttributeList::AT_NoDuplicate:
5292 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
5294 case AttributeList::AT_NoInline:
5295 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
5297 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
5298 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
5300 case AttributeList::AT_StdCall:
5301 case AttributeList::AT_CDecl:
5302 case AttributeList::AT_FastCall:
5303 case AttributeList::AT_ThisCall:
5304 case AttributeList::AT_Pascal:
5305 case AttributeList::AT_VectorCall:
5306 case AttributeList::AT_MSABI:
5307 case AttributeList::AT_SysVABI:
5308 case AttributeList::AT_Pcs:
5309 case AttributeList::AT_IntelOclBicc:
5310 handleCallConvAttr(S, D, Attr);
5312 case AttributeList::AT_OpenCLKernel:
5313 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
5315 case AttributeList::AT_OpenCLImageAccess:
5316 handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
5318 case AttributeList::AT_InternalLinkage:
5319 handleInternalLinkageAttr(S, D, Attr);
5322 // Microsoft attributes:
5323 case AttributeList::AT_MSNoVTable:
5324 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
5326 case AttributeList::AT_MSStruct:
5327 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
5329 case AttributeList::AT_Uuid:
5330 handleUuidAttr(S, D, Attr);
5332 case AttributeList::AT_MSInheritance:
5333 handleMSInheritanceAttr(S, D, Attr);
5335 case AttributeList::AT_SelectAny:
5336 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
5338 case AttributeList::AT_Thread:
5339 handleDeclspecThreadAttr(S, D, Attr);
5342 // Thread safety attributes:
5343 case AttributeList::AT_AssertExclusiveLock:
5344 handleAssertExclusiveLockAttr(S, D, Attr);
5346 case AttributeList::AT_AssertSharedLock:
5347 handleAssertSharedLockAttr(S, D, Attr);
5349 case AttributeList::AT_GuardedVar:
5350 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
5352 case AttributeList::AT_PtGuardedVar:
5353 handlePtGuardedVarAttr(S, D, Attr);
5355 case AttributeList::AT_ScopedLockable:
5356 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
5358 case AttributeList::AT_NoSanitize:
5359 handleNoSanitizeAttr(S, D, Attr);
5361 case AttributeList::AT_NoSanitizeSpecific:
5362 handleNoSanitizeSpecificAttr(S, D, Attr);
5364 case AttributeList::AT_NoThreadSafetyAnalysis:
5365 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
5367 case AttributeList::AT_GuardedBy:
5368 handleGuardedByAttr(S, D, Attr);
5370 case AttributeList::AT_PtGuardedBy:
5371 handlePtGuardedByAttr(S, D, Attr);
5373 case AttributeList::AT_ExclusiveTrylockFunction:
5374 handleExclusiveTrylockFunctionAttr(S, D, Attr);
5376 case AttributeList::AT_LockReturned:
5377 handleLockReturnedAttr(S, D, Attr);
5379 case AttributeList::AT_LocksExcluded:
5380 handleLocksExcludedAttr(S, D, Attr);
5382 case AttributeList::AT_SharedTrylockFunction:
5383 handleSharedTrylockFunctionAttr(S, D, Attr);
5385 case AttributeList::AT_AcquiredBefore:
5386 handleAcquiredBeforeAttr(S, D, Attr);
5388 case AttributeList::AT_AcquiredAfter:
5389 handleAcquiredAfterAttr(S, D, Attr);
5392 // Capability analysis attributes.
5393 case AttributeList::AT_Capability:
5394 case AttributeList::AT_Lockable:
5395 handleCapabilityAttr(S, D, Attr);
5397 case AttributeList::AT_RequiresCapability:
5398 handleRequiresCapabilityAttr(S, D, Attr);
5401 case AttributeList::AT_AssertCapability:
5402 handleAssertCapabilityAttr(S, D, Attr);
5404 case AttributeList::AT_AcquireCapability:
5405 handleAcquireCapabilityAttr(S, D, Attr);
5407 case AttributeList::AT_ReleaseCapability:
5408 handleReleaseCapabilityAttr(S, D, Attr);
5410 case AttributeList::AT_TryAcquireCapability:
5411 handleTryAcquireCapabilityAttr(S, D, Attr);
5414 // Consumed analysis attributes.
5415 case AttributeList::AT_Consumable:
5416 handleConsumableAttr(S, D, Attr);
5418 case AttributeList::AT_ConsumableAutoCast:
5419 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
5421 case AttributeList::AT_ConsumableSetOnRead:
5422 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
5424 case AttributeList::AT_CallableWhen:
5425 handleCallableWhenAttr(S, D, Attr);
5427 case AttributeList::AT_ParamTypestate:
5428 handleParamTypestateAttr(S, D, Attr);
5430 case AttributeList::AT_ReturnTypestate:
5431 handleReturnTypestateAttr(S, D, Attr);
5433 case AttributeList::AT_SetTypestate:
5434 handleSetTypestateAttr(S, D, Attr);
5436 case AttributeList::AT_TestTypestate:
5437 handleTestTypestateAttr(S, D, Attr);
5440 // Type safety attributes.
5441 case AttributeList::AT_ArgumentWithTypeTag:
5442 handleArgumentWithTypeTagAttr(S, D, Attr);
5444 case AttributeList::AT_TypeTagForDatatype:
5445 handleTypeTagForDatatypeAttr(S, D, Attr);
5450 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5451 /// attribute list to the specified decl, ignoring any type attributes.
5452 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
5453 const AttributeList *AttrList,
5454 bool IncludeCXX11Attributes) {
5455 for (const AttributeList* l = AttrList; l; l = l->getNext())
5456 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
5458 // FIXME: We should be able to handle these cases in TableGen.
5460 // static int a9 __attribute__((weakref));
5461 // but that looks really pointless. We reject it.
5462 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
5463 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
5464 << cast<NamedDecl>(D);
5465 D->dropAttr<WeakRefAttr>();
5469 // FIXME: We should be able to handle this in TableGen as well. It would be
5470 // good to have a way to specify "these attributes must appear as a group",
5471 // for these. Additionally, it would be good to have a way to specify "these
5472 // attribute must never appear as a group" for attributes like cold and hot.
5473 if (!D->hasAttr<OpenCLKernelAttr>()) {
5474 // These attributes cannot be applied to a non-kernel function.
5475 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
5476 // FIXME: This emits a different error message than
5477 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
5478 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5479 D->setInvalidDecl();
5480 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
5481 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5482 D->setInvalidDecl();
5483 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
5484 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5485 D->setInvalidDecl();
5486 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
5487 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5488 << A << ExpectedKernelFunction;
5489 D->setInvalidDecl();
5490 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
5491 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5492 << A << ExpectedKernelFunction;
5493 D->setInvalidDecl();
5498 // Annotation attributes are the only attributes allowed after an access
5500 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5501 const AttributeList *AttrList) {
5502 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5503 if (l->getKind() == AttributeList::AT_Annotate) {
5504 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
5506 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
5514 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
5515 /// contains any decl attributes that we should warn about.
5516 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
5517 for ( ; A; A = A->getNext()) {
5518 // Only warn if the attribute is an unignored, non-type attribute.
5519 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
5520 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
5522 if (A->getKind() == AttributeList::UnknownAttribute) {
5523 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
5524 << A->getName() << A->getRange();
5526 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
5527 << A->getName() << A->getRange();
5532 /// checkUnusedDeclAttributes - Given a declarator which is not being
5533 /// used to build a declaration, complain about any decl attributes
5534 /// which might be lying around on it.
5535 void Sema::checkUnusedDeclAttributes(Declarator &D) {
5536 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
5537 ::checkUnusedDeclAttributes(*this, D.getAttributes());
5538 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
5539 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
5542 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5543 /// \#pragma weak needs a non-definition decl and source may not have one.
5544 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5545 SourceLocation Loc) {
5546 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
5547 NamedDecl *NewD = nullptr;
5548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5549 FunctionDecl *NewFD;
5550 // FIXME: Missing call to CheckFunctionDeclaration().
5552 // FIXME: Is the qualifier info correct?
5553 // FIXME: Is the DeclContext correct?
5554 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
5555 Loc, Loc, DeclarationName(II),
5556 FD->getType(), FD->getTypeSourceInfo(),
5557 SC_None, false/*isInlineSpecified*/,
5559 false/*isConstexprSpecified*/);
5562 if (FD->getQualifier())
5563 NewFD->setQualifierInfo(FD->getQualifierLoc());
5565 // Fake up parameter variables; they are declared as if this were
5567 QualType FDTy = FD->getType();
5568 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5569 SmallVector<ParmVarDecl*, 16> Params;
5570 for (const auto &AI : FT->param_types()) {
5571 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
5572 Param->setScopeInfo(0, Params.size());
5573 Params.push_back(Param);
5575 NewFD->setParams(Params);
5577 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5578 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
5579 VD->getInnerLocStart(), VD->getLocation(), II,
5580 VD->getType(), VD->getTypeSourceInfo(),
5581 VD->getStorageClass());
5582 if (VD->getQualifier()) {
5583 VarDecl *NewVD = cast<VarDecl>(NewD);
5584 NewVD->setQualifierInfo(VD->getQualifierLoc());
5590 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5591 /// applied to it, possibly with an alias.
5592 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
5593 if (W.getUsed()) return; // only do this once
5595 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5596 IdentifierInfo *NDId = ND->getIdentifier();
5597 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
5598 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
5600 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5601 WeakTopLevelDecl.push_back(NewD);
5602 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5603 // to insert Decl at TU scope, sorry.
5604 DeclContext *SavedContext = CurContext;
5605 CurContext = Context.getTranslationUnitDecl();
5606 NewD->setDeclContext(CurContext);
5607 NewD->setLexicalDeclContext(CurContext);
5608 PushOnScopeChains(NewD, S);
5609 CurContext = SavedContext;
5610 } else { // just add weak to existing
5611 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5615 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
5616 // It's valid to "forward-declare" #pragma weak, in which case we
5618 LoadExternalWeakUndeclaredIdentifiers();
5619 if (!WeakUndeclaredIdentifiers.empty()) {
5620 NamedDecl *ND = nullptr;
5621 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5622 if (VD->isExternC())
5624 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5625 if (FD->isExternC())
5628 if (IdentifierInfo *Id = ND->getIdentifier()) {
5629 auto I = WeakUndeclaredIdentifiers.find(Id);
5630 if (I != WeakUndeclaredIdentifiers.end()) {
5631 WeakInfo W = I->second;
5632 DeclApplyPragmaWeak(S, ND, W);
5633 WeakUndeclaredIdentifiers[Id] = W;
5640 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
5641 /// it, apply them to D. This is a bit tricky because PD can have attributes
5642 /// specified in many different places, and we need to find and apply them all.
5643 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
5644 // Apply decl attributes from the DeclSpec if present.
5645 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
5646 ProcessDeclAttributeList(S, D, Attrs);
5648 // Walk the declarator structure, applying decl attributes that were in a type
5649 // position to the decl itself. This handles cases like:
5650 // int *__attr__(x)** D;
5651 // when X is a decl attribute.
5652 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5653 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5654 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
5656 // Finally, apply any attributes on the decl itself.
5657 if (const AttributeList *Attrs = PD.getAttributes())
5658 ProcessDeclAttributeList(S, D, Attrs);
5661 /// Is the given declaration allowed to use a forbidden type?
5662 /// If so, it'll still be annotated with an attribute that makes it
5663 /// illegal to actually use.
5664 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
5665 const DelayedDiagnostic &diag,
5666 UnavailableAttr::ImplicitReason &reason) {
5667 // Private ivars are always okay. Unfortunately, people don't
5668 // always properly make their ivars private, even in system headers.
5669 // Plus we need to make fields okay, too.
5670 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5671 !isa<FunctionDecl>(decl))
5674 // Silently accept unsupported uses of __weak in both user and system
5675 // declarations when it's been disabled, for ease of integration with
5676 // -fno-objc-arc files. We do have to take some care against attempts
5677 // to define such things; for now, we've only done that for ivars
5679 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
5680 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
5681 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
5682 reason = UnavailableAttr::IR_ForbiddenWeak;
5687 // Allow all sorts of things in system headers.
5688 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
5689 // Currently, all the failures dealt with this way are due to ARC
5691 reason = UnavailableAttr::IR_ARCForbiddenType;
5698 /// Handle a delayed forbidden-type diagnostic.
5699 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5701 auto reason = UnavailableAttr::IR_None;
5702 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
5703 assert(reason && "didn't set reason?");
5704 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
5708 if (S.getLangOpts().ObjCAutoRefCount)
5709 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5710 // FIXME: we may want to suppress diagnostics for all
5711 // kind of forbidden type messages on unavailable functions.
5712 if (FD->hasAttr<UnavailableAttr>() &&
5713 diag.getForbiddenTypeDiagnostic() ==
5714 diag::err_arc_array_param_no_ownership) {
5715 diag.Triggered = true;
5720 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5721 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5722 diag.Triggered = true;
5726 static bool isDeclDeprecated(Decl *D) {
5728 if (D->isDeprecated())
5730 // A category implicitly has the availability of the interface.
5731 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5732 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5733 return Interface->isDeprecated();
5734 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5738 static bool isDeclUnavailable(Decl *D) {
5740 if (D->isUnavailable())
5742 // A category implicitly has the availability of the interface.
5743 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5744 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5745 return Interface->isUnavailable();
5746 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5750 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
5751 Decl *Ctx, const NamedDecl *D,
5752 StringRef Message, SourceLocation Loc,
5753 const ObjCInterfaceDecl *UnknownObjCClass,
5754 const ObjCPropertyDecl *ObjCProperty,
5755 bool ObjCPropertyAccess) {
5756 // Diagnostics for deprecated or unavailable.
5757 unsigned diag, diag_message, diag_fwdclass_message;
5758 unsigned diag_available_here = diag::note_availability_specified_here;
5760 // Matches 'diag::note_property_attribute' options.
5761 unsigned property_note_select;
5763 // Matches diag::note_availability_specified_here.
5764 unsigned available_here_select_kind;
5766 // Don't warn if our current context is deprecated or unavailable.
5768 case Sema::AD_Deprecation:
5769 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
5771 diag = !ObjCPropertyAccess ? diag::warn_deprecated
5772 : diag::warn_property_method_deprecated;
5773 diag_message = diag::warn_deprecated_message;
5774 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
5775 property_note_select = /* deprecated */ 0;
5776 available_here_select_kind = /* deprecated */ 2;
5779 case Sema::AD_Unavailable:
5780 if (isDeclUnavailable(Ctx))
5782 diag = !ObjCPropertyAccess ? diag::err_unavailable
5783 : diag::err_property_method_unavailable;
5784 diag_message = diag::err_unavailable_message;
5785 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
5786 property_note_select = /* unavailable */ 1;
5787 available_here_select_kind = /* unavailable */ 0;
5789 if (auto attr = D->getAttr<UnavailableAttr>()) {
5790 if (attr->isImplicit() && attr->getImplicitReason()) {
5791 // Most of these failures are due to extra restrictions in ARC;
5792 // reflect that in the primary diagnostic when applicable.
5793 auto flagARCError = [&] {
5794 if (S.getLangOpts().ObjCAutoRefCount &&
5795 S.getSourceManager().isInSystemHeader(D->getLocation()))
5796 diag = diag::err_unavailable_in_arc;
5799 switch (attr->getImplicitReason()) {
5800 case UnavailableAttr::IR_None: break;
5802 case UnavailableAttr::IR_ARCForbiddenType:
5804 diag_available_here = diag::note_arc_forbidden_type;
5807 case UnavailableAttr::IR_ForbiddenWeak:
5808 if (S.getLangOpts().ObjCWeakRuntime)
5809 diag_available_here = diag::note_arc_weak_disabled;
5811 diag_available_here = diag::note_arc_weak_no_runtime;
5814 case UnavailableAttr::IR_ARCForbiddenConversion:
5816 diag_available_here = diag::note_performs_forbidden_arc_conversion;
5819 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
5821 diag_available_here = diag::note_arc_init_returns_unrelated;
5824 case UnavailableAttr::IR_ARCFieldWithOwnership:
5826 diag_available_here = diag::note_arc_field_with_ownership;
5834 case Sema::AD_Partial:
5835 diag = diag::warn_partial_availability;
5836 diag_message = diag::warn_partial_message;
5837 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
5838 property_note_select = /* partial */ 2;
5839 available_here_select_kind = /* partial */ 3;
5843 if (!Message.empty()) {
5844 S.Diag(Loc, diag_message) << D << Message;
5846 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5847 << ObjCProperty->getDeclName() << property_note_select;
5848 } else if (!UnknownObjCClass) {
5849 S.Diag(Loc, diag) << D;
5851 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5852 << ObjCProperty->getDeclName() << property_note_select;
5854 S.Diag(Loc, diag_fwdclass_message) << D;
5855 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5858 S.Diag(D->getLocation(), diag_available_here)
5859 << D << available_here_select_kind;
5860 if (K == Sema::AD_Partial)
5861 S.Diag(Loc, diag::note_partial_availability_silence) << D;
5864 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
5866 assert(DD.Kind == DelayedDiagnostic::Deprecation ||
5867 DD.Kind == DelayedDiagnostic::Unavailable);
5868 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
5869 ? Sema::AD_Deprecation
5870 : Sema::AD_Unavailable;
5871 DD.Triggered = true;
5872 DoEmitAvailabilityWarning(
5873 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
5874 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
5877 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5878 assert(DelayedDiagnostics.getCurrentPool());
5879 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5880 DelayedDiagnostics.popWithoutEmitting(state);
5882 // When delaying diagnostics to run in the context of a parsed
5883 // declaration, we only want to actually emit anything if parsing
5887 // We emit all the active diagnostics in this pool or any of its
5888 // parents. In general, we'll get one pool for the decl spec
5889 // and a child pool for each declarator; in a decl group like:
5890 // deprecated_typedef foo, *bar, baz();
5891 // only the declarator pops will be passed decls. This is correct;
5892 // we really do need to consider delayed diagnostics from the decl spec
5893 // for each of the different declarations.
5894 const DelayedDiagnosticPool *pool = &poppedPool;
5896 for (DelayedDiagnosticPool::pool_iterator
5897 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5898 // This const_cast is a bit lame. Really, Triggered should be mutable.
5899 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5903 switch (diag.Kind) {
5904 case DelayedDiagnostic::Deprecation:
5905 case DelayedDiagnostic::Unavailable:
5906 // Don't bother giving deprecation/unavailable diagnostics if
5907 // the decl is invalid.
5908 if (!decl->isInvalidDecl())
5909 handleDelayedAvailabilityCheck(*this, diag, decl);
5912 case DelayedDiagnostic::Access:
5913 HandleDelayedAccessCheck(diag, decl);
5916 case DelayedDiagnostic::ForbiddenType:
5917 handleDelayedForbiddenType(*this, diag, decl);
5921 } while ((pool = pool->getParent()));
5924 /// Given a set of delayed diagnostics, re-emit them as if they had
5925 /// been delayed in the current context instead of in the given pool.
5926 /// Essentially, this just moves them to the current pool.
5927 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5928 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5929 assert(curPool && "re-emitting in undelayed context not supported");
5930 curPool->steal(pool);
5933 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
5934 NamedDecl *D, StringRef Message,
5936 const ObjCInterfaceDecl *UnknownObjCClass,
5937 const ObjCPropertyDecl *ObjCProperty,
5938 bool ObjCPropertyAccess) {
5939 // Delay if we're currently parsing a declaration.
5940 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
5941 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
5942 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
5943 ObjCPropertyAccess));
5947 Decl *Ctx = cast<Decl>(getCurLexicalContext());
5948 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
5949 ObjCProperty, ObjCPropertyAccess);