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 template <typename AttrType>
352 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
353 const AttributeList &Attr) {
354 handleSimpleAttribute<AttrType>(S, D, Attr);
357 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't
358 /// already have one of the given incompatible attributes.
359 template <typename AttrType, typename IncompatibleAttrType,
360 typename... IncompatibleAttrTypes>
361 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
362 const AttributeList &Attr) {
363 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
366 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
370 /// \brief Check if the passed-in expression is of type int or bool.
371 static bool isIntOrBool(Expr *Exp) {
372 QualType QT = Exp->getType();
373 return QT->isBooleanType() || QT->isIntegerType();
377 // Check to see if the type is a smart pointer of some kind. We assume
378 // it's a smart pointer if it defines both operator-> and operator*.
379 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
380 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
381 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
385 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
386 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
393 /// \brief Check if passed in Decl is a pointer type.
394 /// Note that this function may produce an error message.
395 /// \return true if the Decl is a pointer type; false otherwise
396 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
397 const AttributeList &Attr) {
398 const ValueDecl *vd = cast<ValueDecl>(D);
399 QualType QT = vd->getType();
400 if (QT->isAnyPointerType())
403 if (const RecordType *RT = QT->getAs<RecordType>()) {
404 // If it's an incomplete type, it could be a smart pointer; skip it.
405 // (We don't want to force template instantiation if we can avoid it,
406 // since that would alter the order in which templates are instantiated.)
407 if (RT->isIncompleteType())
410 if (threadSafetyCheckIsSmartPointer(S, RT))
414 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
415 << Attr.getName() << QT;
419 /// \brief Checks that the passed in QualType either is of RecordType or points
420 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
421 static const RecordType *getRecordType(QualType QT) {
422 if (const RecordType *RT = QT->getAs<RecordType>())
425 // Now check if we point to record type.
426 if (const PointerType *PT = QT->getAs<PointerType>())
427 return PT->getPointeeType()->getAs<RecordType>();
432 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
433 const RecordType *RT = getRecordType(Ty);
438 // Don't check for the capability if the class hasn't been defined yet.
439 if (RT->isIncompleteType())
442 // Allow smart pointers to be used as capability objects.
443 // FIXME -- Check the type that the smart pointer points to.
444 if (threadSafetyCheckIsSmartPointer(S, RT))
447 // Check if the record itself has a capability.
448 RecordDecl *RD = RT->getDecl();
449 if (RD->hasAttr<CapabilityAttr>())
452 // Else check if any base classes have a capability.
453 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
454 CXXBasePaths BPaths(false, false);
455 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
456 const auto *Type = BS->getType()->getAs<RecordType>();
457 return Type->getDecl()->hasAttr<CapabilityAttr>();
464 static bool checkTypedefTypeForCapability(QualType Ty) {
465 const auto *TD = Ty->getAs<TypedefType>();
469 TypedefNameDecl *TN = TD->getDecl();
473 return TN->hasAttr<CapabilityAttr>();
476 static bool typeHasCapability(Sema &S, QualType Ty) {
477 if (checkTypedefTypeForCapability(Ty))
480 if (checkRecordTypeForCapability(S, Ty))
486 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
487 // Capability expressions are simple expressions involving the boolean logic
488 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
489 // a DeclRefExpr is found, its type should be checked to determine whether it
490 // is a capability or not.
492 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
493 return typeHasCapability(S, E->getType());
494 else if (const auto *E = dyn_cast<CastExpr>(Ex))
495 return isCapabilityExpr(S, E->getSubExpr());
496 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
497 return isCapabilityExpr(S, E->getSubExpr());
498 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
499 if (E->getOpcode() == UO_LNot)
500 return isCapabilityExpr(S, E->getSubExpr());
502 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
503 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
504 return isCapabilityExpr(S, E->getLHS()) &&
505 isCapabilityExpr(S, E->getRHS());
512 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
513 /// a capability object.
514 /// \param Sidx The attribute argument index to start checking with.
515 /// \param ParamIdxOk Whether an argument can be indexing into a function
517 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
518 const AttributeList &Attr,
519 SmallVectorImpl<Expr *> &Args,
521 bool ParamIdxOk = false) {
522 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
523 Expr *ArgExp = Attr.getArgAsExpr(Idx);
525 if (ArgExp->isTypeDependent()) {
526 // FIXME -- need to check this again on template instantiation
527 Args.push_back(ArgExp);
531 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
532 if (StrLit->getLength() == 0 ||
533 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
534 // Pass empty strings to the analyzer without warnings.
535 // Treat "*" as the universal lock.
536 Args.push_back(ArgExp);
540 // We allow constant strings to be used as a placeholder for expressions
541 // that are not valid C++ syntax, but warn that they are ignored.
542 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
544 Args.push_back(ArgExp);
548 QualType ArgTy = ArgExp->getType();
550 // A pointer to member expression of the form &MyClass::mu is treated
551 // specially -- we need to look at the type of the member.
552 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
553 if (UOp->getOpcode() == UO_AddrOf)
554 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
555 if (DRE->getDecl()->isCXXInstanceMember())
556 ArgTy = DRE->getDecl()->getType();
558 // First see if we can just cast to record type, or pointer to record type.
559 const RecordType *RT = getRecordType(ArgTy);
561 // Now check if we index into a record type function param.
562 if(!RT && ParamIdxOk) {
563 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
564 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
566 unsigned int NumParams = FD->getNumParams();
567 llvm::APInt ArgValue = IL->getValue();
568 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
569 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
570 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
571 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
572 << Attr.getName() << Idx + 1 << NumParams;
575 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
579 // If the type does not have a capability, see if the components of the
580 // expression have capabilities. This allows for writing C code where the
581 // capability may be on the type, and the expression is a capability
582 // boolean logic expression. Eg) requires_capability(A || B && !C)
583 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
584 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
585 << Attr.getName() << ArgTy;
587 Args.push_back(ArgExp);
591 //===----------------------------------------------------------------------===//
592 // Attribute Implementations
593 //===----------------------------------------------------------------------===//
595 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
596 const AttributeList &Attr) {
597 if (!threadSafetyCheckIsPointer(S, D, Attr))
600 D->addAttr(::new (S.Context)
601 PtGuardedVarAttr(Attr.getRange(), S.Context,
602 Attr.getAttributeSpellingListIndex()));
605 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
606 const AttributeList &Attr,
608 SmallVector<Expr*, 1> Args;
609 // check that all arguments are lockable objects
610 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
611 unsigned Size = Args.size();
620 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
622 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
625 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
626 Attr.getAttributeSpellingListIndex()));
629 static void handlePtGuardedByAttr(Sema &S, Decl *D,
630 const AttributeList &Attr) {
632 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
635 if (!threadSafetyCheckIsPointer(S, D, Attr))
638 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
640 Attr.getAttributeSpellingListIndex()));
643 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
644 const AttributeList &Attr,
645 SmallVectorImpl<Expr *> &Args) {
646 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
649 // Check that this attribute only applies to lockable types.
650 QualType QT = cast<ValueDecl>(D)->getType();
651 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
652 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
657 // Check that all arguments are lockable objects.
658 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
665 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
666 const AttributeList &Attr) {
667 SmallVector<Expr*, 1> Args;
668 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
671 Expr **StartArg = &Args[0];
672 D->addAttr(::new (S.Context)
673 AcquiredAfterAttr(Attr.getRange(), S.Context,
674 StartArg, Args.size(),
675 Attr.getAttributeSpellingListIndex()));
678 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
679 const AttributeList &Attr) {
680 SmallVector<Expr*, 1> Args;
681 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
684 Expr **StartArg = &Args[0];
685 D->addAttr(::new (S.Context)
686 AcquiredBeforeAttr(Attr.getRange(), S.Context,
687 StartArg, Args.size(),
688 Attr.getAttributeSpellingListIndex()));
691 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
692 const AttributeList &Attr,
693 SmallVectorImpl<Expr *> &Args) {
694 // zero or more arguments ok
695 // check that all arguments are lockable objects
696 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
701 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
702 const AttributeList &Attr) {
703 SmallVector<Expr*, 1> Args;
704 if (!checkLockFunAttrCommon(S, D, Attr, Args))
707 unsigned Size = Args.size();
708 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
709 D->addAttr(::new (S.Context)
710 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
711 Attr.getAttributeSpellingListIndex()));
714 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
715 const AttributeList &Attr) {
716 SmallVector<Expr*, 1> Args;
717 if (!checkLockFunAttrCommon(S, D, Attr, Args))
720 unsigned Size = Args.size();
721 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
722 D->addAttr(::new (S.Context)
723 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
725 Attr.getAttributeSpellingListIndex()));
729 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
730 const AttributeList &Attr,
731 SmallVectorImpl<Expr *> &Args) {
732 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
735 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
736 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
737 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
741 // check that all arguments are lockable objects
742 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
747 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
748 const AttributeList &Attr) {
749 SmallVector<Expr*, 2> Args;
750 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
753 D->addAttr(::new (S.Context)
754 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
755 Attr.getArgAsExpr(0),
756 Args.data(), Args.size(),
757 Attr.getAttributeSpellingListIndex()));
760 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
761 const AttributeList &Attr) {
762 SmallVector<Expr*, 2> Args;
763 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
766 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
767 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
768 Args.size(), Attr.getAttributeSpellingListIndex()));
771 static void handleLockReturnedAttr(Sema &S, Decl *D,
772 const AttributeList &Attr) {
773 // check that the argument is lockable object
774 SmallVector<Expr*, 1> Args;
775 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
776 unsigned Size = Args.size();
780 D->addAttr(::new (S.Context)
781 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
782 Attr.getAttributeSpellingListIndex()));
785 static void handleLocksExcludedAttr(Sema &S, Decl *D,
786 const AttributeList &Attr) {
787 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
790 // check that all arguments are lockable objects
791 SmallVector<Expr*, 1> Args;
792 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
793 unsigned Size = Args.size();
796 Expr **StartArg = &Args[0];
798 D->addAttr(::new (S.Context)
799 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
800 Attr.getAttributeSpellingListIndex()));
803 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
804 Expr *Cond = Attr.getArgAsExpr(0);
805 if (!Cond->isTypeDependent()) {
806 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
807 if (Converted.isInvalid())
809 Cond = Converted.get();
813 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
816 SmallVector<PartialDiagnosticAt, 8> Diags;
817 if (!Cond->isValueDependent() &&
818 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
820 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
821 for (int I = 0, N = Diags.size(); I != N; ++I)
822 S.Diag(Diags[I].first, Diags[I].second);
826 D->addAttr(::new (S.Context)
827 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
828 Attr.getAttributeSpellingListIndex()));
831 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
832 const AttributeList &Attr) {
833 if (D->hasAttr<PassObjectSizeAttr>()) {
834 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
839 Expr *E = Attr.getArgAsExpr(0);
841 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
844 // pass_object_size's argument is passed in as the second argument of
845 // __builtin_object_size. So, it has the same constraints as that second
846 // argument; namely, it must be in the range [0, 3].
848 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
849 << Attr.getName() << 0 << 3 << E->getSourceRange();
853 // pass_object_size is only supported on constant pointer parameters; as a
854 // kindness to users, we allow the parameter to be non-const for declarations.
855 // At this point, we have no clue if `D` belongs to a function declaration or
856 // definition, so we defer the constness check until later.
857 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
858 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
859 << Attr.getName() << 1;
863 D->addAttr(::new (S.Context)
864 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
865 Attr.getAttributeSpellingListIndex()));
868 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
869 ConsumableAttr::ConsumedState DefaultState;
871 if (Attr.isArgIdent(0)) {
872 IdentifierLoc *IL = Attr.getArgAsIdent(0);
873 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
875 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
876 << Attr.getName() << IL->Ident;
880 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
881 << Attr.getName() << AANT_ArgumentIdentifier;
885 D->addAttr(::new (S.Context)
886 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
887 Attr.getAttributeSpellingListIndex()));
891 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
892 const AttributeList &Attr) {
893 ASTContext &CurrContext = S.getASTContext();
894 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
896 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
897 if (!RD->hasAttr<ConsumableAttr>()) {
898 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
899 RD->getNameAsString();
909 static void handleCallableWhenAttr(Sema &S, Decl *D,
910 const AttributeList &Attr) {
911 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
914 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
917 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
918 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
919 CallableWhenAttr::ConsumedState CallableState;
921 StringRef StateString;
923 if (Attr.isArgIdent(ArgIndex)) {
924 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
925 StateString = Ident->Ident->getName();
928 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
932 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
934 S.Diag(Loc, diag::warn_attribute_type_not_supported)
935 << Attr.getName() << StateString;
939 States.push_back(CallableState);
942 D->addAttr(::new (S.Context)
943 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
944 States.size(), Attr.getAttributeSpellingListIndex()));
948 static void handleParamTypestateAttr(Sema &S, Decl *D,
949 const AttributeList &Attr) {
950 ParamTypestateAttr::ConsumedState ParamState;
952 if (Attr.isArgIdent(0)) {
953 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
954 StringRef StateString = Ident->Ident->getName();
956 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
958 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
959 << Attr.getName() << StateString;
963 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
964 Attr.getName() << AANT_ArgumentIdentifier;
968 // FIXME: This check is currently being done in the analysis. It can be
969 // enabled here only after the parser propagates attributes at
970 // template specialization definition, not declaration.
971 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
972 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
974 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
975 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
976 // ReturnType.getAsString();
980 D->addAttr(::new (S.Context)
981 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
982 Attr.getAttributeSpellingListIndex()));
986 static void handleReturnTypestateAttr(Sema &S, Decl *D,
987 const AttributeList &Attr) {
988 ReturnTypestateAttr::ConsumedState ReturnState;
990 if (Attr.isArgIdent(0)) {
991 IdentifierLoc *IL = Attr.getArgAsIdent(0);
992 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
994 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
995 << Attr.getName() << IL->Ident;
999 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1000 Attr.getName() << AANT_ArgumentIdentifier;
1004 // FIXME: This check is currently being done in the analysis. It can be
1005 // enabled here only after the parser propagates attributes at
1006 // template specialization definition, not declaration.
1007 //QualType ReturnType;
1009 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1010 // ReturnType = Param->getType();
1012 //} else if (const CXXConstructorDecl *Constructor =
1013 // dyn_cast<CXXConstructorDecl>(D)) {
1014 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1018 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1021 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1023 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1024 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1025 // ReturnType.getAsString();
1029 D->addAttr(::new (S.Context)
1030 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1031 Attr.getAttributeSpellingListIndex()));
1035 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1036 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1039 SetTypestateAttr::ConsumedState NewState;
1040 if (Attr.isArgIdent(0)) {
1041 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1042 StringRef Param = Ident->Ident->getName();
1043 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1044 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1045 << Attr.getName() << Param;
1049 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1050 Attr.getName() << AANT_ArgumentIdentifier;
1054 D->addAttr(::new (S.Context)
1055 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1056 Attr.getAttributeSpellingListIndex()));
1059 static void handleTestTypestateAttr(Sema &S, Decl *D,
1060 const AttributeList &Attr) {
1061 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1064 TestTypestateAttr::ConsumedState TestState;
1065 if (Attr.isArgIdent(0)) {
1066 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1067 StringRef Param = Ident->Ident->getName();
1068 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1069 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1070 << Attr.getName() << Param;
1074 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1075 Attr.getName() << AANT_ArgumentIdentifier;
1079 D->addAttr(::new (S.Context)
1080 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1081 Attr.getAttributeSpellingListIndex()));
1084 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1085 const AttributeList &Attr) {
1086 // Remember this typedef decl, we will need it later for diagnostics.
1087 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1090 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1091 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1092 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1093 Attr.getAttributeSpellingListIndex()));
1094 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1095 // Report warning about changed offset in the newer compiler versions.
1096 if (!FD->getType()->isDependentType() &&
1097 !FD->getType()->isIncompleteType() && FD->isBitField() &&
1098 S.Context.getTypeAlign(FD->getType()) <= 8)
1099 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1101 FD->addAttr(::new (S.Context) PackedAttr(
1102 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1104 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1107 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1108 // The IBOutlet/IBOutletCollection attributes only apply to instance
1109 // variables or properties of Objective-C classes. The outlet must also
1110 // have an object reference type.
1111 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1112 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1113 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1114 << Attr.getName() << VD->getType() << 0;
1118 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1119 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1120 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1121 << Attr.getName() << PD->getType() << 1;
1126 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1133 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1134 if (!checkIBOutletCommon(S, D, Attr))
1137 D->addAttr(::new (S.Context)
1138 IBOutletAttr(Attr.getRange(), S.Context,
1139 Attr.getAttributeSpellingListIndex()));
1142 static void handleIBOutletCollection(Sema &S, Decl *D,
1143 const AttributeList &Attr) {
1145 // The iboutletcollection attribute can have zero or one arguments.
1146 if (Attr.getNumArgs() > 1) {
1147 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1148 << Attr.getName() << 1;
1152 if (!checkIBOutletCommon(S, D, Attr))
1157 if (Attr.hasParsedType())
1158 PT = Attr.getTypeArg();
1160 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1161 S.getScopeForContext(D->getDeclContext()->getParent()));
1163 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1168 TypeSourceInfo *QTLoc = nullptr;
1169 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1171 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1173 // Diagnose use of non-object type in iboutletcollection attribute.
1174 // FIXME. Gnu attribute extension ignores use of builtin types in
1175 // attributes. So, __attribute__((iboutletcollection(char))) will be
1176 // treated as __attribute__((iboutletcollection())).
1177 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1178 S.Diag(Attr.getLoc(),
1179 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1180 : diag::err_iboutletcollection_type) << QT;
1184 D->addAttr(::new (S.Context)
1185 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1186 Attr.getAttributeSpellingListIndex()));
1189 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1191 if (T->isReferenceType())
1194 T = T.getNonReferenceType();
1197 // The nonnull attribute, and other similar attributes, can be applied to a
1198 // transparent union that contains a pointer type.
1199 if (const RecordType *UT = T->getAsUnionType()) {
1200 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1201 RecordDecl *UD = UT->getDecl();
1202 for (const auto *I : UD->fields()) {
1203 QualType QT = I->getType();
1204 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1210 return T->isAnyPointerType() || T->isBlockPointerType();
1213 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1214 SourceRange AttrParmRange,
1215 SourceRange TypeRange,
1216 bool isReturnValue = false) {
1217 if (!S.isValidPointerAttrType(T)) {
1219 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1220 << Attr.getName() << AttrParmRange << TypeRange;
1222 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1223 << Attr.getName() << AttrParmRange << TypeRange << 0;
1229 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1230 SmallVector<unsigned, 8> NonNullArgs;
1231 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1232 Expr *Ex = Attr.getArgAsExpr(I);
1234 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1237 // Is the function argument a pointer type?
1238 if (Idx < getFunctionOrMethodNumParams(D) &&
1239 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1240 Ex->getSourceRange(),
1241 getFunctionOrMethodParamRange(D, Idx)))
1244 NonNullArgs.push_back(Idx);
1247 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1248 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1249 // check if the attribute came from a macro expansion or a template
1251 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1252 S.ActiveTemplateInstantiations.empty()) {
1253 bool AnyPointers = isFunctionOrMethodVariadic(D);
1254 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1255 I != E && !AnyPointers; ++I) {
1256 QualType T = getFunctionOrMethodParamType(D, I);
1257 if (T->isDependentType() || S.isValidPointerAttrType(T))
1262 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1265 unsigned *Start = NonNullArgs.data();
1266 unsigned Size = NonNullArgs.size();
1267 llvm::array_pod_sort(Start, Start + Size);
1268 D->addAttr(::new (S.Context)
1269 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1270 Attr.getAttributeSpellingListIndex()));
1273 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1274 const AttributeList &Attr) {
1275 if (Attr.getNumArgs() > 0) {
1276 if (D->getFunctionType()) {
1277 handleNonNullAttr(S, D, Attr);
1279 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1280 << D->getSourceRange();
1285 // Is the argument a pointer type?
1286 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1287 D->getSourceRange()))
1290 D->addAttr(::new (S.Context)
1291 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1292 Attr.getAttributeSpellingListIndex()));
1295 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1296 const AttributeList &Attr) {
1297 QualType ResultType = getFunctionOrMethodResultType(D);
1298 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1299 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1300 /* isReturnValue */ true))
1303 D->addAttr(::new (S.Context)
1304 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1305 Attr.getAttributeSpellingListIndex()));
1308 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1309 const AttributeList &Attr) {
1310 Expr *E = Attr.getArgAsExpr(0),
1311 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1312 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1313 Attr.getAttributeSpellingListIndex());
1316 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1317 Expr *OE, unsigned SpellingListIndex) {
1318 QualType ResultType = getFunctionOrMethodResultType(D);
1319 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1321 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1322 SourceLocation AttrLoc = AttrRange.getBegin();
1324 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1325 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1326 << &TmpAttr << AttrRange << SR;
1330 if (!E->isValueDependent()) {
1332 if (!E->isIntegerConstantExpr(I, Context)) {
1334 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1335 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1336 << E->getSourceRange();
1338 Diag(AttrLoc, diag::err_attribute_argument_type)
1339 << &TmpAttr << AANT_ArgumentIntegerConstant
1340 << E->getSourceRange();
1344 if (!I.isPowerOf2()) {
1345 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1346 << E->getSourceRange();
1352 if (!OE->isValueDependent()) {
1354 if (!OE->isIntegerConstantExpr(I, Context)) {
1355 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1356 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1357 << OE->getSourceRange();
1363 D->addAttr(::new (Context)
1364 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1367 /// Normalize the attribute, __foo__ becomes foo.
1368 /// Returns true if normalization was applied.
1369 static bool normalizeName(StringRef &AttrName) {
1370 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1371 AttrName.endswith("__")) {
1372 AttrName = AttrName.drop_front(2).drop_back(2);
1378 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1379 // This attribute must be applied to a function declaration. The first
1380 // argument to the attribute must be an identifier, the name of the resource,
1381 // for example: malloc. The following arguments must be argument indexes, the
1382 // arguments must be of integer type for Returns, otherwise of pointer type.
1383 // The difference between Holds and Takes is that a pointer may still be used
1384 // after being held. free() should be __attribute((ownership_takes)), whereas
1385 // a list append function may well be __attribute((ownership_holds)).
1387 if (!AL.isArgIdent(0)) {
1388 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1389 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1393 // Figure out our Kind.
1394 OwnershipAttr::OwnershipKind K =
1395 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1396 AL.getAttributeSpellingListIndex()).getOwnKind();
1400 case OwnershipAttr::Takes:
1401 case OwnershipAttr::Holds:
1402 if (AL.getNumArgs() < 2) {
1403 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1404 << AL.getName() << 2;
1408 case OwnershipAttr::Returns:
1409 if (AL.getNumArgs() > 2) {
1410 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1411 << AL.getName() << 1;
1417 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1419 StringRef ModuleName = Module->getName();
1420 if (normalizeName(ModuleName)) {
1421 Module = &S.PP.getIdentifierTable().get(ModuleName);
1424 SmallVector<unsigned, 8> OwnershipArgs;
1425 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1426 Expr *Ex = AL.getArgAsExpr(i);
1428 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1431 // Is the function argument a pointer type?
1432 QualType T = getFunctionOrMethodParamType(D, Idx);
1433 int Err = -1; // No error
1435 case OwnershipAttr::Takes:
1436 case OwnershipAttr::Holds:
1437 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1440 case OwnershipAttr::Returns:
1441 if (!T->isIntegerType())
1446 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1447 << Ex->getSourceRange();
1451 // Check we don't have a conflict with another ownership attribute.
1452 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1453 // Cannot have two ownership attributes of different kinds for the same
1455 if (I->getOwnKind() != K && I->args_end() !=
1456 std::find(I->args_begin(), I->args_end(), Idx)) {
1457 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1458 << AL.getName() << I;
1460 } else if (K == OwnershipAttr::Returns &&
1461 I->getOwnKind() == OwnershipAttr::Returns) {
1462 // A returns attribute conflicts with any other returns attribute using
1463 // a different index. Note, diagnostic reporting is 1-based, but stored
1464 // argument indexes are 0-based.
1465 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1466 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1467 << *(I->args_begin()) + 1;
1469 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1470 << (unsigned)Idx + 1 << Ex->getSourceRange();
1475 OwnershipArgs.push_back(Idx);
1478 unsigned* start = OwnershipArgs.data();
1479 unsigned size = OwnershipArgs.size();
1480 llvm::array_pod_sort(start, start + size);
1482 D->addAttr(::new (S.Context)
1483 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1484 AL.getAttributeSpellingListIndex()));
1487 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1488 // Check the attribute arguments.
1489 if (Attr.getNumArgs() > 1) {
1490 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1491 << Attr.getName() << 1;
1495 NamedDecl *nd = cast<NamedDecl>(D);
1499 // static int a __attribute__((weakref ("v2")));
1500 // static int b() __attribute__((weakref ("f3")));
1502 // and ignores the attributes of
1504 // static int a __attribute__((weakref ("v2")));
1507 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1508 if (!Ctx->isFileContext()) {
1509 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1514 // The GCC manual says
1516 // At present, a declaration to which `weakref' is attached can only
1521 // Without a TARGET,
1522 // given as an argument to `weakref' or to `alias', `weakref' is
1523 // equivalent to `weak'.
1525 // gcc 4.4.1 will accept
1526 // int a7 __attribute__((weakref));
1528 // int a7 __attribute__((weak));
1529 // This looks like a bug in gcc. We reject that for now. We should revisit
1530 // it if this behaviour is actually used.
1533 // static ((alias ("y"), weakref)).
1534 // Should we? How to check that weakref is before or after alias?
1536 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1537 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1538 // StringRef parameter it was given anyway.
1540 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1541 // GCC will accept anything as the argument of weakref. Should we
1542 // check for an existing decl?
1543 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1544 Attr.getAttributeSpellingListIndex()));
1546 D->addAttr(::new (S.Context)
1547 WeakRefAttr(Attr.getRange(), S.Context,
1548 Attr.getAttributeSpellingListIndex()));
1551 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1553 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1556 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1557 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1561 // Aliases should be on declarations, not definitions.
1562 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1563 if (FD->isThisDeclarationADefinition()) {
1564 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
1568 const auto *VD = cast<VarDecl>(D);
1569 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1570 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
1575 // FIXME: check if target symbol exists in current file
1577 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1578 Attr.getAttributeSpellingListIndex()));
1581 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1582 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1585 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1586 Attr.getAttributeSpellingListIndex()));
1589 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1590 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1593 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1594 Attr.getAttributeSpellingListIndex()));
1597 static void handleTLSModelAttr(Sema &S, Decl *D,
1598 const AttributeList &Attr) {
1600 SourceLocation LiteralLoc;
1601 // Check that it is a string.
1602 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1605 // Check that the value.
1606 if (Model != "global-dynamic" && Model != "local-dynamic"
1607 && Model != "initial-exec" && Model != "local-exec") {
1608 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1612 D->addAttr(::new (S.Context)
1613 TLSModelAttr(Attr.getRange(), S.Context, Model,
1614 Attr.getAttributeSpellingListIndex()));
1617 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1618 QualType ResultType = getFunctionOrMethodResultType(D);
1619 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1620 D->addAttr(::new (S.Context) RestrictAttr(
1621 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1625 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1626 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1629 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1630 if (S.LangOpts.CPlusPlus) {
1631 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1632 << Attr.getName() << AttributeLangSupport::Cpp;
1636 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1637 Attr.getAttributeSpellingListIndex()))
1641 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1642 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1646 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1647 Attr.getAttributeSpellingListIndex()));
1650 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1651 if (hasDeclarator(D)) return;
1653 if (S.CheckNoReturnAttr(attr)) return;
1655 if (!isa<ObjCMethodDecl>(D)) {
1656 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1657 << attr.getName() << ExpectedFunctionOrMethod;
1661 D->addAttr(::new (S.Context)
1662 NoReturnAttr(attr.getRange(), S.Context,
1663 attr.getAttributeSpellingListIndex()));
1666 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1667 if (!checkAttributeNumArgs(*this, attr, 0)) {
1675 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1676 const AttributeList &Attr) {
1678 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1679 // because 'analyzer_noreturn' does not impact the type.
1680 if (!isFunctionOrMethodOrBlock(D)) {
1681 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1682 if (!VD || (!VD->getType()->isBlockPointerType() &&
1683 !VD->getType()->isFunctionPointerType())) {
1684 S.Diag(Attr.getLoc(),
1685 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1686 : diag::warn_attribute_wrong_decl_type)
1687 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1692 D->addAttr(::new (S.Context)
1693 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1694 Attr.getAttributeSpellingListIndex()));
1697 // PS3 PPU-specific.
1698 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1700 Returning a Vector Class in Registers
1702 According to the PPU ABI specifications, a class with a single member of
1703 vector type is returned in memory when used as the return value of a function.
1704 This results in inefficient code when implementing vector classes. To return
1705 the value in a single vector register, add the vecreturn attribute to the
1706 class definition. This attribute is also applicable to struct types.
1712 __vector float xyzw;
1713 } __attribute__((vecreturn));
1715 Vector Add(Vector lhs, Vector rhs)
1718 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1719 return result; // This will be returned in a register
1722 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1723 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1727 RecordDecl *record = cast<RecordDecl>(D);
1730 if (!isa<CXXRecordDecl>(record)) {
1731 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1735 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1736 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1740 for (const auto *I : record->fields()) {
1741 if ((count == 1) || !I->getType()->isVectorType()) {
1742 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1748 D->addAttr(::new (S.Context)
1749 VecReturnAttr(Attr.getRange(), S.Context,
1750 Attr.getAttributeSpellingListIndex()));
1753 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1754 const AttributeList &Attr) {
1755 if (isa<ParmVarDecl>(D)) {
1756 // [[carries_dependency]] can only be applied to a parameter if it is a
1757 // parameter of a function declaration or lambda.
1758 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1759 S.Diag(Attr.getLoc(),
1760 diag::err_carries_dependency_param_not_function_decl);
1765 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1766 Attr.getRange(), S.Context,
1767 Attr.getAttributeSpellingListIndex()));
1770 static void handleNotTailCalledAttr(Sema &S, Decl *D,
1771 const AttributeList &Attr) {
1772 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1776 D->addAttr(::new (S.Context) NotTailCalledAttr(
1777 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1780 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1781 const AttributeList &Attr) {
1782 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1786 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1787 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1790 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1791 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1792 if (VD->hasLocalStorage()) {
1793 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1796 } else if (!isFunctionOrMethod(D)) {
1797 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1798 << Attr.getName() << ExpectedVariableOrFunction;
1802 D->addAttr(::new (S.Context)
1803 UsedAttr(Attr.getRange(), S.Context,
1804 Attr.getAttributeSpellingListIndex()));
1807 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1808 uint32_t priority = ConstructorAttr::DefaultPriority;
1809 if (Attr.getNumArgs() &&
1810 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1813 D->addAttr(::new (S.Context)
1814 ConstructorAttr(Attr.getRange(), S.Context, priority,
1815 Attr.getAttributeSpellingListIndex()));
1818 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1819 uint32_t priority = DestructorAttr::DefaultPriority;
1820 if (Attr.getNumArgs() &&
1821 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1824 D->addAttr(::new (S.Context)
1825 DestructorAttr(Attr.getRange(), S.Context, priority,
1826 Attr.getAttributeSpellingListIndex()));
1829 template <typename AttrTy>
1830 static void handleAttrWithMessage(Sema &S, Decl *D,
1831 const AttributeList &Attr) {
1832 // Handle the case where the attribute has a text message.
1834 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1837 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1838 Attr.getAttributeSpellingListIndex()));
1841 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1842 const AttributeList &Attr) {
1843 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1844 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1845 << Attr.getName() << Attr.getRange();
1849 D->addAttr(::new (S.Context)
1850 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1851 Attr.getAttributeSpellingListIndex()));
1854 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1855 IdentifierInfo *Platform,
1856 VersionTuple Introduced,
1857 VersionTuple Deprecated,
1858 VersionTuple Obsoleted) {
1859 StringRef PlatformName
1860 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1861 if (PlatformName.empty())
1862 PlatformName = Platform->getName();
1864 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1865 // of these steps are needed).
1866 if (!Introduced.empty() && !Deprecated.empty() &&
1867 !(Introduced <= Deprecated)) {
1868 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1869 << 1 << PlatformName << Deprecated.getAsString()
1870 << 0 << Introduced.getAsString();
1874 if (!Introduced.empty() && !Obsoleted.empty() &&
1875 !(Introduced <= Obsoleted)) {
1876 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1877 << 2 << PlatformName << Obsoleted.getAsString()
1878 << 0 << Introduced.getAsString();
1882 if (!Deprecated.empty() && !Obsoleted.empty() &&
1883 !(Deprecated <= Obsoleted)) {
1884 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1885 << 2 << PlatformName << Obsoleted.getAsString()
1886 << 1 << Deprecated.getAsString();
1893 /// \brief Check whether the two versions match.
1895 /// If either version tuple is empty, then they are assumed to match. If
1896 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1897 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1898 bool BeforeIsOkay) {
1899 if (X.empty() || Y.empty())
1905 if (BeforeIsOkay && X < Y)
1911 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1912 IdentifierInfo *Platform,
1913 VersionTuple Introduced,
1914 VersionTuple Deprecated,
1915 VersionTuple Obsoleted,
1918 AvailabilityMergeKind AMK,
1919 unsigned AttrSpellingListIndex) {
1920 VersionTuple MergedIntroduced = Introduced;
1921 VersionTuple MergedDeprecated = Deprecated;
1922 VersionTuple MergedObsoleted = Obsoleted;
1923 bool FoundAny = false;
1924 bool OverrideOrImpl = false;
1927 case AMK_Redeclaration:
1928 OverrideOrImpl = false;
1932 case AMK_ProtocolImplementation:
1933 OverrideOrImpl = true;
1937 if (D->hasAttrs()) {
1938 AttrVec &Attrs = D->getAttrs();
1939 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1940 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1946 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1947 if (OldPlatform != Platform) {
1952 // If there is an existing availability attribute for this platform that
1953 // is explicit and the new one is implicit use the explicit one and
1954 // discard the new implicit attribute.
1955 if (OldAA->getRange().isValid() && Range.isInvalid()) {
1959 // If there is an existing attribute for this platform that is implicit
1960 // and the new attribute is explicit then erase the old one and
1961 // continue processing the attributes.
1962 if (Range.isValid() && OldAA->getRange().isInvalid()) {
1963 Attrs.erase(Attrs.begin() + i);
1969 VersionTuple OldIntroduced = OldAA->getIntroduced();
1970 VersionTuple OldDeprecated = OldAA->getDeprecated();
1971 VersionTuple OldObsoleted = OldAA->getObsoleted();
1972 bool OldIsUnavailable = OldAA->getUnavailable();
1974 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
1975 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
1976 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
1977 !(OldIsUnavailable == IsUnavailable ||
1978 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
1979 if (OverrideOrImpl) {
1981 VersionTuple FirstVersion;
1982 VersionTuple SecondVersion;
1983 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
1985 FirstVersion = OldIntroduced;
1986 SecondVersion = Introduced;
1987 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
1989 FirstVersion = Deprecated;
1990 SecondVersion = OldDeprecated;
1991 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
1993 FirstVersion = Obsoleted;
1994 SecondVersion = OldObsoleted;
1998 Diag(OldAA->getLocation(),
1999 diag::warn_mismatched_availability_override_unavail)
2000 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2001 << (AMK == AMK_Override);
2003 Diag(OldAA->getLocation(),
2004 diag::warn_mismatched_availability_override)
2006 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2007 << FirstVersion.getAsString() << SecondVersion.getAsString()
2008 << (AMK == AMK_Override);
2010 if (AMK == AMK_Override)
2011 Diag(Range.getBegin(), diag::note_overridden_method);
2013 Diag(Range.getBegin(), diag::note_protocol_method);
2015 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2016 Diag(Range.getBegin(), diag::note_previous_attribute);
2019 Attrs.erase(Attrs.begin() + i);
2024 VersionTuple MergedIntroduced2 = MergedIntroduced;
2025 VersionTuple MergedDeprecated2 = MergedDeprecated;
2026 VersionTuple MergedObsoleted2 = MergedObsoleted;
2028 if (MergedIntroduced2.empty())
2029 MergedIntroduced2 = OldIntroduced;
2030 if (MergedDeprecated2.empty())
2031 MergedDeprecated2 = OldDeprecated;
2032 if (MergedObsoleted2.empty())
2033 MergedObsoleted2 = OldObsoleted;
2035 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2036 MergedIntroduced2, MergedDeprecated2,
2037 MergedObsoleted2)) {
2038 Attrs.erase(Attrs.begin() + i);
2043 MergedIntroduced = MergedIntroduced2;
2044 MergedDeprecated = MergedDeprecated2;
2045 MergedObsoleted = MergedObsoleted2;
2051 MergedIntroduced == Introduced &&
2052 MergedDeprecated == Deprecated &&
2053 MergedObsoleted == Obsoleted)
2056 // Only create a new attribute if !OverrideOrImpl, but we want to do
2058 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2059 MergedDeprecated, MergedObsoleted) &&
2061 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
2062 Introduced, Deprecated,
2063 Obsoleted, IsUnavailable, Message,
2064 AttrSpellingListIndex);
2069 static void handleAvailabilityAttr(Sema &S, Decl *D,
2070 const AttributeList &Attr) {
2071 if (!checkAttributeNumArgs(S, Attr, 1))
2073 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2074 unsigned Index = Attr.getAttributeSpellingListIndex();
2076 IdentifierInfo *II = Platform->Ident;
2077 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2078 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2081 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2083 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2087 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2088 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2089 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2090 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2092 if (const StringLiteral *SE =
2093 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2094 Str = SE->getString();
2096 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2104 D->addAttr(NewAttr);
2106 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2107 // matches before the start of the watchOS platform.
2108 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2109 IdentifierInfo *NewII = nullptr;
2110 if (II->getName() == "ios")
2111 NewII = &S.Context.Idents.get("watchos");
2112 else if (II->getName() == "ios_app_extension")
2113 NewII = &S.Context.Idents.get("watchos_app_extension");
2116 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2117 if (Version.empty())
2119 auto Major = Version.getMajor();
2120 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2121 if (NewMajor >= 2) {
2122 if (Version.getMinor().hasValue()) {
2123 if (Version.getSubminor().hasValue())
2124 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2125 Version.getSubminor().getValue());
2127 return VersionTuple(NewMajor, Version.getMinor().getValue());
2131 return VersionTuple(2, 0);
2134 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2135 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2136 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2138 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2148 D->addAttr(NewAttr);
2150 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2151 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2152 // matches before the start of the tvOS platform.
2153 IdentifierInfo *NewII = nullptr;
2154 if (II->getName() == "ios")
2155 NewII = &S.Context.Idents.get("tvos");
2156 else if (II->getName() == "ios_app_extension")
2157 NewII = &S.Context.Idents.get("tvos_app_extension");
2160 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2170 D->addAttr(NewAttr);
2176 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2177 typename T::VisibilityType value,
2178 unsigned attrSpellingListIndex) {
2179 T *existingAttr = D->getAttr<T>();
2181 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2182 if (existingValue == value)
2184 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2185 S.Diag(range.getBegin(), diag::note_previous_attribute);
2188 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2191 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2192 VisibilityAttr::VisibilityType Vis,
2193 unsigned AttrSpellingListIndex) {
2194 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2195 AttrSpellingListIndex);
2198 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2199 TypeVisibilityAttr::VisibilityType Vis,
2200 unsigned AttrSpellingListIndex) {
2201 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2202 AttrSpellingListIndex);
2205 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2206 bool isTypeVisibility) {
2207 // Visibility attributes don't mean anything on a typedef.
2208 if (isa<TypedefNameDecl>(D)) {
2209 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2214 // 'type_visibility' can only go on a type or namespace.
2215 if (isTypeVisibility &&
2216 !(isa<TagDecl>(D) ||
2217 isa<ObjCInterfaceDecl>(D) ||
2218 isa<NamespaceDecl>(D))) {
2219 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2220 << Attr.getName() << ExpectedTypeOrNamespace;
2224 // Check that the argument is a string literal.
2226 SourceLocation LiteralLoc;
2227 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2230 VisibilityAttr::VisibilityType type;
2231 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2232 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2233 << Attr.getName() << TypeStr;
2237 // Complain about attempts to use protected visibility on targets
2238 // (like Darwin) that don't support it.
2239 if (type == VisibilityAttr::Protected &&
2240 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2241 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2242 type = VisibilityAttr::Default;
2245 unsigned Index = Attr.getAttributeSpellingListIndex();
2246 clang::Attr *newAttr;
2247 if (isTypeVisibility) {
2248 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2249 (TypeVisibilityAttr::VisibilityType) type,
2252 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2255 D->addAttr(newAttr);
2258 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2259 const AttributeList &Attr) {
2260 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2261 if (!Attr.isArgIdent(0)) {
2262 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2263 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2267 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2268 ObjCMethodFamilyAttr::FamilyKind F;
2269 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2270 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2275 if (F == ObjCMethodFamilyAttr::OMF_init &&
2276 !method->getReturnType()->isObjCObjectPointerType()) {
2277 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2278 << method->getReturnType();
2279 // Ignore the attribute.
2283 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2285 Attr.getAttributeSpellingListIndex()));
2288 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2289 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2290 QualType T = TD->getUnderlyingType();
2291 if (!T->isCARCBridgableType()) {
2292 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2296 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2297 QualType T = PD->getType();
2298 if (!T->isCARCBridgableType()) {
2299 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2304 // It is okay to include this attribute on properties, e.g.:
2306 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2308 // In this case it follows tradition and suppresses an error in the above
2310 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2312 D->addAttr(::new (S.Context)
2313 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2314 Attr.getAttributeSpellingListIndex()));
2317 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2318 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2319 QualType T = TD->getUnderlyingType();
2320 if (!T->isObjCObjectPointerType()) {
2321 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2325 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2328 D->addAttr(::new (S.Context)
2329 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2330 Attr.getAttributeSpellingListIndex()));
2333 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2334 if (!Attr.isArgIdent(0)) {
2335 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2336 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2340 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2341 BlocksAttr::BlockType type;
2342 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2343 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2344 << Attr.getName() << II;
2348 D->addAttr(::new (S.Context)
2349 BlocksAttr(Attr.getRange(), S.Context, type,
2350 Attr.getAttributeSpellingListIndex()));
2353 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2354 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2355 if (Attr.getNumArgs() > 0) {
2356 Expr *E = Attr.getArgAsExpr(0);
2357 llvm::APSInt Idx(32);
2358 if (E->isTypeDependent() || E->isValueDependent() ||
2359 !E->isIntegerConstantExpr(Idx, S.Context)) {
2360 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2361 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2362 << E->getSourceRange();
2366 if (Idx.isSigned() && Idx.isNegative()) {
2367 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2368 << E->getSourceRange();
2372 sentinel = Idx.getZExtValue();
2375 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2376 if (Attr.getNumArgs() > 1) {
2377 Expr *E = Attr.getArgAsExpr(1);
2378 llvm::APSInt Idx(32);
2379 if (E->isTypeDependent() || E->isValueDependent() ||
2380 !E->isIntegerConstantExpr(Idx, S.Context)) {
2381 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2382 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2383 << E->getSourceRange();
2386 nullPos = Idx.getZExtValue();
2388 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2389 // FIXME: This error message could be improved, it would be nice
2390 // to say what the bounds actually are.
2391 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2392 << E->getSourceRange();
2397 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2398 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2399 if (isa<FunctionNoProtoType>(FT)) {
2400 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2404 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2405 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2408 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2409 if (!MD->isVariadic()) {
2410 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2413 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2414 if (!BD->isVariadic()) {
2415 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2418 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2419 QualType Ty = V->getType();
2420 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2421 const FunctionType *FT = Ty->isFunctionPointerType()
2422 ? D->getFunctionType()
2423 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2424 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2425 int m = Ty->isFunctionPointerType() ? 0 : 1;
2426 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2430 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2431 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2435 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2436 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2439 D->addAttr(::new (S.Context)
2440 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2441 Attr.getAttributeSpellingListIndex()));
2444 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2445 if (D->getFunctionType() &&
2446 D->getFunctionType()->getReturnType()->isVoidType()) {
2447 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2448 << Attr.getName() << 0;
2451 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2452 if (MD->getReturnType()->isVoidType()) {
2453 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2454 << Attr.getName() << 1;
2458 D->addAttr(::new (S.Context)
2459 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2460 Attr.getAttributeSpellingListIndex()));
2463 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2464 // weak_import only applies to variable & function declarations.
2466 if (!D->canBeWeakImported(isDef)) {
2468 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2470 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2471 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2472 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2473 // Nothing to warn about here.
2475 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2476 << Attr.getName() << ExpectedVariableOrFunction;
2481 D->addAttr(::new (S.Context)
2482 WeakImportAttr(Attr.getRange(), S.Context,
2483 Attr.getAttributeSpellingListIndex()));
2486 // Handles reqd_work_group_size and work_group_size_hint.
2487 template <typename WorkGroupAttr>
2488 static void handleWorkGroupSize(Sema &S, Decl *D,
2489 const AttributeList &Attr) {
2491 for (unsigned i = 0; i < 3; ++i) {
2492 const Expr *E = Attr.getArgAsExpr(i);
2493 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2495 if (WGSize[i] == 0) {
2496 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2497 << Attr.getName() << E->getSourceRange();
2502 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2503 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2504 Existing->getYDim() == WGSize[1] &&
2505 Existing->getZDim() == WGSize[2]))
2506 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2508 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2509 WGSize[0], WGSize[1], WGSize[2],
2510 Attr.getAttributeSpellingListIndex()));
2513 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2514 if (!Attr.hasParsedType()) {
2515 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2516 << Attr.getName() << 1;
2520 TypeSourceInfo *ParmTSI = nullptr;
2521 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2522 assert(ParmTSI && "no type source info for attribute argument");
2524 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2525 (ParmType->isBooleanType() ||
2526 !ParmType->isIntegralType(S.getASTContext()))) {
2527 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2532 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2533 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2534 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2539 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2541 Attr.getAttributeSpellingListIndex()));
2544 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2546 unsigned AttrSpellingListIndex) {
2547 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2548 if (ExistingAttr->getName() == Name)
2550 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2551 Diag(Range.getBegin(), diag::note_previous_attribute);
2554 return ::new (Context) SectionAttr(Range, Context, Name,
2555 AttrSpellingListIndex);
2558 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2559 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2560 if (!Error.empty()) {
2561 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2567 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2568 // Make sure that there is a string literal as the sections's single
2571 SourceLocation LiteralLoc;
2572 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2575 if (!S.checkSectionName(LiteralLoc, Str))
2578 // If the target wants to validate the section specifier, make it happen.
2579 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2580 if (!Error.empty()) {
2581 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2586 unsigned Index = Attr.getAttributeSpellingListIndex();
2587 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2589 D->addAttr(NewAttr);
2592 // Check for things we'd like to warn about, no errors or validation for now.
2593 // TODO: Validation should use a backend target library that specifies
2594 // the allowable subtarget features and cpus. We could use something like a
2595 // TargetCodeGenInfo hook here to do validation.
2596 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2597 for (auto Str : {"tune=", "fpmath="})
2598 if (AttrStr.find(Str) != StringRef::npos)
2599 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2602 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2604 SourceLocation LiteralLoc;
2605 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2607 S.checkTargetAttr(LiteralLoc, Str);
2608 unsigned Index = Attr.getAttributeSpellingListIndex();
2609 TargetAttr *NewAttr =
2610 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2611 D->addAttr(NewAttr);
2615 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2616 VarDecl *VD = cast<VarDecl>(D);
2617 if (!VD->hasLocalStorage()) {
2618 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2622 Expr *E = Attr.getArgAsExpr(0);
2623 SourceLocation Loc = E->getExprLoc();
2624 FunctionDecl *FD = nullptr;
2625 DeclarationNameInfo NI;
2627 // gcc only allows for simple identifiers. Since we support more than gcc, we
2628 // will warn the user.
2629 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2630 if (DRE->hasQualifier())
2631 S.Diag(Loc, diag::warn_cleanup_ext);
2632 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2633 NI = DRE->getNameInfo();
2635 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2639 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2640 if (ULE->hasExplicitTemplateArgs())
2641 S.Diag(Loc, diag::warn_cleanup_ext);
2642 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2643 NI = ULE->getNameInfo();
2645 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2647 if (ULE->getType() == S.Context.OverloadTy)
2648 S.NoteAllOverloadCandidates(ULE);
2652 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2656 if (FD->getNumParams() != 1) {
2657 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2662 // We're currently more strict than GCC about what function types we accept.
2663 // If this ever proves to be a problem it should be easy to fix.
2664 QualType Ty = S.Context.getPointerType(VD->getType());
2665 QualType ParamTy = FD->getParamDecl(0)->getType();
2666 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2667 ParamTy, Ty) != Sema::Compatible) {
2668 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2669 << NI.getName() << ParamTy << Ty;
2673 D->addAttr(::new (S.Context)
2674 CleanupAttr(Attr.getRange(), S.Context, FD,
2675 Attr.getAttributeSpellingListIndex()));
2678 /// Handle __attribute__((format_arg((idx)))) attribute based on
2679 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2680 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2681 Expr *IdxExpr = Attr.getArgAsExpr(0);
2683 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2686 // Make sure the format string is really a string.
2687 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2689 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2690 if (NotNSStringTy &&
2691 !isCFStringType(Ty, S.Context) &&
2692 (!Ty->isPointerType() ||
2693 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2694 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2695 << "a string type" << IdxExpr->getSourceRange()
2696 << getFunctionOrMethodParamRange(D, 0);
2699 Ty = getFunctionOrMethodResultType(D);
2700 if (!isNSStringType(Ty, S.Context) &&
2701 !isCFStringType(Ty, S.Context) &&
2702 (!Ty->isPointerType() ||
2703 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2704 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2705 << (NotNSStringTy ? "string type" : "NSString")
2706 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2710 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2711 // because that has corrected for the implicit this parameter, and is zero-
2712 // based. The attribute expects what the user wrote explicitly.
2714 IdxExpr->EvaluateAsInt(Val, S.Context);
2716 D->addAttr(::new (S.Context)
2717 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2718 Attr.getAttributeSpellingListIndex()));
2721 enum FormatAttrKind {
2730 /// getFormatAttrKind - Map from format attribute names to supported format
2732 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2733 return llvm::StringSwitch<FormatAttrKind>(Format)
2734 // Check for formats that get handled specially.
2735 .Case("NSString", NSStringFormat)
2736 .Case("CFString", CFStringFormat)
2737 .Case("strftime", StrftimeFormat)
2739 // Otherwise, check for supported formats.
2740 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2741 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2742 .Case("kprintf", SupportedFormat) // OpenBSD.
2743 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2744 .Case("os_trace", SupportedFormat)
2746 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2747 .Default(InvalidFormat);
2750 /// Handle __attribute__((init_priority(priority))) attributes based on
2751 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2752 static void handleInitPriorityAttr(Sema &S, Decl *D,
2753 const AttributeList &Attr) {
2754 if (!S.getLangOpts().CPlusPlus) {
2755 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2759 if (S.getCurFunctionOrMethodDecl()) {
2760 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2764 QualType T = cast<VarDecl>(D)->getType();
2765 if (S.Context.getAsArrayType(T))
2766 T = S.Context.getBaseElementType(T);
2767 if (!T->getAs<RecordType>()) {
2768 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2773 Expr *E = Attr.getArgAsExpr(0);
2774 uint32_t prioritynum;
2775 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2780 if (prioritynum < 101 || prioritynum > 65535) {
2781 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2782 << E->getSourceRange() << Attr.getName() << 101 << 65535;
2786 D->addAttr(::new (S.Context)
2787 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2788 Attr.getAttributeSpellingListIndex()));
2791 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2792 IdentifierInfo *Format, int FormatIdx,
2794 unsigned AttrSpellingListIndex) {
2795 // Check whether we already have an equivalent format attribute.
2796 for (auto *F : D->specific_attrs<FormatAttr>()) {
2797 if (F->getType() == Format &&
2798 F->getFormatIdx() == FormatIdx &&
2799 F->getFirstArg() == FirstArg) {
2800 // If we don't have a valid location for this attribute, adopt the
2802 if (F->getLocation().isInvalid())
2808 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2809 FirstArg, AttrSpellingListIndex);
2812 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2813 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2814 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2815 if (!Attr.isArgIdent(0)) {
2816 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2817 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2821 // In C++ the implicit 'this' function parameter also counts, and they are
2822 // counted from one.
2823 bool HasImplicitThisParam = isInstanceMethod(D);
2824 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2826 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2827 StringRef Format = II->getName();
2829 if (normalizeName(Format)) {
2830 // If we've modified the string name, we need a new identifier for it.
2831 II = &S.Context.Idents.get(Format);
2834 // Check for supported formats.
2835 FormatAttrKind Kind = getFormatAttrKind(Format);
2837 if (Kind == IgnoredFormat)
2840 if (Kind == InvalidFormat) {
2841 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2842 << Attr.getName() << II->getName();
2846 // checks for the 2nd argument
2847 Expr *IdxExpr = Attr.getArgAsExpr(1);
2849 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2852 if (Idx < 1 || Idx > NumArgs) {
2853 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2854 << Attr.getName() << 2 << IdxExpr->getSourceRange();
2858 // FIXME: Do we need to bounds check?
2859 unsigned ArgIdx = Idx - 1;
2861 if (HasImplicitThisParam) {
2863 S.Diag(Attr.getLoc(),
2864 diag::err_format_attribute_implicit_this_format_string)
2865 << IdxExpr->getSourceRange();
2871 // make sure the format string is really a string
2872 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2874 if (Kind == CFStringFormat) {
2875 if (!isCFStringType(Ty, S.Context)) {
2876 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2877 << "a CFString" << IdxExpr->getSourceRange()
2878 << getFunctionOrMethodParamRange(D, ArgIdx);
2881 } else if (Kind == NSStringFormat) {
2882 // FIXME: do we need to check if the type is NSString*? What are the
2884 if (!isNSStringType(Ty, S.Context)) {
2885 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2886 << "an NSString" << IdxExpr->getSourceRange()
2887 << getFunctionOrMethodParamRange(D, ArgIdx);
2890 } else if (!Ty->isPointerType() ||
2891 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2892 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2893 << "a string type" << IdxExpr->getSourceRange()
2894 << getFunctionOrMethodParamRange(D, ArgIdx);
2898 // check the 3rd argument
2899 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2901 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2904 // check if the function is variadic if the 3rd argument non-zero
2905 if (FirstArg != 0) {
2906 if (isFunctionOrMethodVariadic(D)) {
2907 ++NumArgs; // +1 for ...
2909 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2914 // strftime requires FirstArg to be 0 because it doesn't read from any
2915 // variable the input is just the current time + the format string.
2916 if (Kind == StrftimeFormat) {
2917 if (FirstArg != 0) {
2918 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2919 << FirstArgExpr->getSourceRange();
2922 // if 0 it disables parameter checking (to use with e.g. va_list)
2923 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2924 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2925 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
2929 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
2931 Attr.getAttributeSpellingListIndex());
2933 D->addAttr(NewAttr);
2936 static void handleTransparentUnionAttr(Sema &S, Decl *D,
2937 const AttributeList &Attr) {
2938 // Try to find the underlying union declaration.
2939 RecordDecl *RD = nullptr;
2940 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
2941 if (TD && TD->getUnderlyingType()->isUnionType())
2942 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
2944 RD = dyn_cast<RecordDecl>(D);
2946 if (!RD || !RD->isUnion()) {
2947 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2948 << Attr.getName() << ExpectedUnion;
2952 if (!RD->isCompleteDefinition()) {
2953 S.Diag(Attr.getLoc(),
2954 diag::warn_transparent_union_attribute_not_definition);
2958 RecordDecl::field_iterator Field = RD->field_begin(),
2959 FieldEnd = RD->field_end();
2960 if (Field == FieldEnd) {
2961 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
2965 FieldDecl *FirstField = *Field;
2966 QualType FirstType = FirstField->getType();
2967 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
2968 S.Diag(FirstField->getLocation(),
2969 diag::warn_transparent_union_attribute_floating)
2970 << FirstType->isVectorType() << FirstType;
2974 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
2975 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
2976 for (; Field != FieldEnd; ++Field) {
2977 QualType FieldType = Field->getType();
2978 // FIXME: this isn't fully correct; we also need to test whether the
2979 // members of the union would all have the same calling convention as the
2980 // first member of the union. Checking just the size and alignment isn't
2981 // sufficient (consider structs passed on the stack instead of in registers
2983 if (S.Context.getTypeSize(FieldType) != FirstSize ||
2984 S.Context.getTypeAlign(FieldType) > FirstAlign) {
2985 // Warn if we drop the attribute.
2986 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
2987 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
2988 : S.Context.getTypeAlign(FieldType);
2989 S.Diag(Field->getLocation(),
2990 diag::warn_transparent_union_attribute_field_size_align)
2991 << isSize << Field->getDeclName() << FieldBits;
2992 unsigned FirstBits = isSize? FirstSize : FirstAlign;
2993 S.Diag(FirstField->getLocation(),
2994 diag::note_transparent_union_first_field_size_align)
2995 << isSize << FirstBits;
3000 RD->addAttr(::new (S.Context)
3001 TransparentUnionAttr(Attr.getRange(), S.Context,
3002 Attr.getAttributeSpellingListIndex()));
3005 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3006 // Make sure that there is a string literal as the annotation's single
3009 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3012 // Don't duplicate annotations that are already set.
3013 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3014 if (I->getAnnotation() == Str)
3018 D->addAttr(::new (S.Context)
3019 AnnotateAttr(Attr.getRange(), S.Context, Str,
3020 Attr.getAttributeSpellingListIndex()));
3023 static void handleAlignValueAttr(Sema &S, Decl *D,
3024 const AttributeList &Attr) {
3025 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3026 Attr.getAttributeSpellingListIndex());
3029 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3030 unsigned SpellingListIndex) {
3031 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3032 SourceLocation AttrLoc = AttrRange.getBegin();
3035 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3036 T = TD->getUnderlyingType();
3037 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3040 llvm_unreachable("Unknown decl type for align_value");
3042 if (!T->isDependentType() && !T->isAnyPointerType() &&
3043 !T->isReferenceType() && !T->isMemberPointerType()) {
3044 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3045 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3049 if (!E->isValueDependent()) {
3050 llvm::APSInt Alignment;
3052 = VerifyIntegerConstantExpression(E, &Alignment,
3053 diag::err_align_value_attribute_argument_not_int,
3054 /*AllowFold*/ false);
3055 if (ICE.isInvalid())
3058 if (!Alignment.isPowerOf2()) {
3059 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3060 << E->getSourceRange();
3064 D->addAttr(::new (Context)
3065 AlignValueAttr(AttrRange, Context, ICE.get(),
3066 SpellingListIndex));
3070 // Save dependent expressions in the AST to be instantiated.
3071 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3075 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3076 // check the attribute arguments.
3077 if (Attr.getNumArgs() > 1) {
3078 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3079 << Attr.getName() << 1;
3083 if (Attr.getNumArgs() == 0) {
3084 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3085 true, nullptr, Attr.getAttributeSpellingListIndex()));
3089 Expr *E = Attr.getArgAsExpr(0);
3090 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3091 S.Diag(Attr.getEllipsisLoc(),
3092 diag::err_pack_expansion_without_parameter_packs);
3096 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3099 if (E->isValueDependent()) {
3100 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3101 if (!TND->getUnderlyingType()->isDependentType()) {
3102 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3103 << E->getSourceRange();
3109 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3110 Attr.isPackExpansion());
3113 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3114 unsigned SpellingListIndex, bool IsPackExpansion) {
3115 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3116 SourceLocation AttrLoc = AttrRange.getBegin();
3118 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3119 if (TmpAttr.isAlignas()) {
3120 // C++11 [dcl.align]p1:
3121 // An alignment-specifier may be applied to a variable or to a class
3122 // data member, but it shall not be applied to a bit-field, a function
3123 // parameter, the formal parameter of a catch clause, or a variable
3124 // declared with the register storage class specifier. An
3125 // alignment-specifier may also be applied to the declaration of a class
3126 // or enumeration type.
3128 // An alignment attribute shall not be specified in a declaration of
3129 // a typedef, or a bit-field, or a function, or a parameter, or an
3130 // object declared with the register storage-class specifier.
3132 if (isa<ParmVarDecl>(D)) {
3134 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3135 if (VD->getStorageClass() == SC_Register)
3137 if (VD->isExceptionVariable())
3139 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3140 if (FD->isBitField())
3142 } else if (!isa<TagDecl>(D)) {
3143 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3144 << (TmpAttr.isC11() ? ExpectedVariableOrField
3145 : ExpectedVariableFieldOrTag);
3148 if (DiagKind != -1) {
3149 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3150 << &TmpAttr << DiagKind;
3155 if (E->isTypeDependent() || E->isValueDependent()) {
3156 // Save dependent expressions in the AST to be instantiated.
3157 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3158 AA->setPackExpansion(IsPackExpansion);
3163 // FIXME: Cache the number on the Attr object?
3164 llvm::APSInt Alignment;
3166 = VerifyIntegerConstantExpression(E, &Alignment,
3167 diag::err_aligned_attribute_argument_not_int,
3168 /*AllowFold*/ false);
3169 if (ICE.isInvalid())
3172 uint64_t AlignVal = Alignment.getZExtValue();
3174 // C++11 [dcl.align]p2:
3175 // -- if the constant expression evaluates to zero, the alignment
3176 // specifier shall have no effect
3178 // An alignment specification of zero has no effect.
3179 if (!(TmpAttr.isAlignas() && !Alignment)) {
3180 if (!llvm::isPowerOf2_64(AlignVal)) {
3181 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3182 << E->getSourceRange();
3187 // Alignment calculations can wrap around if it's greater than 2**28.
3188 unsigned MaxValidAlignment =
3189 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3191 if (AlignVal > MaxValidAlignment) {
3192 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3193 << E->getSourceRange();
3197 if (Context.getTargetInfo().isTLSSupported()) {
3198 unsigned MaxTLSAlign =
3199 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3201 auto *VD = dyn_cast<VarDecl>(D);
3202 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3203 VD->getTLSKind() != VarDecl::TLS_None) {
3204 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3205 << (unsigned)AlignVal << VD << MaxTLSAlign;
3210 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3211 ICE.get(), SpellingListIndex);
3212 AA->setPackExpansion(IsPackExpansion);
3216 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3217 unsigned SpellingListIndex, bool IsPackExpansion) {
3218 // FIXME: Cache the number on the Attr object if non-dependent?
3219 // FIXME: Perform checking of type validity
3220 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3222 AA->setPackExpansion(IsPackExpansion);
3226 void Sema::CheckAlignasUnderalignment(Decl *D) {
3227 assert(D->hasAttrs() && "no attributes on decl");
3229 QualType UnderlyingTy, DiagTy;
3230 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3231 UnderlyingTy = DiagTy = VD->getType();
3233 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3234 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3235 UnderlyingTy = ED->getIntegerType();
3237 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3240 // C++11 [dcl.align]p5, C11 6.7.5/4:
3241 // The combined effect of all alignment attributes in a declaration shall
3242 // not specify an alignment that is less strict than the alignment that
3243 // would otherwise be required for the entity being declared.
3244 AlignedAttr *AlignasAttr = nullptr;
3246 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3247 if (I->isAlignmentDependent())
3251 Align = std::max(Align, I->getAlignment(Context));
3254 if (AlignasAttr && Align) {
3255 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3256 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3257 if (NaturalAlign > RequestedAlign)
3258 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3259 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3263 bool Sema::checkMSInheritanceAttrOnDefinition(
3264 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3265 MSInheritanceAttr::Spelling SemanticSpelling) {
3266 assert(RD->hasDefinition() && "RD has no definition!");
3268 // We may not have seen base specifiers or any virtual methods yet. We will
3269 // have to wait until the record is defined to catch any mismatches.
3270 if (!RD->getDefinition()->isCompleteDefinition())
3273 // The unspecified model never matches what a definition could need.
3274 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3278 if (RD->calculateInheritanceModel() == SemanticSpelling)
3281 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3285 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3286 << 0 /*definition*/;
3287 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3288 << RD->getNameAsString();
3292 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3294 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3295 bool &IntegerMode, bool &ComplexMode) {
3296 switch (Str.size()) {
3318 if (Str[1] == 'F') {
3319 IntegerMode = false;
3320 } else if (Str[1] == 'C') {
3321 IntegerMode = false;
3323 } else if (Str[1] != 'I') {
3328 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3329 // pointer on PIC16 and other embedded platforms.
3331 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3332 else if (Str == "byte")
3333 DestWidth = S.Context.getTargetInfo().getCharWidth();
3336 if (Str == "pointer")
3337 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3340 if (Str == "unwind_word")
3341 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3346 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3349 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3350 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3351 /// HImode, not an intermediate pointer.
3352 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3353 // This attribute isn't documented, but glibc uses it. It changes
3354 // the width of an int or unsigned int to the specified size.
3355 if (!Attr.isArgIdent(0)) {
3356 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3357 << AANT_ArgumentIdentifier;
3361 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3362 StringRef Str = Name->getName();
3366 unsigned DestWidth = 0;
3367 bool IntegerMode = true;
3368 bool ComplexMode = false;
3369 llvm::APInt VectorSize(64, 0);
3370 if (Str.size() >= 4 && Str[0] == 'V') {
3371 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3372 size_t StrSize = Str.size();
3373 size_t VectorStringLength = 0;
3374 while ((VectorStringLength + 1) < StrSize &&
3375 isdigit(Str[VectorStringLength + 1]))
3376 ++VectorStringLength;
3377 if (VectorStringLength &&
3378 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3379 VectorSize.isPowerOf2()) {
3380 parseModeAttrArg(S, Str.substr(VectorStringLength + 1), DestWidth,
3381 IntegerMode, ComplexMode);
3382 S.Diag(Attr.getLoc(), diag::warn_vector_mode_deprecated);
3389 parseModeAttrArg(S, Str, DestWidth, IntegerMode, ComplexMode);
3392 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3393 OldTy = TD->getUnderlyingType();
3394 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3395 OldTy = VD->getType();
3397 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3398 << Attr.getName() << Attr.getRange();
3402 // Base type can also be a vector type (see PR17453).
3403 // Distinguish between base type and base element type.
3404 QualType OldElemTy = OldTy;
3405 if (const VectorType *VT = OldTy->getAs<VectorType>())
3406 OldElemTy = VT->getElementType();
3408 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType())
3409 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3410 else if (IntegerMode) {
3411 if (!OldElemTy->isIntegralOrEnumerationType())
3412 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3413 } else if (ComplexMode) {
3414 if (!OldElemTy->isComplexType())
3415 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3417 if (!OldElemTy->isFloatingType())
3418 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3421 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3422 // and friends, at least with glibc.
3423 // FIXME: Make sure floating-point mappings are accurate
3424 // FIXME: Support XF and TF types
3426 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3433 NewElemTy = S.Context.getIntTypeForBitwidth(
3434 DestWidth, OldElemTy->isSignedIntegerType());
3436 NewElemTy = S.Context.getRealTypeForBitwidth(DestWidth);
3438 if (NewElemTy.isNull()) {
3439 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3444 NewElemTy = S.Context.getComplexType(NewElemTy);
3447 QualType NewTy = NewElemTy;
3448 if (VectorSize.getBoolValue()) {
3449 NewTy = S.Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3450 VectorType::GenericVector);
3451 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3452 // Complex machine mode does not support base vector types.
3454 S.Diag(Attr.getLoc(), diag::err_complex_mode_vector_type);
3457 unsigned NumElements = S.Context.getTypeSize(OldElemTy) *
3458 OldVT->getNumElements() /
3459 S.Context.getTypeSize(NewElemTy);
3461 S.Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3464 if (NewTy.isNull()) {
3465 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3469 // Install the new type.
3470 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3471 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3473 cast<ValueDecl>(D)->setType(NewTy);
3475 D->addAttr(::new (S.Context)
3476 ModeAttr(Attr.getRange(), S.Context, Name,
3477 Attr.getAttributeSpellingListIndex()));
3480 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3481 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3482 if (!VD->hasGlobalStorage())
3483 S.Diag(Attr.getLoc(),
3484 diag::warn_attribute_requires_functions_or_static_globals)
3486 } else if (!isFunctionOrMethod(D)) {
3487 S.Diag(Attr.getLoc(),
3488 diag::warn_attribute_requires_functions_or_static_globals)
3493 D->addAttr(::new (S.Context)
3494 NoDebugAttr(Attr.getRange(), S.Context,
3495 Attr.getAttributeSpellingListIndex()));
3498 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3499 IdentifierInfo *Ident,
3500 unsigned AttrSpellingListIndex) {
3501 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3502 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3503 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3507 if (D->hasAttr<AlwaysInlineAttr>())
3510 return ::new (Context) AlwaysInlineAttr(Range, Context,
3511 AttrSpellingListIndex);
3514 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3515 IdentifierInfo *Ident,
3516 unsigned AttrSpellingListIndex) {
3517 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3520 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3523 InternalLinkageAttr *
3524 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3525 IdentifierInfo *Ident,
3526 unsigned AttrSpellingListIndex) {
3527 if (auto VD = dyn_cast<VarDecl>(D)) {
3528 // Attribute applies to Var but not any subclass of it (like ParmVar,
3529 // ImplicitParm or VarTemplateSpecialization).
3530 if (VD->getKind() != Decl::Var) {
3531 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3532 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3533 : ExpectedVariableOrFunction);
3536 // Attribute does not apply to non-static local variables.
3537 if (VD->hasLocalStorage()) {
3538 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3543 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3546 return ::new (Context)
3547 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3550 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3551 unsigned AttrSpellingListIndex) {
3552 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3553 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3554 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3558 if (D->hasAttr<MinSizeAttr>())
3561 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3564 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3565 unsigned AttrSpellingListIndex) {
3566 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3567 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3568 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3569 D->dropAttr<AlwaysInlineAttr>();
3571 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3572 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3573 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3574 D->dropAttr<MinSizeAttr>();
3577 if (D->hasAttr<OptimizeNoneAttr>())
3580 return ::new (Context) OptimizeNoneAttr(Range, Context,
3581 AttrSpellingListIndex);
3584 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3585 const AttributeList &Attr) {
3586 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3590 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3591 D, Attr.getRange(), Attr.getName(),
3592 Attr.getAttributeSpellingListIndex()))
3596 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3597 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3598 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3599 D->addAttr(MinSize);
3602 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3603 const AttributeList &Attr) {
3604 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3605 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3606 D->addAttr(Optnone);
3609 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3610 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
3612 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
3616 FunctionDecl *FD = cast<FunctionDecl>(D);
3617 if (!FD->getReturnType()->isVoidType()) {
3618 SourceRange RTRange = FD->getReturnTypeSourceRange();
3619 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3621 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3626 D->addAttr(::new (S.Context)
3627 CUDAGlobalAttr(Attr.getRange(), S.Context,
3628 Attr.getAttributeSpellingListIndex()));
3632 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3633 FunctionDecl *Fn = cast<FunctionDecl>(D);
3634 if (!Fn->isInlineSpecified()) {
3635 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3639 D->addAttr(::new (S.Context)
3640 GNUInlineAttr(Attr.getRange(), S.Context,
3641 Attr.getAttributeSpellingListIndex()));
3644 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3645 if (hasDeclarator(D)) return;
3647 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3648 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3650 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
3653 if (!isa<ObjCMethodDecl>(D)) {
3654 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3655 << Attr.getName() << ExpectedFunctionOrMethod;
3659 switch (Attr.getKind()) {
3660 case AttributeList::AT_FastCall:
3661 D->addAttr(::new (S.Context)
3662 FastCallAttr(Attr.getRange(), S.Context,
3663 Attr.getAttributeSpellingListIndex()));
3665 case AttributeList::AT_StdCall:
3666 D->addAttr(::new (S.Context)
3667 StdCallAttr(Attr.getRange(), S.Context,
3668 Attr.getAttributeSpellingListIndex()));
3670 case AttributeList::AT_ThisCall:
3671 D->addAttr(::new (S.Context)
3672 ThisCallAttr(Attr.getRange(), S.Context,
3673 Attr.getAttributeSpellingListIndex()));
3675 case AttributeList::AT_CDecl:
3676 D->addAttr(::new (S.Context)
3677 CDeclAttr(Attr.getRange(), S.Context,
3678 Attr.getAttributeSpellingListIndex()));
3680 case AttributeList::AT_Pascal:
3681 D->addAttr(::new (S.Context)
3682 PascalAttr(Attr.getRange(), S.Context,
3683 Attr.getAttributeSpellingListIndex()));
3685 case AttributeList::AT_VectorCall:
3686 D->addAttr(::new (S.Context)
3687 VectorCallAttr(Attr.getRange(), S.Context,
3688 Attr.getAttributeSpellingListIndex()));
3690 case AttributeList::AT_MSABI:
3691 D->addAttr(::new (S.Context)
3692 MSABIAttr(Attr.getRange(), S.Context,
3693 Attr.getAttributeSpellingListIndex()));
3695 case AttributeList::AT_SysVABI:
3696 D->addAttr(::new (S.Context)
3697 SysVABIAttr(Attr.getRange(), S.Context,
3698 Attr.getAttributeSpellingListIndex()));
3700 case AttributeList::AT_Pcs: {
3701 PcsAttr::PCSType PCS;
3704 PCS = PcsAttr::AAPCS;
3707 PCS = PcsAttr::AAPCS_VFP;
3710 llvm_unreachable("unexpected calling convention in pcs attribute");
3713 D->addAttr(::new (S.Context)
3714 PcsAttr(Attr.getRange(), S.Context, PCS,
3715 Attr.getAttributeSpellingListIndex()));
3718 case AttributeList::AT_IntelOclBicc:
3719 D->addAttr(::new (S.Context)
3720 IntelOclBiccAttr(Attr.getRange(), S.Context,
3721 Attr.getAttributeSpellingListIndex()));
3725 llvm_unreachable("unexpected attribute kind");
3729 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3730 const FunctionDecl *FD) {
3731 if (attr.isInvalid())
3734 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3735 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3740 // TODO: diagnose uses of these conventions on the wrong target.
3741 switch (attr.getKind()) {
3742 case AttributeList::AT_CDecl: CC = CC_C; break;
3743 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3744 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3745 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3746 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3747 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3748 case AttributeList::AT_MSABI:
3749 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3752 case AttributeList::AT_SysVABI:
3753 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3756 case AttributeList::AT_Pcs: {
3758 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3762 if (StrRef == "aapcs") {
3765 } else if (StrRef == "aapcs-vfp") {
3771 Diag(attr.getLoc(), diag::err_invalid_pcs);
3774 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3775 default: llvm_unreachable("unexpected attribute kind");
3778 const TargetInfo &TI = Context.getTargetInfo();
3779 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3780 if (A != TargetInfo::CCCR_OK) {
3781 if (A == TargetInfo::CCCR_Warning)
3782 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3784 // This convention is not valid for the target. Use the default function or
3785 // method calling convention.
3786 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3788 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3789 TargetInfo::CCMT_NonMember;
3790 CC = TI.getDefaultCallingConv(MT);
3796 /// Checks a regparm attribute, returning true if it is ill-formed and
3797 /// otherwise setting numParams to the appropriate value.
3798 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3799 if (Attr.isInvalid())
3802 if (!checkAttributeNumArgs(*this, Attr, 1)) {
3808 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3809 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
3814 if (Context.getTargetInfo().getRegParmMax() == 0) {
3815 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3816 << NumParamsExpr->getSourceRange();
3822 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3823 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3824 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3832 // Checks whether an argument of launch_bounds attribute is acceptable
3833 // May output an error.
3834 static bool checkLaunchBoundsArgument(Sema &S, Expr *E,
3835 const CUDALaunchBoundsAttr &Attr,
3836 const unsigned Idx) {
3838 if (S.DiagnoseUnexpandedParameterPack(E))
3841 // Accept template arguments for now as they depend on something else.
3842 // We'll get to check them when they eventually get instantiated.
3843 if (E->isValueDependent())
3847 if (!E->isIntegerConstantExpr(I, S.Context)) {
3848 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
3849 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
3852 // Make sure we can fit it in 32 bits.
3853 if (!I.isIntN(32)) {
3854 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
3855 << 32 << /* Unsigned */ 1;
3859 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
3860 << &Attr << Idx << E->getSourceRange();
3865 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
3866 Expr *MinBlocks, unsigned SpellingListIndex) {
3867 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
3870 if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0))
3873 if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1))
3876 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
3877 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
3880 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
3881 const AttributeList &Attr) {
3882 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
3883 !checkAttributeAtMostNumArgs(S, Attr, 2))
3886 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3887 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
3888 Attr.getAttributeSpellingListIndex());
3891 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3892 const AttributeList &Attr) {
3893 if (!Attr.isArgIdent(0)) {
3894 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3895 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3899 if (!checkAttributeNumArgs(S, Attr, 3))
3902 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3904 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3905 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3906 << Attr.getName() << ExpectedFunctionOrMethod;
3910 uint64_t ArgumentIdx;
3911 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
3915 uint64_t TypeTagIdx;
3916 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
3920 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
3922 // Ensure that buffer has a pointer type.
3923 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
3924 if (!BufferTy->isPointerType()) {
3925 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
3926 << Attr.getName() << 0;
3930 D->addAttr(::new (S.Context)
3931 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
3932 ArgumentIdx, TypeTagIdx, IsPointer,
3933 Attr.getAttributeSpellingListIndex()));
3936 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
3937 const AttributeList &Attr) {
3938 if (!Attr.isArgIdent(0)) {
3939 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3940 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3944 if (!checkAttributeNumArgs(S, Attr, 1))
3947 if (!isa<VarDecl>(D)) {
3948 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3949 << Attr.getName() << ExpectedVariable;
3953 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
3954 TypeSourceInfo *MatchingCTypeLoc = nullptr;
3955 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
3956 assert(MatchingCTypeLoc && "no type source info for attribute argument");
3958 D->addAttr(::new (S.Context)
3959 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
3961 Attr.getLayoutCompatible(),
3962 Attr.getMustBeNull(),
3963 Attr.getAttributeSpellingListIndex()));
3966 //===----------------------------------------------------------------------===//
3967 // Checker-specific attribute handlers.
3968 //===----------------------------------------------------------------------===//
3970 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
3971 return type->isDependentType() ||
3972 type->isObjCRetainableType();
3975 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
3976 return type->isDependentType() ||
3977 type->isObjCObjectPointerType() ||
3978 S.Context.isObjCNSObjectType(type);
3980 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
3981 return type->isDependentType() ||
3982 type->isPointerType() ||
3983 isValidSubjectOfNSAttribute(S, type);
3986 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3987 ParmVarDecl *param = cast<ParmVarDecl>(D);
3990 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
3991 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
3994 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
3999 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4000 << Attr.getRange() << Attr.getName() << cf;
4005 param->addAttr(::new (S.Context)
4006 CFConsumedAttr(Attr.getRange(), S.Context,
4007 Attr.getAttributeSpellingListIndex()));
4009 param->addAttr(::new (S.Context)
4010 NSConsumedAttr(Attr.getRange(), S.Context,
4011 Attr.getAttributeSpellingListIndex()));
4014 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4015 const AttributeList &Attr) {
4017 QualType returnType;
4019 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4020 returnType = MD->getReturnType();
4021 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4022 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4023 return; // ignore: was handled as a type attribute
4024 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4025 returnType = PD->getType();
4026 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4027 returnType = FD->getReturnType();
4028 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4029 returnType = Param->getType()->getPointeeType();
4030 if (returnType.isNull()) {
4031 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4032 << Attr.getName() << /*pointer-to-CF*/2
4037 AttributeDeclKind ExpectedDeclKind;
4038 switch (Attr.getKind()) {
4039 default: llvm_unreachable("invalid ownership attribute");
4040 case AttributeList::AT_NSReturnsRetained:
4041 case AttributeList::AT_NSReturnsAutoreleased:
4042 case AttributeList::AT_NSReturnsNotRetained:
4043 ExpectedDeclKind = ExpectedFunctionOrMethod;
4046 case AttributeList::AT_CFReturnsRetained:
4047 case AttributeList::AT_CFReturnsNotRetained:
4048 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4051 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4052 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4058 switch (Attr.getKind()) {
4059 default: llvm_unreachable("invalid ownership attribute");
4060 case AttributeList::AT_NSReturnsRetained:
4061 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4065 case AttributeList::AT_NSReturnsAutoreleased:
4066 case AttributeList::AT_NSReturnsNotRetained:
4067 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4071 case AttributeList::AT_CFReturnsRetained:
4072 case AttributeList::AT_CFReturnsNotRetained:
4073 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4079 if (isa<ParmVarDecl>(D)) {
4080 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4081 << Attr.getName() << /*pointer-to-CF*/2
4084 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4089 } SubjectKind = Function;
4090 if (isa<ObjCMethodDecl>(D))
4091 SubjectKind = Method;
4092 else if (isa<ObjCPropertyDecl>(D))
4093 SubjectKind = Property;
4094 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4095 << Attr.getName() << SubjectKind << cf
4101 switch (Attr.getKind()) {
4103 llvm_unreachable("invalid ownership attribute");
4104 case AttributeList::AT_NSReturnsAutoreleased:
4105 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4106 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4108 case AttributeList::AT_CFReturnsNotRetained:
4109 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4110 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4112 case AttributeList::AT_NSReturnsNotRetained:
4113 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4114 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4116 case AttributeList::AT_CFReturnsRetained:
4117 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4118 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4120 case AttributeList::AT_NSReturnsRetained:
4121 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4122 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4127 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4128 const AttributeList &attr) {
4129 const int EP_ObjCMethod = 1;
4130 const int EP_ObjCProperty = 2;
4132 SourceLocation loc = attr.getLoc();
4133 QualType resultType;
4134 if (isa<ObjCMethodDecl>(D))
4135 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4137 resultType = cast<ObjCPropertyDecl>(D)->getType();
4139 if (!resultType->isReferenceType() &&
4140 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4141 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4144 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4145 << /*non-retainable pointer*/ 2;
4147 // Drop the attribute.
4151 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4152 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4155 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4156 const AttributeList &attr) {
4157 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4159 DeclContext *DC = method->getDeclContext();
4160 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4161 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4162 << attr.getName() << 0;
4163 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4166 if (method->getMethodFamily() == OMF_dealloc) {
4167 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4168 << attr.getName() << 1;
4172 method->addAttr(::new (S.Context)
4173 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4174 attr.getAttributeSpellingListIndex()));
4177 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4178 const AttributeList &Attr) {
4179 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4183 D->addAttr(::new (S.Context)
4184 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4185 Attr.getAttributeSpellingListIndex()));
4188 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4189 const AttributeList &Attr) {
4190 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4194 D->addAttr(::new (S.Context)
4195 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4196 Attr.getAttributeSpellingListIndex()));
4199 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4200 const AttributeList &Attr) {
4201 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4204 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4208 // Typedefs only allow objc_bridge(id) and have some additional checking.
4209 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4210 if (!Parm->Ident->isStr("id")) {
4211 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4216 // Only allow 'cv void *'.
4217 QualType T = TD->getUnderlyingType();
4218 if (!T->isVoidPointerType()) {
4219 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4224 D->addAttr(::new (S.Context)
4225 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4226 Attr.getAttributeSpellingListIndex()));
4229 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4230 const AttributeList &Attr) {
4231 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4234 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4238 D->addAttr(::new (S.Context)
4239 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4240 Attr.getAttributeSpellingListIndex()));
4243 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4244 const AttributeList &Attr) {
4245 IdentifierInfo *RelatedClass =
4246 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4247 if (!RelatedClass) {
4248 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4251 IdentifierInfo *ClassMethod =
4252 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4253 IdentifierInfo *InstanceMethod =
4254 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4255 D->addAttr(::new (S.Context)
4256 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4257 ClassMethod, InstanceMethod,
4258 Attr.getAttributeSpellingListIndex()));
4261 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4262 const AttributeList &Attr) {
4263 ObjCInterfaceDecl *IFace;
4264 if (ObjCCategoryDecl *CatDecl =
4265 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4266 IFace = CatDecl->getClassInterface();
4268 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4273 IFace->setHasDesignatedInitializers();
4274 D->addAttr(::new (S.Context)
4275 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4276 Attr.getAttributeSpellingListIndex()));
4279 static void handleObjCRuntimeName(Sema &S, Decl *D,
4280 const AttributeList &Attr) {
4281 StringRef MetaDataName;
4282 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4284 D->addAttr(::new (S.Context)
4285 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4287 Attr.getAttributeSpellingListIndex()));
4290 // when a user wants to use objc_boxable with a union or struct
4291 // but she doesn't have access to the declaration (legacy/third-party code)
4292 // then she can 'enable' this feature via trick with a typedef
4294 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4295 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4296 bool notify = false;
4298 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4299 if (RD && RD->getDefinition()) {
4300 RD = RD->getDefinition();
4305 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4306 ObjCBoxableAttr(Attr.getRange(), S.Context,
4307 Attr.getAttributeSpellingListIndex());
4308 RD->addAttr(BoxableAttr);
4310 // we need to notify ASTReader/ASTWriter about
4311 // modification of existing declaration
4312 if (ASTMutationListener *L = S.getASTMutationListener())
4313 L->AddedAttributeToRecord(BoxableAttr, RD);
4318 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4319 const AttributeList &Attr) {
4320 if (hasDeclarator(D)) return;
4322 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4323 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4326 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4327 const AttributeList &Attr) {
4328 ValueDecl *vd = cast<ValueDecl>(D);
4329 QualType type = vd->getType();
4331 if (!type->isDependentType() &&
4332 !type->isObjCLifetimeType()) {
4333 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4338 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4340 // If we have no lifetime yet, check the lifetime we're presumably
4342 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4343 lifetime = type->getObjCARCImplicitLifetime();
4346 case Qualifiers::OCL_None:
4347 assert(type->isDependentType() &&
4348 "didn't infer lifetime for non-dependent type?");
4351 case Qualifiers::OCL_Weak: // meaningful
4352 case Qualifiers::OCL_Strong: // meaningful
4355 case Qualifiers::OCL_ExplicitNone:
4356 case Qualifiers::OCL_Autoreleasing:
4357 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4358 << (lifetime == Qualifiers::OCL_Autoreleasing);
4362 D->addAttr(::new (S.Context)
4363 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4364 Attr.getAttributeSpellingListIndex()));
4367 //===----------------------------------------------------------------------===//
4368 // Microsoft specific attribute handlers.
4369 //===----------------------------------------------------------------------===//
4371 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4372 if (!S.LangOpts.CPlusPlus) {
4373 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4374 << Attr.getName() << AttributeLangSupport::C;
4378 if (!isa<CXXRecordDecl>(D)) {
4379 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4380 << Attr.getName() << ExpectedClass;
4385 SourceLocation LiteralLoc;
4386 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4389 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4390 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4391 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4392 StrRef = StrRef.drop_front().drop_back();
4394 // Validate GUID length.
4395 if (StrRef.size() != 36) {
4396 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4400 for (unsigned i = 0; i < 36; ++i) {
4401 if (i == 8 || i == 13 || i == 18 || i == 23) {
4402 if (StrRef[i] != '-') {
4403 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4406 } else if (!isHexDigit(StrRef[i])) {
4407 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4412 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4413 Attr.getAttributeSpellingListIndex()));
4416 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4417 if (!S.LangOpts.CPlusPlus) {
4418 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4419 << Attr.getName() << AttributeLangSupport::C;
4422 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
4423 D, Attr.getRange(), /*BestCase=*/true,
4424 Attr.getAttributeSpellingListIndex(),
4425 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
4430 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4431 const AttributeList &Attr) {
4432 VarDecl *VD = cast<VarDecl>(D);
4433 if (!S.Context.getTargetInfo().isTLSSupported()) {
4434 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4437 if (VD->getTSCSpec() != TSCS_unspecified) {
4438 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4441 if (VD->hasLocalStorage()) {
4442 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4445 VD->addAttr(::new (S.Context) ThreadAttr(
4446 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4449 static void handleARMInterruptAttr(Sema &S, Decl *D,
4450 const AttributeList &Attr) {
4451 // Check the attribute arguments.
4452 if (Attr.getNumArgs() > 1) {
4453 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4454 << Attr.getName() << 1;
4459 SourceLocation ArgLoc;
4461 if (Attr.getNumArgs() == 0)
4463 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4466 ARMInterruptAttr::InterruptType Kind;
4467 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4468 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4469 << Attr.getName() << Str << ArgLoc;
4473 unsigned Index = Attr.getAttributeSpellingListIndex();
4474 D->addAttr(::new (S.Context)
4475 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4478 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4479 const AttributeList &Attr) {
4480 if (!checkAttributeNumArgs(S, Attr, 1))
4483 if (!Attr.isArgExpr(0)) {
4484 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4485 << AANT_ArgumentIntegerConstant;
4489 // FIXME: Check for decl - it should be void ()(void).
4491 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4492 llvm::APSInt NumParams(32);
4493 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4494 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4495 << Attr.getName() << AANT_ArgumentIntegerConstant
4496 << NumParamsExpr->getSourceRange();
4500 unsigned Num = NumParams.getLimitedValue(255);
4501 if ((Num & 1) || Num > 30) {
4502 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4503 << Attr.getName() << (int)NumParams.getSExtValue()
4504 << NumParamsExpr->getSourceRange();
4508 D->addAttr(::new (S.Context)
4509 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4510 Attr.getAttributeSpellingListIndex()));
4511 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4514 static void handleMipsInterruptAttr(Sema &S, Decl *D,
4515 const AttributeList &Attr) {
4516 // Only one optional argument permitted.
4517 if (Attr.getNumArgs() > 1) {
4518 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4519 << Attr.getName() << 1;
4524 SourceLocation ArgLoc;
4526 if (Attr.getNumArgs() == 0)
4528 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4531 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
4532 // a) Must be a function.
4533 // b) Must have no parameters.
4534 // c) Must have the 'void' return type.
4535 // d) Cannot have the 'mips16' attribute, as that instruction set
4536 // lacks the 'eret' instruction.
4537 // e) The attribute itself must either have no argument or one of the
4538 // valid interrupt types, see [MipsInterruptDocs].
4540 if (!isFunctionOrMethod(D)) {
4541 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
4542 << "'interrupt'" << ExpectedFunctionOrMethod;
4546 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
4547 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4552 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4553 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4558 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
4562 MipsInterruptAttr::InterruptType Kind;
4563 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4564 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4565 << Attr.getName() << "'" + std::string(Str) + "'";
4569 D->addAttr(::new (S.Context) MipsInterruptAttr(
4570 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
4573 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4574 // Dispatch the interrupt attribute based on the current target.
4575 if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430)
4576 handleMSP430InterruptAttr(S, D, Attr);
4577 else if (S.Context.getTargetInfo().getTriple().getArch() ==
4578 llvm::Triple::mipsel ||
4579 S.Context.getTargetInfo().getTriple().getArch() ==
4581 handleMipsInterruptAttr(S, D, Attr);
4583 handleARMInterruptAttr(S, D, Attr);
4586 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
4587 const AttributeList &Attr) {
4589 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4590 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4593 D->addAttr(::new (S.Context)
4594 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4596 Attr.getAttributeSpellingListIndex()));
4599 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4600 const AttributeList &Attr) {
4602 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4603 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4606 D->addAttr(::new (S.Context)
4607 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4609 Attr.getAttributeSpellingListIndex()));
4612 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4613 const AttributeList& Attr) {
4614 // If we try to apply it to a function pointer, don't warn, but don't
4615 // do anything, either. It doesn't matter anyway, because there's nothing
4616 // special about calling a force_align_arg_pointer function.
4617 ValueDecl *VD = dyn_cast<ValueDecl>(D);
4618 if (VD && VD->getType()->isFunctionPointerType())
4620 // Also don't warn on function pointer typedefs.
4621 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4622 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4623 TD->getUnderlyingType()->isFunctionType()))
4625 // Attribute can only be applied to function types.
4626 if (!isa<FunctionDecl>(D)) {
4627 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4628 << Attr.getName() << /* function */0;
4632 D->addAttr(::new (S.Context)
4633 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4634 Attr.getAttributeSpellingListIndex()));
4637 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4638 unsigned AttrSpellingListIndex) {
4639 if (D->hasAttr<DLLExportAttr>()) {
4640 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
4644 if (D->hasAttr<DLLImportAttr>())
4647 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
4650 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
4651 unsigned AttrSpellingListIndex) {
4652 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
4653 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
4654 D->dropAttr<DLLImportAttr>();
4657 if (D->hasAttr<DLLExportAttr>())
4660 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
4663 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
4664 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
4665 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4666 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
4671 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4672 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
4673 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4674 // MinGW doesn't allow dllimport on inline functions.
4675 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
4681 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
4682 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4683 MD->getParent()->isLambda()) {
4684 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
4689 unsigned Index = A.getAttributeSpellingListIndex();
4690 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
4691 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
4692 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
4694 D->addAttr(NewAttr);
4698 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
4699 unsigned AttrSpellingListIndex,
4700 MSInheritanceAttr::Spelling SemanticSpelling) {
4701 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
4702 if (IA->getSemanticSpelling() == SemanticSpelling)
4704 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
4705 << 1 /*previous declaration*/;
4706 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
4707 D->dropAttr<MSInheritanceAttr>();
4710 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
4711 if (RD->hasDefinition()) {
4712 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
4713 SemanticSpelling)) {
4717 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
4718 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4719 << 1 /*partial specialization*/;
4722 if (RD->getDescribedClassTemplate()) {
4723 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
4724 << 0 /*primary template*/;
4729 return ::new (Context)
4730 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
4733 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4734 // The capability attributes take a single string parameter for the name of
4735 // the capability they represent. The lockable attribute does not take any
4736 // parameters. However, semantically, both attributes represent the same
4737 // concept, and so they use the same semantic attribute. Eventually, the
4738 // lockable attribute will be removed.
4740 // For backward compatibility, any capability which has no specified string
4741 // literal will be considered a "mutex."
4742 StringRef N("mutex");
4743 SourceLocation LiteralLoc;
4744 if (Attr.getKind() == AttributeList::AT_Capability &&
4745 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
4748 // Currently, there are only two names allowed for a capability: role and
4749 // mutex (case insensitive). Diagnose other capability names.
4750 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
4751 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
4753 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
4754 Attr.getAttributeSpellingListIndex()));
4757 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
4758 const AttributeList &Attr) {
4759 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
4760 Attr.getArgAsExpr(0),
4761 Attr.getAttributeSpellingListIndex()));
4764 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
4765 const AttributeList &Attr) {
4766 SmallVector<Expr*, 1> Args;
4767 if (!checkLockFunAttrCommon(S, D, Attr, Args))
4770 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
4772 Args.data(), Args.size(),
4773 Attr.getAttributeSpellingListIndex()));
4776 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
4777 const AttributeList &Attr) {
4778 SmallVector<Expr*, 2> Args;
4779 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
4782 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
4784 Attr.getArgAsExpr(0),
4787 Attr.getAttributeSpellingListIndex()));
4790 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
4791 const AttributeList &Attr) {
4792 // Check that all arguments are lockable objects.
4793 SmallVector<Expr *, 1> Args;
4794 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
4796 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
4797 Attr.getRange(), S.Context, Args.data(), Args.size(),
4798 Attr.getAttributeSpellingListIndex()));
4801 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
4802 const AttributeList &Attr) {
4803 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4806 // check that all arguments are lockable objects
4807 SmallVector<Expr*, 1> Args;
4808 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
4812 RequiresCapabilityAttr *RCA = ::new (S.Context)
4813 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
4814 Args.size(), Attr.getAttributeSpellingListIndex());
4819 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4820 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
4821 if (NSD->isAnonymousNamespace()) {
4822 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
4823 // Do not want to attach the attribute to the namespace because that will
4824 // cause confusing diagnostic reports for uses of declarations within the
4830 if (!S.getLangOpts().CPlusPlus14)
4831 if (Attr.isCXX11Attribute() &&
4832 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
4833 S.Diag(Attr.getLoc(), diag::ext_deprecated_attr_is_a_cxx14_extension);
4835 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4838 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4839 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4842 std::vector<std::string> Sanitizers;
4844 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4845 StringRef SanitizerName;
4846 SourceLocation LiteralLoc;
4848 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
4851 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
4852 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
4854 Sanitizers.push_back(SanitizerName);
4857 D->addAttr(::new (S.Context) NoSanitizeAttr(
4858 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
4859 Attr.getAttributeSpellingListIndex()));
4862 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
4863 const AttributeList &Attr) {
4864 StringRef AttrName = Attr.getName()->getName();
4865 normalizeName(AttrName);
4866 std::string SanitizerName =
4867 llvm::StringSwitch<std::string>(AttrName)
4868 .Case("no_address_safety_analysis", "address")
4869 .Case("no_sanitize_address", "address")
4870 .Case("no_sanitize_thread", "thread")
4871 .Case("no_sanitize_memory", "memory");
4872 D->addAttr(::new (S.Context)
4873 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
4874 Attr.getAttributeSpellingListIndex()));
4877 static void handleInternalLinkageAttr(Sema &S, Decl *D,
4878 const AttributeList &Attr) {
4879 if (InternalLinkageAttr *Internal =
4880 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
4881 Attr.getAttributeSpellingListIndex()))
4882 D->addAttr(Internal);
4885 /// Handles semantic checking for features that are common to all attributes,
4886 /// such as checking whether a parameter was properly specified, or the correct
4887 /// number of arguments were passed, etc.
4888 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4889 const AttributeList &Attr) {
4890 // Several attributes carry different semantics than the parsing requires, so
4891 // those are opted out of the common handling.
4893 // We also bail on unknown and ignored attributes because those are handled
4894 // as part of the target-specific handling logic.
4895 if (Attr.hasCustomParsing() ||
4896 Attr.getKind() == AttributeList::UnknownAttribute)
4899 // Check whether the attribute requires specific language extensions to be
4901 if (!Attr.diagnoseLangOpts(S))
4904 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
4905 // If there are no optional arguments, then checking for the argument count
4907 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4910 // There are optional arguments, so checking is slightly more involved.
4911 if (Attr.getMinArgs() &&
4912 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
4914 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
4915 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
4919 // Check whether the attribute appertains to the given subject.
4920 if (!Attr.diagnoseAppertainsTo(S, D))
4926 //===----------------------------------------------------------------------===//
4927 // Top Level Sema Entry Points
4928 //===----------------------------------------------------------------------===//
4930 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4931 /// the attribute applies to decls. If the attribute is a type attribute, just
4932 /// silently ignore it if a GNU attribute.
4933 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4934 const AttributeList &Attr,
4935 bool IncludeCXX11Attributes) {
4936 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
4939 // Ignore C++11 attributes on declarator chunks: they appertain to the type
4941 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4944 // Unknown attributes are automatically warned on. Target-specific attributes
4945 // which do not apply to the current target architecture are treated as
4946 // though they were unknown attributes.
4947 if (Attr.getKind() == AttributeList::UnknownAttribute ||
4948 !Attr.existsInTarget(S.Context.getTargetInfo())) {
4949 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
4950 ? diag::warn_unhandled_ms_attribute_ignored
4951 : diag::warn_unknown_attribute_ignored)
4956 if (handleCommonAttributeFeatures(S, scope, D, Attr))
4959 switch (Attr.getKind()) {
4961 // Type attributes are handled elsewhere; silently move on.
4962 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
4964 case AttributeList::AT_Interrupt:
4965 handleInterruptAttr(S, D, Attr);
4967 case AttributeList::AT_X86ForceAlignArgPointer:
4968 handleX86ForceAlignArgPointerAttr(S, D, Attr);
4970 case AttributeList::AT_DLLExport:
4971 case AttributeList::AT_DLLImport:
4972 handleDLLAttr(S, D, Attr);
4974 case AttributeList::AT_Mips16:
4975 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
4978 case AttributeList::AT_NoMips16:
4979 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
4981 case AttributeList::AT_AMDGPUNumVGPR:
4982 handleAMDGPUNumVGPRAttr(S, D, Attr);
4984 case AttributeList::AT_AMDGPUNumSGPR:
4985 handleAMDGPUNumSGPRAttr(S, D, Attr);
4987 case AttributeList::AT_IBAction:
4988 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
4990 case AttributeList::AT_IBOutlet:
4991 handleIBOutlet(S, D, Attr);
4993 case AttributeList::AT_IBOutletCollection:
4994 handleIBOutletCollection(S, D, Attr);
4996 case AttributeList::AT_Alias:
4997 handleAliasAttr(S, D, Attr);
4999 case AttributeList::AT_Aligned:
5000 handleAlignedAttr(S, D, Attr);
5002 case AttributeList::AT_AlignValue:
5003 handleAlignValueAttr(S, D, Attr);
5005 case AttributeList::AT_AlwaysInline:
5006 handleAlwaysInlineAttr(S, D, Attr);
5008 case AttributeList::AT_AnalyzerNoReturn:
5009 handleAnalyzerNoReturnAttr(S, D, Attr);
5011 case AttributeList::AT_TLSModel:
5012 handleTLSModelAttr(S, D, Attr);
5014 case AttributeList::AT_Annotate:
5015 handleAnnotateAttr(S, D, Attr);
5017 case AttributeList::AT_Availability:
5018 handleAvailabilityAttr(S, D, Attr);
5020 case AttributeList::AT_CarriesDependency:
5021 handleDependencyAttr(S, scope, D, Attr);
5023 case AttributeList::AT_Common:
5024 handleCommonAttr(S, D, Attr);
5026 case AttributeList::AT_CUDAConstant:
5027 handleSimpleAttributeWithExclusions<CUDAConstantAttr, CUDASharedAttr>(S, D,
5030 case AttributeList::AT_PassObjectSize:
5031 handlePassObjectSizeAttr(S, D, Attr);
5033 case AttributeList::AT_Constructor:
5034 handleConstructorAttr(S, D, Attr);
5036 case AttributeList::AT_CXX11NoReturn:
5037 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5039 case AttributeList::AT_Deprecated:
5040 handleDeprecatedAttr(S, D, Attr);
5042 case AttributeList::AT_Destructor:
5043 handleDestructorAttr(S, D, Attr);
5045 case AttributeList::AT_EnableIf:
5046 handleEnableIfAttr(S, D, Attr);
5048 case AttributeList::AT_ExtVectorType:
5049 handleExtVectorTypeAttr(S, scope, D, Attr);
5051 case AttributeList::AT_MinSize:
5052 handleMinSizeAttr(S, D, Attr);
5054 case AttributeList::AT_OptimizeNone:
5055 handleOptimizeNoneAttr(S, D, Attr);
5057 case AttributeList::AT_FlagEnum:
5058 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5060 case AttributeList::AT_Flatten:
5061 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5063 case AttributeList::AT_Format:
5064 handleFormatAttr(S, D, Attr);
5066 case AttributeList::AT_FormatArg:
5067 handleFormatArgAttr(S, D, Attr);
5069 case AttributeList::AT_CUDAGlobal:
5070 handleGlobalAttr(S, D, Attr);
5072 case AttributeList::AT_CUDADevice:
5073 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
5076 case AttributeList::AT_CUDAHost:
5077 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
5080 case AttributeList::AT_GNUInline:
5081 handleGNUInlineAttr(S, D, Attr);
5083 case AttributeList::AT_CUDALaunchBounds:
5084 handleLaunchBoundsAttr(S, D, Attr);
5086 case AttributeList::AT_Restrict:
5087 handleRestrictAttr(S, D, Attr);
5089 case AttributeList::AT_MayAlias:
5090 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5092 case AttributeList::AT_Mode:
5093 handleModeAttr(S, D, Attr);
5095 case AttributeList::AT_NoAlias:
5096 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5098 case AttributeList::AT_NoCommon:
5099 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5101 case AttributeList::AT_NoSplitStack:
5102 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5104 case AttributeList::AT_NonNull:
5105 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5106 handleNonNullAttrParameter(S, PVD, Attr);
5108 handleNonNullAttr(S, D, Attr);
5110 case AttributeList::AT_ReturnsNonNull:
5111 handleReturnsNonNullAttr(S, D, Attr);
5113 case AttributeList::AT_AssumeAligned:
5114 handleAssumeAlignedAttr(S, D, Attr);
5116 case AttributeList::AT_Overloadable:
5117 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5119 case AttributeList::AT_Ownership:
5120 handleOwnershipAttr(S, D, Attr);
5122 case AttributeList::AT_Cold:
5123 handleColdAttr(S, D, Attr);
5125 case AttributeList::AT_Hot:
5126 handleHotAttr(S, D, Attr);
5128 case AttributeList::AT_Naked:
5129 handleNakedAttr(S, D, Attr);
5131 case AttributeList::AT_NoReturn:
5132 handleNoReturnAttr(S, D, Attr);
5134 case AttributeList::AT_NoThrow:
5135 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5137 case AttributeList::AT_CUDAShared:
5138 handleSimpleAttributeWithExclusions<CUDASharedAttr, CUDAConstantAttr>(S, D,
5141 case AttributeList::AT_VecReturn:
5142 handleVecReturnAttr(S, D, Attr);
5145 case AttributeList::AT_ObjCOwnership:
5146 handleObjCOwnershipAttr(S, D, Attr);
5148 case AttributeList::AT_ObjCPreciseLifetime:
5149 handleObjCPreciseLifetimeAttr(S, D, Attr);
5152 case AttributeList::AT_ObjCReturnsInnerPointer:
5153 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5156 case AttributeList::AT_ObjCRequiresSuper:
5157 handleObjCRequiresSuperAttr(S, D, Attr);
5160 case AttributeList::AT_ObjCBridge:
5161 handleObjCBridgeAttr(S, scope, D, Attr);
5164 case AttributeList::AT_ObjCBridgeMutable:
5165 handleObjCBridgeMutableAttr(S, scope, D, Attr);
5168 case AttributeList::AT_ObjCBridgeRelated:
5169 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
5172 case AttributeList::AT_ObjCDesignatedInitializer:
5173 handleObjCDesignatedInitializer(S, D, Attr);
5176 case AttributeList::AT_ObjCRuntimeName:
5177 handleObjCRuntimeName(S, D, Attr);
5180 case AttributeList::AT_ObjCBoxable:
5181 handleObjCBoxable(S, D, Attr);
5184 case AttributeList::AT_CFAuditedTransfer:
5185 handleCFAuditedTransferAttr(S, D, Attr);
5187 case AttributeList::AT_CFUnknownTransfer:
5188 handleCFUnknownTransferAttr(S, D, Attr);
5191 case AttributeList::AT_CFConsumed:
5192 case AttributeList::AT_NSConsumed:
5193 handleNSConsumedAttr(S, D, Attr);
5195 case AttributeList::AT_NSConsumesSelf:
5196 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
5199 case AttributeList::AT_NSReturnsAutoreleased:
5200 case AttributeList::AT_NSReturnsNotRetained:
5201 case AttributeList::AT_CFReturnsNotRetained:
5202 case AttributeList::AT_NSReturnsRetained:
5203 case AttributeList::AT_CFReturnsRetained:
5204 handleNSReturnsRetainedAttr(S, D, Attr);
5206 case AttributeList::AT_WorkGroupSizeHint:
5207 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
5209 case AttributeList::AT_ReqdWorkGroupSize:
5210 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
5212 case AttributeList::AT_VecTypeHint:
5213 handleVecTypeHint(S, D, Attr);
5216 case AttributeList::AT_InitPriority:
5217 handleInitPriorityAttr(S, D, Attr);
5220 case AttributeList::AT_Packed:
5221 handlePackedAttr(S, D, Attr);
5223 case AttributeList::AT_Section:
5224 handleSectionAttr(S, D, Attr);
5226 case AttributeList::AT_Target:
5227 handleTargetAttr(S, D, Attr);
5229 case AttributeList::AT_Unavailable:
5230 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
5232 case AttributeList::AT_ArcWeakrefUnavailable:
5233 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
5235 case AttributeList::AT_ObjCRootClass:
5236 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
5238 case AttributeList::AT_ObjCExplicitProtocolImpl:
5239 handleObjCSuppresProtocolAttr(S, D, Attr);
5241 case AttributeList::AT_ObjCRequiresPropertyDefs:
5242 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
5244 case AttributeList::AT_Unused:
5245 handleSimpleAttribute<UnusedAttr>(S, D, Attr);
5247 case AttributeList::AT_ReturnsTwice:
5248 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
5250 case AttributeList::AT_NotTailCalled:
5251 handleNotTailCalledAttr(S, D, Attr);
5253 case AttributeList::AT_DisableTailCalls:
5254 handleDisableTailCallsAttr(S, D, Attr);
5256 case AttributeList::AT_Used:
5257 handleUsedAttr(S, D, Attr);
5259 case AttributeList::AT_Visibility:
5260 handleVisibilityAttr(S, D, Attr, false);
5262 case AttributeList::AT_TypeVisibility:
5263 handleVisibilityAttr(S, D, Attr, true);
5265 case AttributeList::AT_WarnUnused:
5266 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
5268 case AttributeList::AT_WarnUnusedResult:
5269 handleWarnUnusedResult(S, D, Attr);
5271 case AttributeList::AT_Weak:
5272 handleSimpleAttribute<WeakAttr>(S, D, Attr);
5274 case AttributeList::AT_WeakRef:
5275 handleWeakRefAttr(S, D, Attr);
5277 case AttributeList::AT_WeakImport:
5278 handleWeakImportAttr(S, D, Attr);
5280 case AttributeList::AT_TransparentUnion:
5281 handleTransparentUnionAttr(S, D, Attr);
5283 case AttributeList::AT_ObjCException:
5284 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
5286 case AttributeList::AT_ObjCMethodFamily:
5287 handleObjCMethodFamilyAttr(S, D, Attr);
5289 case AttributeList::AT_ObjCNSObject:
5290 handleObjCNSObject(S, D, Attr);
5292 case AttributeList::AT_ObjCIndependentClass:
5293 handleObjCIndependentClass(S, D, Attr);
5295 case AttributeList::AT_Blocks:
5296 handleBlocksAttr(S, D, Attr);
5298 case AttributeList::AT_Sentinel:
5299 handleSentinelAttr(S, D, Attr);
5301 case AttributeList::AT_Const:
5302 handleSimpleAttribute<ConstAttr>(S, D, Attr);
5304 case AttributeList::AT_Pure:
5305 handleSimpleAttribute<PureAttr>(S, D, Attr);
5307 case AttributeList::AT_Cleanup:
5308 handleCleanupAttr(S, D, Attr);
5310 case AttributeList::AT_NoDebug:
5311 handleNoDebugAttr(S, D, Attr);
5313 case AttributeList::AT_NoDuplicate:
5314 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
5316 case AttributeList::AT_NoInline:
5317 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
5319 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
5320 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
5322 case AttributeList::AT_StdCall:
5323 case AttributeList::AT_CDecl:
5324 case AttributeList::AT_FastCall:
5325 case AttributeList::AT_ThisCall:
5326 case AttributeList::AT_Pascal:
5327 case AttributeList::AT_VectorCall:
5328 case AttributeList::AT_MSABI:
5329 case AttributeList::AT_SysVABI:
5330 case AttributeList::AT_Pcs:
5331 case AttributeList::AT_IntelOclBicc:
5332 handleCallConvAttr(S, D, Attr);
5334 case AttributeList::AT_OpenCLKernel:
5335 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
5337 case AttributeList::AT_OpenCLImageAccess:
5338 handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr);
5340 case AttributeList::AT_InternalLinkage:
5341 handleInternalLinkageAttr(S, D, Attr);
5344 // Microsoft attributes:
5345 case AttributeList::AT_MSNoVTable:
5346 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
5348 case AttributeList::AT_MSStruct:
5349 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
5351 case AttributeList::AT_Uuid:
5352 handleUuidAttr(S, D, Attr);
5354 case AttributeList::AT_MSInheritance:
5355 handleMSInheritanceAttr(S, D, Attr);
5357 case AttributeList::AT_SelectAny:
5358 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
5360 case AttributeList::AT_Thread:
5361 handleDeclspecThreadAttr(S, D, Attr);
5364 // Thread safety attributes:
5365 case AttributeList::AT_AssertExclusiveLock:
5366 handleAssertExclusiveLockAttr(S, D, Attr);
5368 case AttributeList::AT_AssertSharedLock:
5369 handleAssertSharedLockAttr(S, D, Attr);
5371 case AttributeList::AT_GuardedVar:
5372 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
5374 case AttributeList::AT_PtGuardedVar:
5375 handlePtGuardedVarAttr(S, D, Attr);
5377 case AttributeList::AT_ScopedLockable:
5378 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
5380 case AttributeList::AT_NoSanitize:
5381 handleNoSanitizeAttr(S, D, Attr);
5383 case AttributeList::AT_NoSanitizeSpecific:
5384 handleNoSanitizeSpecificAttr(S, D, Attr);
5386 case AttributeList::AT_NoThreadSafetyAnalysis:
5387 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
5389 case AttributeList::AT_GuardedBy:
5390 handleGuardedByAttr(S, D, Attr);
5392 case AttributeList::AT_PtGuardedBy:
5393 handlePtGuardedByAttr(S, D, Attr);
5395 case AttributeList::AT_ExclusiveTrylockFunction:
5396 handleExclusiveTrylockFunctionAttr(S, D, Attr);
5398 case AttributeList::AT_LockReturned:
5399 handleLockReturnedAttr(S, D, Attr);
5401 case AttributeList::AT_LocksExcluded:
5402 handleLocksExcludedAttr(S, D, Attr);
5404 case AttributeList::AT_SharedTrylockFunction:
5405 handleSharedTrylockFunctionAttr(S, D, Attr);
5407 case AttributeList::AT_AcquiredBefore:
5408 handleAcquiredBeforeAttr(S, D, Attr);
5410 case AttributeList::AT_AcquiredAfter:
5411 handleAcquiredAfterAttr(S, D, Attr);
5414 // Capability analysis attributes.
5415 case AttributeList::AT_Capability:
5416 case AttributeList::AT_Lockable:
5417 handleCapabilityAttr(S, D, Attr);
5419 case AttributeList::AT_RequiresCapability:
5420 handleRequiresCapabilityAttr(S, D, Attr);
5423 case AttributeList::AT_AssertCapability:
5424 handleAssertCapabilityAttr(S, D, Attr);
5426 case AttributeList::AT_AcquireCapability:
5427 handleAcquireCapabilityAttr(S, D, Attr);
5429 case AttributeList::AT_ReleaseCapability:
5430 handleReleaseCapabilityAttr(S, D, Attr);
5432 case AttributeList::AT_TryAcquireCapability:
5433 handleTryAcquireCapabilityAttr(S, D, Attr);
5436 // Consumed analysis attributes.
5437 case AttributeList::AT_Consumable:
5438 handleConsumableAttr(S, D, Attr);
5440 case AttributeList::AT_ConsumableAutoCast:
5441 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
5443 case AttributeList::AT_ConsumableSetOnRead:
5444 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
5446 case AttributeList::AT_CallableWhen:
5447 handleCallableWhenAttr(S, D, Attr);
5449 case AttributeList::AT_ParamTypestate:
5450 handleParamTypestateAttr(S, D, Attr);
5452 case AttributeList::AT_ReturnTypestate:
5453 handleReturnTypestateAttr(S, D, Attr);
5455 case AttributeList::AT_SetTypestate:
5456 handleSetTypestateAttr(S, D, Attr);
5458 case AttributeList::AT_TestTypestate:
5459 handleTestTypestateAttr(S, D, Attr);
5462 // Type safety attributes.
5463 case AttributeList::AT_ArgumentWithTypeTag:
5464 handleArgumentWithTypeTagAttr(S, D, Attr);
5466 case AttributeList::AT_TypeTagForDatatype:
5467 handleTypeTagForDatatypeAttr(S, D, Attr);
5472 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5473 /// attribute list to the specified decl, ignoring any type attributes.
5474 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
5475 const AttributeList *AttrList,
5476 bool IncludeCXX11Attributes) {
5477 for (const AttributeList* l = AttrList; l; l = l->getNext())
5478 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
5480 // FIXME: We should be able to handle these cases in TableGen.
5482 // static int a9 __attribute__((weakref));
5483 // but that looks really pointless. We reject it.
5484 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
5485 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
5486 << cast<NamedDecl>(D);
5487 D->dropAttr<WeakRefAttr>();
5491 // FIXME: We should be able to handle this in TableGen as well. It would be
5492 // good to have a way to specify "these attributes must appear as a group",
5493 // for these. Additionally, it would be good to have a way to specify "these
5494 // attribute must never appear as a group" for attributes like cold and hot.
5495 if (!D->hasAttr<OpenCLKernelAttr>()) {
5496 // These attributes cannot be applied to a non-kernel function.
5497 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
5498 // FIXME: This emits a different error message than
5499 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
5500 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5501 D->setInvalidDecl();
5502 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
5503 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5504 D->setInvalidDecl();
5505 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
5506 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5507 D->setInvalidDecl();
5508 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
5509 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5510 << A << ExpectedKernelFunction;
5511 D->setInvalidDecl();
5512 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
5513 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5514 << A << ExpectedKernelFunction;
5515 D->setInvalidDecl();
5520 // Annotation attributes are the only attributes allowed after an access
5522 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5523 const AttributeList *AttrList) {
5524 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5525 if (l->getKind() == AttributeList::AT_Annotate) {
5526 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
5528 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
5536 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
5537 /// contains any decl attributes that we should warn about.
5538 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
5539 for ( ; A; A = A->getNext()) {
5540 // Only warn if the attribute is an unignored, non-type attribute.
5541 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
5542 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
5544 if (A->getKind() == AttributeList::UnknownAttribute) {
5545 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
5546 << A->getName() << A->getRange();
5548 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
5549 << A->getName() << A->getRange();
5554 /// checkUnusedDeclAttributes - Given a declarator which is not being
5555 /// used to build a declaration, complain about any decl attributes
5556 /// which might be lying around on it.
5557 void Sema::checkUnusedDeclAttributes(Declarator &D) {
5558 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
5559 ::checkUnusedDeclAttributes(*this, D.getAttributes());
5560 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
5561 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
5564 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5565 /// \#pragma weak needs a non-definition decl and source may not have one.
5566 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5567 SourceLocation Loc) {
5568 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
5569 NamedDecl *NewD = nullptr;
5570 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5571 FunctionDecl *NewFD;
5572 // FIXME: Missing call to CheckFunctionDeclaration().
5574 // FIXME: Is the qualifier info correct?
5575 // FIXME: Is the DeclContext correct?
5576 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
5577 Loc, Loc, DeclarationName(II),
5578 FD->getType(), FD->getTypeSourceInfo(),
5579 SC_None, false/*isInlineSpecified*/,
5581 false/*isConstexprSpecified*/);
5584 if (FD->getQualifier())
5585 NewFD->setQualifierInfo(FD->getQualifierLoc());
5587 // Fake up parameter variables; they are declared as if this were
5589 QualType FDTy = FD->getType();
5590 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5591 SmallVector<ParmVarDecl*, 16> Params;
5592 for (const auto &AI : FT->param_types()) {
5593 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
5594 Param->setScopeInfo(0, Params.size());
5595 Params.push_back(Param);
5597 NewFD->setParams(Params);
5599 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5600 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
5601 VD->getInnerLocStart(), VD->getLocation(), II,
5602 VD->getType(), VD->getTypeSourceInfo(),
5603 VD->getStorageClass());
5604 if (VD->getQualifier()) {
5605 VarDecl *NewVD = cast<VarDecl>(NewD);
5606 NewVD->setQualifierInfo(VD->getQualifierLoc());
5612 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5613 /// applied to it, possibly with an alias.
5614 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
5615 if (W.getUsed()) return; // only do this once
5617 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5618 IdentifierInfo *NDId = ND->getIdentifier();
5619 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
5620 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
5622 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5623 WeakTopLevelDecl.push_back(NewD);
5624 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5625 // to insert Decl at TU scope, sorry.
5626 DeclContext *SavedContext = CurContext;
5627 CurContext = Context.getTranslationUnitDecl();
5628 NewD->setDeclContext(CurContext);
5629 NewD->setLexicalDeclContext(CurContext);
5630 PushOnScopeChains(NewD, S);
5631 CurContext = SavedContext;
5632 } else { // just add weak to existing
5633 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
5637 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
5638 // It's valid to "forward-declare" #pragma weak, in which case we
5640 LoadExternalWeakUndeclaredIdentifiers();
5641 if (!WeakUndeclaredIdentifiers.empty()) {
5642 NamedDecl *ND = nullptr;
5643 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5644 if (VD->isExternC())
5646 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5647 if (FD->isExternC())
5650 if (IdentifierInfo *Id = ND->getIdentifier()) {
5651 auto I = WeakUndeclaredIdentifiers.find(Id);
5652 if (I != WeakUndeclaredIdentifiers.end()) {
5653 WeakInfo W = I->second;
5654 DeclApplyPragmaWeak(S, ND, W);
5655 WeakUndeclaredIdentifiers[Id] = W;
5662 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
5663 /// it, apply them to D. This is a bit tricky because PD can have attributes
5664 /// specified in many different places, and we need to find and apply them all.
5665 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
5666 // Apply decl attributes from the DeclSpec if present.
5667 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
5668 ProcessDeclAttributeList(S, D, Attrs);
5670 // Walk the declarator structure, applying decl attributes that were in a type
5671 // position to the decl itself. This handles cases like:
5672 // int *__attr__(x)** D;
5673 // when X is a decl attribute.
5674 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5675 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5676 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
5678 // Finally, apply any attributes on the decl itself.
5679 if (const AttributeList *Attrs = PD.getAttributes())
5680 ProcessDeclAttributeList(S, D, Attrs);
5683 /// Is the given declaration allowed to use a forbidden type?
5684 /// If so, it'll still be annotated with an attribute that makes it
5685 /// illegal to actually use.
5686 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
5687 const DelayedDiagnostic &diag,
5688 UnavailableAttr::ImplicitReason &reason) {
5689 // Private ivars are always okay. Unfortunately, people don't
5690 // always properly make their ivars private, even in system headers.
5691 // Plus we need to make fields okay, too.
5692 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5693 !isa<FunctionDecl>(decl))
5696 // Silently accept unsupported uses of __weak in both user and system
5697 // declarations when it's been disabled, for ease of integration with
5698 // -fno-objc-arc files. We do have to take some care against attempts
5699 // to define such things; for now, we've only done that for ivars
5701 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
5702 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
5703 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
5704 reason = UnavailableAttr::IR_ForbiddenWeak;
5709 // Allow all sorts of things in system headers.
5710 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
5711 // Currently, all the failures dealt with this way are due to ARC
5713 reason = UnavailableAttr::IR_ARCForbiddenType;
5720 /// Handle a delayed forbidden-type diagnostic.
5721 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5723 auto reason = UnavailableAttr::IR_None;
5724 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
5725 assert(reason && "didn't set reason?");
5726 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
5730 if (S.getLangOpts().ObjCAutoRefCount)
5731 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5732 // FIXME: we may want to suppress diagnostics for all
5733 // kind of forbidden type messages on unavailable functions.
5734 if (FD->hasAttr<UnavailableAttr>() &&
5735 diag.getForbiddenTypeDiagnostic() ==
5736 diag::err_arc_array_param_no_ownership) {
5737 diag.Triggered = true;
5742 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5743 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5744 diag.Triggered = true;
5748 static bool isDeclDeprecated(Decl *D) {
5750 if (D->isDeprecated())
5752 // A category implicitly has the availability of the interface.
5753 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5754 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5755 return Interface->isDeprecated();
5756 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5760 static bool isDeclUnavailable(Decl *D) {
5762 if (D->isUnavailable())
5764 // A category implicitly has the availability of the interface.
5765 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5766 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
5767 return Interface->isUnavailable();
5768 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5772 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
5773 Decl *Ctx, const NamedDecl *D,
5774 StringRef Message, SourceLocation Loc,
5775 const ObjCInterfaceDecl *UnknownObjCClass,
5776 const ObjCPropertyDecl *ObjCProperty,
5777 bool ObjCPropertyAccess) {
5778 // Diagnostics for deprecated or unavailable.
5779 unsigned diag, diag_message, diag_fwdclass_message;
5780 unsigned diag_available_here = diag::note_availability_specified_here;
5782 // Matches 'diag::note_property_attribute' options.
5783 unsigned property_note_select;
5785 // Matches diag::note_availability_specified_here.
5786 unsigned available_here_select_kind;
5788 // Don't warn if our current context is deprecated or unavailable.
5790 case Sema::AD_Deprecation:
5791 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
5793 diag = !ObjCPropertyAccess ? diag::warn_deprecated
5794 : diag::warn_property_method_deprecated;
5795 diag_message = diag::warn_deprecated_message;
5796 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
5797 property_note_select = /* deprecated */ 0;
5798 available_here_select_kind = /* deprecated */ 2;
5801 case Sema::AD_Unavailable:
5802 if (isDeclUnavailable(Ctx))
5804 diag = !ObjCPropertyAccess ? diag::err_unavailable
5805 : diag::err_property_method_unavailable;
5806 diag_message = diag::err_unavailable_message;
5807 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
5808 property_note_select = /* unavailable */ 1;
5809 available_here_select_kind = /* unavailable */ 0;
5811 if (auto attr = D->getAttr<UnavailableAttr>()) {
5812 if (attr->isImplicit() && attr->getImplicitReason()) {
5813 // Most of these failures are due to extra restrictions in ARC;
5814 // reflect that in the primary diagnostic when applicable.
5815 auto flagARCError = [&] {
5816 if (S.getLangOpts().ObjCAutoRefCount &&
5817 S.getSourceManager().isInSystemHeader(D->getLocation()))
5818 diag = diag::err_unavailable_in_arc;
5821 switch (attr->getImplicitReason()) {
5822 case UnavailableAttr::IR_None: break;
5824 case UnavailableAttr::IR_ARCForbiddenType:
5826 diag_available_here = diag::note_arc_forbidden_type;
5829 case UnavailableAttr::IR_ForbiddenWeak:
5830 if (S.getLangOpts().ObjCWeakRuntime)
5831 diag_available_here = diag::note_arc_weak_disabled;
5833 diag_available_here = diag::note_arc_weak_no_runtime;
5836 case UnavailableAttr::IR_ARCForbiddenConversion:
5838 diag_available_here = diag::note_performs_forbidden_arc_conversion;
5841 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
5843 diag_available_here = diag::note_arc_init_returns_unrelated;
5846 case UnavailableAttr::IR_ARCFieldWithOwnership:
5848 diag_available_here = diag::note_arc_field_with_ownership;
5856 case Sema::AD_Partial:
5857 diag = diag::warn_partial_availability;
5858 diag_message = diag::warn_partial_message;
5859 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
5860 property_note_select = /* partial */ 2;
5861 available_here_select_kind = /* partial */ 3;
5865 if (!Message.empty()) {
5866 S.Diag(Loc, diag_message) << D << Message;
5868 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5869 << ObjCProperty->getDeclName() << property_note_select;
5870 } else if (!UnknownObjCClass) {
5871 S.Diag(Loc, diag) << D;
5873 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
5874 << ObjCProperty->getDeclName() << property_note_select;
5876 S.Diag(Loc, diag_fwdclass_message) << D;
5877 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5880 S.Diag(D->getLocation(), diag_available_here)
5881 << D << available_here_select_kind;
5882 if (K == Sema::AD_Partial)
5883 S.Diag(Loc, diag::note_partial_availability_silence) << D;
5886 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
5888 assert(DD.Kind == DelayedDiagnostic::Deprecation ||
5889 DD.Kind == DelayedDiagnostic::Unavailable);
5890 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
5891 ? Sema::AD_Deprecation
5892 : Sema::AD_Unavailable;
5893 DD.Triggered = true;
5894 DoEmitAvailabilityWarning(
5895 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
5896 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
5899 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5900 assert(DelayedDiagnostics.getCurrentPool());
5901 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5902 DelayedDiagnostics.popWithoutEmitting(state);
5904 // When delaying diagnostics to run in the context of a parsed
5905 // declaration, we only want to actually emit anything if parsing
5909 // We emit all the active diagnostics in this pool or any of its
5910 // parents. In general, we'll get one pool for the decl spec
5911 // and a child pool for each declarator; in a decl group like:
5912 // deprecated_typedef foo, *bar, baz();
5913 // only the declarator pops will be passed decls. This is correct;
5914 // we really do need to consider delayed diagnostics from the decl spec
5915 // for each of the different declarations.
5916 const DelayedDiagnosticPool *pool = &poppedPool;
5918 for (DelayedDiagnosticPool::pool_iterator
5919 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5920 // This const_cast is a bit lame. Really, Triggered should be mutable.
5921 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5925 switch (diag.Kind) {
5926 case DelayedDiagnostic::Deprecation:
5927 case DelayedDiagnostic::Unavailable:
5928 // Don't bother giving deprecation/unavailable diagnostics if
5929 // the decl is invalid.
5930 if (!decl->isInvalidDecl())
5931 handleDelayedAvailabilityCheck(*this, diag, decl);
5934 case DelayedDiagnostic::Access:
5935 HandleDelayedAccessCheck(diag, decl);
5938 case DelayedDiagnostic::ForbiddenType:
5939 handleDelayedForbiddenType(*this, diag, decl);
5943 } while ((pool = pool->getParent()));
5946 /// Given a set of delayed diagnostics, re-emit them as if they had
5947 /// been delayed in the current context instead of in the given pool.
5948 /// Essentially, this just moves them to the current pool.
5949 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5950 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5951 assert(curPool && "re-emitting in undelayed context not supported");
5952 curPool->steal(pool);
5955 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
5956 NamedDecl *D, StringRef Message,
5958 const ObjCInterfaceDecl *UnknownObjCClass,
5959 const ObjCPropertyDecl *ObjCProperty,
5960 bool ObjCPropertyAccess) {
5961 // Delay if we're currently parsing a declaration.
5962 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
5963 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
5964 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
5965 ObjCPropertyAccess));
5969 Decl *Ctx = cast<Decl>(getCurLexicalContext());
5970 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
5971 ObjCProperty, ObjCPropertyAccess);