1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements decl-related attribute processing.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/MathExtras.h"
39 using namespace clang;
42 namespace AttributeLangSupport {
48 } // end namespace AttributeLangSupport
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 /// isFunctionOrMethod - Return true if the given decl has function
55 /// type (function or function-typed variable) or an Objective-C
57 static bool isFunctionOrMethod(const Decl *D) {
58 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
61 /// \brief Return true if the given decl has function type (function or
62 /// function-typed variable) or an Objective-C method or a block.
63 static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
67 /// Return true if the given decl has a declarator that should have
68 /// been processed by Sema::GetTypeForDeclarator.
69 static bool hasDeclarator(const Decl *D) {
70 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
71 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
75 /// hasFunctionProto - Return true if the given decl has a argument
76 /// information. This decl should have already passed
77 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
78 static bool hasFunctionProto(const Decl *D) {
79 if (const FunctionType *FnTy = D->getFunctionType())
80 return isa<FunctionProtoType>(FnTy);
81 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
84 /// getFunctionOrMethodNumParams - Return number of function or method
85 /// parameters. It is an error to call this on a K&R function (use
86 /// hasFunctionProto first).
87 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
88 if (const FunctionType *FnTy = D->getFunctionType())
89 return cast<FunctionProtoType>(FnTy)->getNumParams();
90 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
91 return BD->getNumParams();
92 return cast<ObjCMethodDecl>(D)->param_size();
95 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
96 if (const FunctionType *FnTy = D->getFunctionType())
97 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
98 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
99 return BD->getParamDecl(Idx)->getType();
101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
104 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
105 if (const auto *FD = dyn_cast<FunctionDecl>(D))
106 return FD->getParamDecl(Idx)->getSourceRange();
107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
108 return MD->parameters()[Idx]->getSourceRange();
109 if (const auto *BD = dyn_cast<BlockDecl>(D))
110 return BD->getParamDecl(Idx)->getSourceRange();
111 return SourceRange();
114 static QualType getFunctionOrMethodResultType(const Decl *D) {
115 if (const FunctionType *FnTy = D->getFunctionType())
116 return cast<FunctionType>(FnTy)->getReturnType();
117 return cast<ObjCMethodDecl>(D)->getReturnType();
120 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
121 if (const auto *FD = dyn_cast<FunctionDecl>(D))
122 return FD->getReturnTypeSourceRange();
123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
124 return MD->getReturnTypeSourceRange();
125 return SourceRange();
128 static bool isFunctionOrMethodVariadic(const Decl *D) {
129 if (const FunctionType *FnTy = D->getFunctionType()) {
130 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
131 return proto->isVariadic();
133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
134 return BD->isVariadic();
136 return cast<ObjCMethodDecl>(D)->isVariadic();
139 static bool isInstanceMethod(const Decl *D) {
140 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
141 return MethodDecl->isInstance();
145 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
146 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
150 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
154 IdentifierInfo* ClsName = Cls->getIdentifier();
156 // FIXME: Should we walk the chain of classes?
157 return ClsName == &Ctx.Idents.get("NSString") ||
158 ClsName == &Ctx.Idents.get("NSMutableString");
161 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
162 const PointerType *PT = T->getAs<PointerType>();
166 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
170 const RecordDecl *RD = RT->getDecl();
171 if (RD->getTagKind() != TTK_Struct)
174 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
177 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
178 // FIXME: Include the type in the argument list.
179 return Attr.getNumArgs() + Attr.hasParsedType();
182 template <typename Compare>
183 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
184 unsigned Num, unsigned Diag,
186 if (Comp(getNumAttributeArgs(Attr), Num)) {
187 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
194 /// \brief Check if the attribute has exactly as many args as Num. May
196 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
198 return checkAttributeNumArgsImpl(S, Attr, Num,
199 diag::err_attribute_wrong_number_arguments,
200 std::not_equal_to<unsigned>());
203 /// \brief Check if the attribute has at least as many args as Num. May
205 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
207 return checkAttributeNumArgsImpl(S, Attr, Num,
208 diag::err_attribute_too_few_arguments,
209 std::less<unsigned>());
212 /// \brief Check if the attribute has at most as many args as Num. May
214 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
216 return checkAttributeNumArgsImpl(S, Attr, Num,
217 diag::err_attribute_too_many_arguments,
218 std::greater<unsigned>());
221 /// \brief A helper function to provide Attribute Location for the Attr types
222 /// AND the AttributeList.
223 template <typename AttrInfo>
224 static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
225 SourceLocation>::type
226 getAttrLoc(const AttrInfo &Attr) {
227 return Attr.getLocation();
229 static SourceLocation getAttrLoc(const clang::AttributeList &Attr) {
230 return Attr.getLoc();
233 /// \brief A helper function to provide Attribute Name for the Attr types
234 /// AND the AttributeList.
235 template <typename AttrInfo>
236 static typename std::enable_if<std::is_base_of<clang::Attr, AttrInfo>::value,
237 const AttrInfo *>::type
238 getAttrName(const AttrInfo &Attr) {
241 const IdentifierInfo *getAttrName(const clang::AttributeList &Attr) {
242 return Attr.getName();
245 /// \brief If Expr is a valid integer constant, get the value of the integer
246 /// expression and return success or failure. May output an error.
247 template<typename AttrInfo>
248 static bool checkUInt32Argument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
249 uint32_t &Val, unsigned Idx = UINT_MAX) {
251 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
252 !Expr->isIntegerConstantExpr(I, S.Context)) {
254 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
255 << getAttrName(Attr) << Idx << AANT_ArgumentIntegerConstant
256 << Expr->getSourceRange();
258 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_type)
259 << getAttrName(Attr) << AANT_ArgumentIntegerConstant
260 << Expr->getSourceRange();
265 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
266 << I.toString(10, false) << 32 << /* Unsigned */ 1;
270 Val = (uint32_t)I.getZExtValue();
274 /// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
275 /// that the result will fit into a regular (signed) int. All args have the same
276 /// purpose as they do in checkUInt32Argument.
277 template<typename AttrInfo>
278 static bool checkPositiveIntArgument(Sema &S, const AttrInfo& Attr, const Expr *Expr,
279 int &Val, unsigned Idx = UINT_MAX) {
281 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
284 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
285 llvm::APSInt I(32); // for toString
287 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
288 << I.toString(10, false) << 32 << /* Unsigned */ 0;
296 /// \brief Diagnose mutually exclusive attributes when present on a given
297 /// declaration. Returns true if diagnosed.
298 template <typename AttrTy>
299 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
300 IdentifierInfo *Ident) {
301 if (AttrTy *A = D->getAttr<AttrTy>()) {
302 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
304 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
310 /// \brief Check if IdxExpr is a valid parameter index for a function or
311 /// instance method D. May output an error.
313 /// \returns true if IdxExpr is a valid index.
314 template <typename AttrInfo>
315 static bool checkFunctionOrMethodParameterIndex(
316 Sema &S, const Decl *D, const AttrInfo& Attr,
317 unsigned AttrArgNum, const Expr *IdxExpr, uint64_t &Idx) {
318 assert(isFunctionOrMethodOrBlock(D));
320 // In C++ the implicit 'this' function parameter also counts.
321 // Parameters are counted from one.
322 bool HP = hasFunctionProto(D);
323 bool HasImplicitThisParam = isInstanceMethod(D);
324 bool IV = HP && isFunctionOrMethodVariadic(D);
326 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
329 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
330 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
331 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_n_type)
332 << getAttrName(Attr) << AttrArgNum << AANT_ArgumentIntegerConstant
333 << IdxExpr->getSourceRange();
337 Idx = IdxInt.getLimitedValue();
338 if (Idx < 1 || (!IV && Idx > NumParams)) {
339 S.Diag(getAttrLoc(Attr), diag::err_attribute_argument_out_of_bounds)
340 << getAttrName(Attr) << AttrArgNum << IdxExpr->getSourceRange();
343 Idx--; // Convert to zero-based.
344 if (HasImplicitThisParam) {
346 S.Diag(getAttrLoc(Attr),
347 diag::err_attribute_invalid_implicit_this_argument)
348 << getAttrName(Attr) << IdxExpr->getSourceRange();
357 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
358 /// If not emit an error and return false. If the argument is an identifier it
359 /// will emit an error with a fixit hint and treat it as if it was a string
361 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
362 unsigned ArgNum, StringRef &Str,
363 SourceLocation *ArgLocation) {
364 // Look for identifiers. If we have one emit a hint to fix it to a literal.
365 if (Attr.isArgIdent(ArgNum)) {
366 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
367 Diag(Loc->Loc, diag::err_attribute_argument_type)
368 << Attr.getName() << AANT_ArgumentString
369 << FixItHint::CreateInsertion(Loc->Loc, "\"")
370 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
371 Str = Loc->Ident->getName();
373 *ArgLocation = Loc->Loc;
377 // Now check for an actual string literal.
378 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
379 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
381 *ArgLocation = ArgExpr->getLocStart();
383 if (!Literal || !Literal->isAscii()) {
384 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
385 << Attr.getName() << AANT_ArgumentString;
389 Str = Literal->getString();
393 /// \brief Applies the given attribute to the Decl without performing any
394 /// additional semantic checking.
395 template <typename AttrType>
396 static void handleSimpleAttribute(Sema &S, Decl *D,
397 const AttributeList &Attr) {
398 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
399 Attr.getAttributeSpellingListIndex()));
402 template <typename AttrType>
403 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
404 const AttributeList &Attr) {
405 handleSimpleAttribute<AttrType>(S, D, Attr);
408 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't
409 /// already have one of the given incompatible attributes.
410 template <typename AttrType, typename IncompatibleAttrType,
411 typename... IncompatibleAttrTypes>
412 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
413 const AttributeList &Attr) {
414 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
417 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
421 /// \brief Check if the passed-in expression is of type int or bool.
422 static bool isIntOrBool(Expr *Exp) {
423 QualType QT = Exp->getType();
424 return QT->isBooleanType() || QT->isIntegerType();
428 // Check to see if the type is a smart pointer of some kind. We assume
429 // it's a smart pointer if it defines both operator-> and operator*.
430 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
431 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
432 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
436 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
437 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
444 /// \brief Check if passed in Decl is a pointer type.
445 /// Note that this function may produce an error message.
446 /// \return true if the Decl is a pointer type; false otherwise
447 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
448 const AttributeList &Attr) {
449 const ValueDecl *vd = cast<ValueDecl>(D);
450 QualType QT = vd->getType();
451 if (QT->isAnyPointerType())
454 if (const RecordType *RT = QT->getAs<RecordType>()) {
455 // If it's an incomplete type, it could be a smart pointer; skip it.
456 // (We don't want to force template instantiation if we can avoid it,
457 // since that would alter the order in which templates are instantiated.)
458 if (RT->isIncompleteType())
461 if (threadSafetyCheckIsSmartPointer(S, RT))
465 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
466 << Attr.getName() << QT;
470 /// \brief Checks that the passed in QualType either is of RecordType or points
471 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
472 static const RecordType *getRecordType(QualType QT) {
473 if (const RecordType *RT = QT->getAs<RecordType>())
476 // Now check if we point to record type.
477 if (const PointerType *PT = QT->getAs<PointerType>())
478 return PT->getPointeeType()->getAs<RecordType>();
483 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
484 const RecordType *RT = getRecordType(Ty);
489 // Don't check for the capability if the class hasn't been defined yet.
490 if (RT->isIncompleteType())
493 // Allow smart pointers to be used as capability objects.
494 // FIXME -- Check the type that the smart pointer points to.
495 if (threadSafetyCheckIsSmartPointer(S, RT))
498 // Check if the record itself has a capability.
499 RecordDecl *RD = RT->getDecl();
500 if (RD->hasAttr<CapabilityAttr>())
503 // Else check if any base classes have a capability.
504 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
505 CXXBasePaths BPaths(false, false);
506 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
507 const auto *Type = BS->getType()->getAs<RecordType>();
508 return Type->getDecl()->hasAttr<CapabilityAttr>();
515 static bool checkTypedefTypeForCapability(QualType Ty) {
516 const auto *TD = Ty->getAs<TypedefType>();
520 TypedefNameDecl *TN = TD->getDecl();
524 return TN->hasAttr<CapabilityAttr>();
527 static bool typeHasCapability(Sema &S, QualType Ty) {
528 if (checkTypedefTypeForCapability(Ty))
531 if (checkRecordTypeForCapability(S, Ty))
537 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
538 // Capability expressions are simple expressions involving the boolean logic
539 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
540 // a DeclRefExpr is found, its type should be checked to determine whether it
541 // is a capability or not.
543 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
544 return typeHasCapability(S, E->getType());
545 else if (const auto *E = dyn_cast<CastExpr>(Ex))
546 return isCapabilityExpr(S, E->getSubExpr());
547 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
548 return isCapabilityExpr(S, E->getSubExpr());
549 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
550 if (E->getOpcode() == UO_LNot)
551 return isCapabilityExpr(S, E->getSubExpr());
553 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
554 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
555 return isCapabilityExpr(S, E->getLHS()) &&
556 isCapabilityExpr(S, E->getRHS());
563 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
564 /// a capability object.
565 /// \param Sidx The attribute argument index to start checking with.
566 /// \param ParamIdxOk Whether an argument can be indexing into a function
568 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
569 const AttributeList &Attr,
570 SmallVectorImpl<Expr *> &Args,
572 bool ParamIdxOk = false) {
573 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
574 Expr *ArgExp = Attr.getArgAsExpr(Idx);
576 if (ArgExp->isTypeDependent()) {
577 // FIXME -- need to check this again on template instantiation
578 Args.push_back(ArgExp);
582 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
583 if (StrLit->getLength() == 0 ||
584 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
585 // Pass empty strings to the analyzer without warnings.
586 // Treat "*" as the universal lock.
587 Args.push_back(ArgExp);
591 // We allow constant strings to be used as a placeholder for expressions
592 // that are not valid C++ syntax, but warn that they are ignored.
593 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
595 Args.push_back(ArgExp);
599 QualType ArgTy = ArgExp->getType();
601 // A pointer to member expression of the form &MyClass::mu is treated
602 // specially -- we need to look at the type of the member.
603 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
604 if (UOp->getOpcode() == UO_AddrOf)
605 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
606 if (DRE->getDecl()->isCXXInstanceMember())
607 ArgTy = DRE->getDecl()->getType();
609 // First see if we can just cast to record type, or pointer to record type.
610 const RecordType *RT = getRecordType(ArgTy);
612 // Now check if we index into a record type function param.
613 if(!RT && ParamIdxOk) {
614 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
615 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
617 unsigned int NumParams = FD->getNumParams();
618 llvm::APInt ArgValue = IL->getValue();
619 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
620 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
621 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
622 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
623 << Attr.getName() << Idx + 1 << NumParams;
626 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
630 // If the type does not have a capability, see if the components of the
631 // expression have capabilities. This allows for writing C code where the
632 // capability may be on the type, and the expression is a capability
633 // boolean logic expression. Eg) requires_capability(A || B && !C)
634 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
635 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
636 << Attr.getName() << ArgTy;
638 Args.push_back(ArgExp);
642 //===----------------------------------------------------------------------===//
643 // Attribute Implementations
644 //===----------------------------------------------------------------------===//
646 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
647 const AttributeList &Attr) {
648 if (!threadSafetyCheckIsPointer(S, D, Attr))
651 D->addAttr(::new (S.Context)
652 PtGuardedVarAttr(Attr.getRange(), S.Context,
653 Attr.getAttributeSpellingListIndex()));
656 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
657 const AttributeList &Attr,
659 SmallVector<Expr*, 1> Args;
660 // check that all arguments are lockable objects
661 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
662 unsigned Size = Args.size();
671 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
673 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
676 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
677 Attr.getAttributeSpellingListIndex()));
680 static void handlePtGuardedByAttr(Sema &S, Decl *D,
681 const AttributeList &Attr) {
683 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
686 if (!threadSafetyCheckIsPointer(S, D, Attr))
689 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
691 Attr.getAttributeSpellingListIndex()));
694 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
695 const AttributeList &Attr,
696 SmallVectorImpl<Expr *> &Args) {
697 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
700 // Check that this attribute only applies to lockable types.
701 QualType QT = cast<ValueDecl>(D)->getType();
702 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
703 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
708 // Check that all arguments are lockable objects.
709 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
716 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
717 const AttributeList &Attr) {
718 SmallVector<Expr*, 1> Args;
719 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
722 Expr **StartArg = &Args[0];
723 D->addAttr(::new (S.Context)
724 AcquiredAfterAttr(Attr.getRange(), S.Context,
725 StartArg, Args.size(),
726 Attr.getAttributeSpellingListIndex()));
729 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
730 const AttributeList &Attr) {
731 SmallVector<Expr*, 1> Args;
732 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
735 Expr **StartArg = &Args[0];
736 D->addAttr(::new (S.Context)
737 AcquiredBeforeAttr(Attr.getRange(), S.Context,
738 StartArg, Args.size(),
739 Attr.getAttributeSpellingListIndex()));
742 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
743 const AttributeList &Attr,
744 SmallVectorImpl<Expr *> &Args) {
745 // zero or more arguments ok
746 // check that all arguments are lockable objects
747 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
752 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
753 const AttributeList &Attr) {
754 SmallVector<Expr*, 1> Args;
755 if (!checkLockFunAttrCommon(S, D, Attr, Args))
758 unsigned Size = Args.size();
759 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
760 D->addAttr(::new (S.Context)
761 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
762 Attr.getAttributeSpellingListIndex()));
765 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
766 const AttributeList &Attr) {
767 SmallVector<Expr*, 1> Args;
768 if (!checkLockFunAttrCommon(S, D, Attr, Args))
771 unsigned Size = Args.size();
772 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
773 D->addAttr(::new (S.Context)
774 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
776 Attr.getAttributeSpellingListIndex()));
779 /// \brief Checks to be sure that the given parameter number is in bounds, and is
780 /// an integral type. Will emit appropriate diagnostics if this returns
783 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
784 /// to actually retrieve the argument, so it's base-0.
785 template <typename AttrInfo>
786 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
787 const AttrInfo &Attr, Expr *AttrArg,
788 unsigned FuncParamNo, unsigned AttrArgNo,
789 bool AllowDependentType = false) {
791 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo, AttrArg,
795 const ParmVarDecl *Param = FD->getParamDecl(Idx);
796 if (AllowDependentType && Param->getType()->isDependentType())
798 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
799 SourceLocation SrcLoc = AttrArg->getLocStart();
800 S.Diag(SrcLoc, diag::err_attribute_integers_only)
801 << getAttrName(Attr) << Param->getSourceRange();
807 /// \brief Checks to be sure that the given parameter number is in bounds, and is
808 /// an integral type. Will emit appropriate diagnostics if this returns false.
810 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
811 /// to actually retrieve the argument, so it's base-0.
812 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
813 const AttributeList &Attr,
814 unsigned FuncParamNo, unsigned AttrArgNo,
815 bool AllowDependentType = false) {
816 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
817 return checkParamIsIntegerType(S, FD, Attr, Attr.getArgAsExpr(AttrArgNo),
818 FuncParamNo, AttrArgNo, AllowDependentType);
821 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
822 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
823 !checkAttributeAtMostNumArgs(S, Attr, 2))
826 const auto *FD = cast<FunctionDecl>(D);
827 if (!FD->getReturnType()->isPointerType()) {
828 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
833 const Expr *SizeExpr = Attr.getArgAsExpr(0);
835 // Parameter indices are 1-indexed, hence Index=1
836 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
839 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
842 // Args are 1-indexed, so 0 implies that the arg was not present
844 if (Attr.getNumArgs() == 2) {
845 const Expr *NumberExpr = Attr.getArgAsExpr(1);
846 // Parameter indices are 1-based, hence Index=2
847 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
851 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
855 D->addAttr(::new (S.Context) AllocSizeAttr(
856 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
857 Attr.getAttributeSpellingListIndex()));
860 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
861 const AttributeList &Attr,
862 SmallVectorImpl<Expr *> &Args) {
863 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
866 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
867 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
868 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
872 // check that all arguments are lockable objects
873 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
878 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
879 const AttributeList &Attr) {
880 SmallVector<Expr*, 2> Args;
881 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
884 D->addAttr(::new (S.Context)
885 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
886 Attr.getArgAsExpr(0),
887 Args.data(), Args.size(),
888 Attr.getAttributeSpellingListIndex()));
891 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
892 const AttributeList &Attr) {
893 SmallVector<Expr*, 2> Args;
894 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
897 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
898 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
899 Args.size(), Attr.getAttributeSpellingListIndex()));
902 static void handleLockReturnedAttr(Sema &S, Decl *D,
903 const AttributeList &Attr) {
904 // check that the argument is lockable object
905 SmallVector<Expr*, 1> Args;
906 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
907 unsigned Size = Args.size();
911 D->addAttr(::new (S.Context)
912 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
913 Attr.getAttributeSpellingListIndex()));
916 static void handleLocksExcludedAttr(Sema &S, Decl *D,
917 const AttributeList &Attr) {
918 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
921 // check that all arguments are lockable objects
922 SmallVector<Expr*, 1> Args;
923 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
924 unsigned Size = Args.size();
927 Expr **StartArg = &Args[0];
929 D->addAttr(::new (S.Context)
930 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
931 Attr.getAttributeSpellingListIndex()));
934 static bool checkFunctionConditionAttr(Sema &S, Decl *D,
935 const AttributeList &Attr,
936 Expr *&Cond, StringRef &Msg) {
937 Cond = Attr.getArgAsExpr(0);
938 if (!Cond->isTypeDependent()) {
939 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
940 if (Converted.isInvalid())
942 Cond = Converted.get();
945 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
949 Msg = "<no message provided>";
951 SmallVector<PartialDiagnosticAt, 8> Diags;
952 if (!Cond->isValueDependent() &&
953 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
955 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
957 for (const PartialDiagnosticAt &PDiag : Diags)
958 S.Diag(PDiag.first, PDiag.second);
964 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
965 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
969 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
970 D->addAttr(::new (S.Context)
971 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
972 Attr.getAttributeSpellingListIndex()));
976 /// Determines if a given Expr references any of the given function's
977 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
978 class ArgumentDependenceChecker
979 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
981 const CXXRecordDecl *ClassType;
983 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
987 ArgumentDependenceChecker(const FunctionDecl *FD) {
989 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
990 ClassType = MD->getParent();
994 Parms.insert(FD->param_begin(), FD->param_end());
997 bool referencesArgs(Expr *E) {
1003 bool VisitCXXThisExpr(CXXThisExpr *E) {
1004 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1005 "`this` doesn't refer to the enclosing class?");
1010 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1011 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1012 if (Parms.count(PVD)) {
1021 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1022 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
1026 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
1029 StringRef DiagTypeStr;
1030 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
1033 DiagnoseIfAttr::DiagnosticType DiagType;
1034 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1035 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
1036 diag::err_diagnose_if_invalid_diagnostic_type);
1040 auto *FD = cast<FunctionDecl>(D);
1041 bool ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1042 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1043 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, FD,
1044 Attr.getAttributeSpellingListIndex()));
1047 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1048 const AttributeList &Attr) {
1049 if (D->hasAttr<PassObjectSizeAttr>()) {
1050 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1055 Expr *E = Attr.getArgAsExpr(0);
1057 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1060 // pass_object_size's argument is passed in as the second argument of
1061 // __builtin_object_size. So, it has the same constraints as that second
1062 // argument; namely, it must be in the range [0, 3].
1064 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1065 << Attr.getName() << 0 << 3 << E->getSourceRange();
1069 // pass_object_size is only supported on constant pointer parameters; as a
1070 // kindness to users, we allow the parameter to be non-const for declarations.
1071 // At this point, we have no clue if `D` belongs to a function declaration or
1072 // definition, so we defer the constness check until later.
1073 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1074 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1075 << Attr.getName() << 1;
1079 D->addAttr(::new (S.Context)
1080 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1081 Attr.getAttributeSpellingListIndex()));
1084 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1085 ConsumableAttr::ConsumedState DefaultState;
1087 if (Attr.isArgIdent(0)) {
1088 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1089 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1091 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1092 << Attr.getName() << IL->Ident;
1096 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1097 << Attr.getName() << AANT_ArgumentIdentifier;
1101 D->addAttr(::new (S.Context)
1102 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
1103 Attr.getAttributeSpellingListIndex()));
1106 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1107 const AttributeList &Attr) {
1108 ASTContext &CurrContext = S.getASTContext();
1109 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1111 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1112 if (!RD->hasAttr<ConsumableAttr>()) {
1113 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1114 RD->getNameAsString();
1123 static void handleCallableWhenAttr(Sema &S, Decl *D,
1124 const AttributeList &Attr) {
1125 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1128 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1131 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1132 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1133 CallableWhenAttr::ConsumedState CallableState;
1135 StringRef StateString;
1137 if (Attr.isArgIdent(ArgIndex)) {
1138 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1139 StateString = Ident->Ident->getName();
1142 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1146 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1148 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1149 << Attr.getName() << StateString;
1153 States.push_back(CallableState);
1156 D->addAttr(::new (S.Context)
1157 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1158 States.size(), Attr.getAttributeSpellingListIndex()));
1161 static void handleParamTypestateAttr(Sema &S, Decl *D,
1162 const AttributeList &Attr) {
1163 ParamTypestateAttr::ConsumedState ParamState;
1165 if (Attr.isArgIdent(0)) {
1166 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1167 StringRef StateString = Ident->Ident->getName();
1169 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1171 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1172 << Attr.getName() << StateString;
1176 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1177 Attr.getName() << AANT_ArgumentIdentifier;
1181 // FIXME: This check is currently being done in the analysis. It can be
1182 // enabled here only after the parser propagates attributes at
1183 // template specialization definition, not declaration.
1184 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1185 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1187 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1188 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1189 // ReturnType.getAsString();
1193 D->addAttr(::new (S.Context)
1194 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1195 Attr.getAttributeSpellingListIndex()));
1198 static void handleReturnTypestateAttr(Sema &S, Decl *D,
1199 const AttributeList &Attr) {
1200 ReturnTypestateAttr::ConsumedState ReturnState;
1202 if (Attr.isArgIdent(0)) {
1203 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1204 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1206 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1207 << Attr.getName() << IL->Ident;
1211 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1212 Attr.getName() << AANT_ArgumentIdentifier;
1216 // FIXME: This check is currently being done in the analysis. It can be
1217 // enabled here only after the parser propagates attributes at
1218 // template specialization definition, not declaration.
1219 //QualType ReturnType;
1221 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1222 // ReturnType = Param->getType();
1224 //} else if (const CXXConstructorDecl *Constructor =
1225 // dyn_cast<CXXConstructorDecl>(D)) {
1226 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1230 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1233 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1235 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1236 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1237 // ReturnType.getAsString();
1241 D->addAttr(::new (S.Context)
1242 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1243 Attr.getAttributeSpellingListIndex()));
1246 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1247 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1250 SetTypestateAttr::ConsumedState NewState;
1251 if (Attr.isArgIdent(0)) {
1252 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1253 StringRef Param = Ident->Ident->getName();
1254 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1255 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1256 << Attr.getName() << Param;
1260 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1261 Attr.getName() << AANT_ArgumentIdentifier;
1265 D->addAttr(::new (S.Context)
1266 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1267 Attr.getAttributeSpellingListIndex()));
1270 static void handleTestTypestateAttr(Sema &S, Decl *D,
1271 const AttributeList &Attr) {
1272 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1275 TestTypestateAttr::ConsumedState TestState;
1276 if (Attr.isArgIdent(0)) {
1277 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1278 StringRef Param = Ident->Ident->getName();
1279 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1280 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1281 << Attr.getName() << Param;
1285 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1286 Attr.getName() << AANT_ArgumentIdentifier;
1290 D->addAttr(::new (S.Context)
1291 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1292 Attr.getAttributeSpellingListIndex()));
1295 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1296 const AttributeList &Attr) {
1297 // Remember this typedef decl, we will need it later for diagnostics.
1298 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1301 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1302 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1303 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1304 Attr.getAttributeSpellingListIndex()));
1305 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1306 // Report warning about changed offset in the newer compiler versions.
1307 if (!FD->getType()->isDependentType() &&
1308 !FD->getType()->isIncompleteType() && FD->isBitField() &&
1309 S.Context.getTypeAlign(FD->getType()) <= 8)
1310 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1312 FD->addAttr(::new (S.Context) PackedAttr(
1313 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1315 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1318 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1319 // The IBOutlet/IBOutletCollection attributes only apply to instance
1320 // variables or properties of Objective-C classes. The outlet must also
1321 // have an object reference type.
1322 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1323 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1324 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1325 << Attr.getName() << VD->getType() << 0;
1329 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1330 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1331 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1332 << Attr.getName() << PD->getType() << 1;
1337 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1344 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1345 if (!checkIBOutletCommon(S, D, Attr))
1348 D->addAttr(::new (S.Context)
1349 IBOutletAttr(Attr.getRange(), S.Context,
1350 Attr.getAttributeSpellingListIndex()));
1353 static void handleIBOutletCollection(Sema &S, Decl *D,
1354 const AttributeList &Attr) {
1356 // The iboutletcollection attribute can have zero or one arguments.
1357 if (Attr.getNumArgs() > 1) {
1358 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1359 << Attr.getName() << 1;
1363 if (!checkIBOutletCommon(S, D, Attr))
1368 if (Attr.hasParsedType())
1369 PT = Attr.getTypeArg();
1371 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1372 S.getScopeForContext(D->getDeclContext()->getParent()));
1374 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1379 TypeSourceInfo *QTLoc = nullptr;
1380 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1382 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1384 // Diagnose use of non-object type in iboutletcollection attribute.
1385 // FIXME. Gnu attribute extension ignores use of builtin types in
1386 // attributes. So, __attribute__((iboutletcollection(char))) will be
1387 // treated as __attribute__((iboutletcollection())).
1388 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1389 S.Diag(Attr.getLoc(),
1390 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1391 : diag::err_iboutletcollection_type) << QT;
1395 D->addAttr(::new (S.Context)
1396 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1397 Attr.getAttributeSpellingListIndex()));
1400 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1402 if (T->isReferenceType())
1405 T = T.getNonReferenceType();
1408 // The nonnull attribute, and other similar attributes, can be applied to a
1409 // transparent union that contains a pointer type.
1410 if (const RecordType *UT = T->getAsUnionType()) {
1411 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1412 RecordDecl *UD = UT->getDecl();
1413 for (const auto *I : UD->fields()) {
1414 QualType QT = I->getType();
1415 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1421 return T->isAnyPointerType() || T->isBlockPointerType();
1424 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1425 SourceRange AttrParmRange,
1426 SourceRange TypeRange,
1427 bool isReturnValue = false) {
1428 if (!S.isValidPointerAttrType(T)) {
1430 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1431 << Attr.getName() << AttrParmRange << TypeRange;
1433 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1434 << Attr.getName() << AttrParmRange << TypeRange << 0;
1440 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1441 SmallVector<unsigned, 8> NonNullArgs;
1442 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1443 Expr *Ex = Attr.getArgAsExpr(I);
1445 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1448 // Is the function argument a pointer type?
1449 if (Idx < getFunctionOrMethodNumParams(D) &&
1450 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1451 Ex->getSourceRange(),
1452 getFunctionOrMethodParamRange(D, Idx)))
1455 NonNullArgs.push_back(Idx);
1458 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1459 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1460 // check if the attribute came from a macro expansion or a template
1462 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1463 !S.inTemplateInstantiation()) {
1464 bool AnyPointers = isFunctionOrMethodVariadic(D);
1465 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1466 I != E && !AnyPointers; ++I) {
1467 QualType T = getFunctionOrMethodParamType(D, I);
1468 if (T->isDependentType() || S.isValidPointerAttrType(T))
1473 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1476 unsigned *Start = NonNullArgs.data();
1477 unsigned Size = NonNullArgs.size();
1478 llvm::array_pod_sort(Start, Start + Size);
1479 D->addAttr(::new (S.Context)
1480 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1481 Attr.getAttributeSpellingListIndex()));
1484 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1485 const AttributeList &Attr) {
1486 if (Attr.getNumArgs() > 0) {
1487 if (D->getFunctionType()) {
1488 handleNonNullAttr(S, D, Attr);
1490 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1491 << D->getSourceRange();
1496 // Is the argument a pointer type?
1497 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1498 D->getSourceRange()))
1501 D->addAttr(::new (S.Context)
1502 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1503 Attr.getAttributeSpellingListIndex()));
1506 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1507 const AttributeList &Attr) {
1508 QualType ResultType = getFunctionOrMethodResultType(D);
1509 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1510 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1511 /* isReturnValue */ true))
1514 D->addAttr(::new (S.Context)
1515 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1516 Attr.getAttributeSpellingListIndex()));
1519 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1520 const AttributeList &Attr) {
1521 Expr *E = Attr.getArgAsExpr(0),
1522 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1523 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1524 Attr.getAttributeSpellingListIndex());
1527 static void handleAllocAlignAttr(Sema &S, Decl *D,
1528 const AttributeList &Attr) {
1529 S.AddAllocAlignAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
1530 Attr.getAttributeSpellingListIndex());
1533 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1534 Expr *OE, unsigned SpellingListIndex) {
1535 QualType ResultType = getFunctionOrMethodResultType(D);
1536 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1538 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1539 SourceLocation AttrLoc = AttrRange.getBegin();
1541 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1542 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1543 << &TmpAttr << AttrRange << SR;
1547 if (!E->isValueDependent()) {
1549 if (!E->isIntegerConstantExpr(I, Context)) {
1551 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1552 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1553 << E->getSourceRange();
1555 Diag(AttrLoc, diag::err_attribute_argument_type)
1556 << &TmpAttr << AANT_ArgumentIntegerConstant
1557 << E->getSourceRange();
1561 if (!I.isPowerOf2()) {
1562 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1563 << E->getSourceRange();
1569 if (!OE->isValueDependent()) {
1571 if (!OE->isIntegerConstantExpr(I, Context)) {
1572 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1573 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1574 << OE->getSourceRange();
1580 D->addAttr(::new (Context)
1581 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1584 void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1585 unsigned SpellingListIndex) {
1586 QualType ResultType = getFunctionOrMethodResultType(D);
1588 AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex);
1589 SourceLocation AttrLoc = AttrRange.getBegin();
1591 if (!ResultType->isDependentType() &&
1592 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1593 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1594 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1599 const auto *FuncDecl = cast<FunctionDecl>(D);
1600 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1601 /*AttrArgNo=*/1, ParamExpr,
1605 QualType Ty = getFunctionOrMethodParamType(D, IndexVal);
1606 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1607 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only)
1608 << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange();
1612 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
1613 // because that has corrected for the implicit this parameter, and is zero-
1614 // based. The attribute expects what the user wrote explicitly.
1616 ParamExpr->EvaluateAsInt(Val, Context);
1618 D->addAttr(::new (Context) AllocAlignAttr(
1619 AttrRange, Context, Val.getZExtValue(), SpellingListIndex));
1622 /// Normalize the attribute, __foo__ becomes foo.
1623 /// Returns true if normalization was applied.
1624 static bool normalizeName(StringRef &AttrName) {
1625 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1626 AttrName.endswith("__")) {
1627 AttrName = AttrName.drop_front(2).drop_back(2);
1633 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1634 // This attribute must be applied to a function declaration. The first
1635 // argument to the attribute must be an identifier, the name of the resource,
1636 // for example: malloc. The following arguments must be argument indexes, the
1637 // arguments must be of integer type for Returns, otherwise of pointer type.
1638 // The difference between Holds and Takes is that a pointer may still be used
1639 // after being held. free() should be __attribute((ownership_takes)), whereas
1640 // a list append function may well be __attribute((ownership_holds)).
1642 if (!AL.isArgIdent(0)) {
1643 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1644 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1648 // Figure out our Kind.
1649 OwnershipAttr::OwnershipKind K =
1650 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1651 AL.getAttributeSpellingListIndex()).getOwnKind();
1655 case OwnershipAttr::Takes:
1656 case OwnershipAttr::Holds:
1657 if (AL.getNumArgs() < 2) {
1658 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1659 << AL.getName() << 2;
1663 case OwnershipAttr::Returns:
1664 if (AL.getNumArgs() > 2) {
1665 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1666 << AL.getName() << 1;
1672 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1674 StringRef ModuleName = Module->getName();
1675 if (normalizeName(ModuleName)) {
1676 Module = &S.PP.getIdentifierTable().get(ModuleName);
1679 SmallVector<unsigned, 8> OwnershipArgs;
1680 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1681 Expr *Ex = AL.getArgAsExpr(i);
1683 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1686 // Is the function argument a pointer type?
1687 QualType T = getFunctionOrMethodParamType(D, Idx);
1688 int Err = -1; // No error
1690 case OwnershipAttr::Takes:
1691 case OwnershipAttr::Holds:
1692 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1695 case OwnershipAttr::Returns:
1696 if (!T->isIntegerType())
1701 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1702 << Ex->getSourceRange();
1706 // Check we don't have a conflict with another ownership attribute.
1707 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1708 // Cannot have two ownership attributes of different kinds for the same
1710 if (I->getOwnKind() != K && I->args_end() !=
1711 std::find(I->args_begin(), I->args_end(), Idx)) {
1712 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1713 << AL.getName() << I;
1715 } else if (K == OwnershipAttr::Returns &&
1716 I->getOwnKind() == OwnershipAttr::Returns) {
1717 // A returns attribute conflicts with any other returns attribute using
1718 // a different index. Note, diagnostic reporting is 1-based, but stored
1719 // argument indexes are 0-based.
1720 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1721 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1722 << *(I->args_begin()) + 1;
1724 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1725 << (unsigned)Idx + 1 << Ex->getSourceRange();
1730 OwnershipArgs.push_back(Idx);
1733 unsigned* start = OwnershipArgs.data();
1734 unsigned size = OwnershipArgs.size();
1735 llvm::array_pod_sort(start, start + size);
1737 D->addAttr(::new (S.Context)
1738 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1739 AL.getAttributeSpellingListIndex()));
1742 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1743 // Check the attribute arguments.
1744 if (Attr.getNumArgs() > 1) {
1745 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1746 << Attr.getName() << 1;
1750 NamedDecl *nd = cast<NamedDecl>(D);
1754 // static int a __attribute__((weakref ("v2")));
1755 // static int b() __attribute__((weakref ("f3")));
1757 // and ignores the attributes of
1759 // static int a __attribute__((weakref ("v2")));
1762 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1763 if (!Ctx->isFileContext()) {
1764 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1769 // The GCC manual says
1771 // At present, a declaration to which `weakref' is attached can only
1776 // Without a TARGET,
1777 // given as an argument to `weakref' or to `alias', `weakref' is
1778 // equivalent to `weak'.
1780 // gcc 4.4.1 will accept
1781 // int a7 __attribute__((weakref));
1783 // int a7 __attribute__((weak));
1784 // This looks like a bug in gcc. We reject that for now. We should revisit
1785 // it if this behaviour is actually used.
1788 // static ((alias ("y"), weakref)).
1789 // Should we? How to check that weakref is before or after alias?
1791 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1792 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1793 // StringRef parameter it was given anyway.
1795 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1796 // GCC will accept anything as the argument of weakref. Should we
1797 // check for an existing decl?
1798 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1799 Attr.getAttributeSpellingListIndex()));
1801 D->addAttr(::new (S.Context)
1802 WeakRefAttr(Attr.getRange(), S.Context,
1803 Attr.getAttributeSpellingListIndex()));
1806 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1808 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1811 // Aliases should be on declarations, not definitions.
1812 const auto *FD = cast<FunctionDecl>(D);
1813 if (FD->isThisDeclarationADefinition()) {
1814 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1817 // FIXME: it should be handled as a target specific attribute.
1818 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1819 llvm::Triple::ELF) {
1820 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1824 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1825 Attr.getAttributeSpellingListIndex()));
1828 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1830 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1833 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1834 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1837 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1838 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1841 // Aliases should be on declarations, not definitions.
1842 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1843 if (FD->isThisDeclarationADefinition()) {
1844 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
1848 const auto *VD = cast<VarDecl>(D);
1849 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1850 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
1855 // FIXME: check if target symbol exists in current file
1857 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1858 Attr.getAttributeSpellingListIndex()));
1861 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1862 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1865 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1866 Attr.getAttributeSpellingListIndex()));
1869 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1870 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1873 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1874 Attr.getAttributeSpellingListIndex()));
1877 static void handleTLSModelAttr(Sema &S, Decl *D,
1878 const AttributeList &Attr) {
1880 SourceLocation LiteralLoc;
1881 // Check that it is a string.
1882 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1885 // Check that the value.
1886 if (Model != "global-dynamic" && Model != "local-dynamic"
1887 && Model != "initial-exec" && Model != "local-exec") {
1888 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1892 D->addAttr(::new (S.Context)
1893 TLSModelAttr(Attr.getRange(), S.Context, Model,
1894 Attr.getAttributeSpellingListIndex()));
1897 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1898 QualType ResultType = getFunctionOrMethodResultType(D);
1899 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1900 D->addAttr(::new (S.Context) RestrictAttr(
1901 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1905 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1906 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1909 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1910 if (S.LangOpts.CPlusPlus) {
1911 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1912 << Attr.getName() << AttributeLangSupport::Cpp;
1916 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1917 Attr.getAttributeSpellingListIndex()))
1921 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1922 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1926 if (Attr.isDeclspecAttribute()) {
1927 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1928 const auto &Arch = Triple.getArch();
1929 if (Arch != llvm::Triple::x86 &&
1930 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1931 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_on_arch)
1932 << Attr.getName() << Triple.getArchName();
1937 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1938 Attr.getAttributeSpellingListIndex()));
1941 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1942 if (hasDeclarator(D)) return;
1944 if (S.CheckNoReturnAttr(attr)) return;
1946 if (!isa<ObjCMethodDecl>(D)) {
1947 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1948 << attr.getName() << ExpectedFunctionOrMethod;
1952 D->addAttr(::new (S.Context)
1953 NoReturnAttr(attr.getRange(), S.Context,
1954 attr.getAttributeSpellingListIndex()));
1957 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1958 if (!checkAttributeNumArgs(*this, attr, 0)) {
1966 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1967 const AttributeList &Attr) {
1969 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1970 // because 'analyzer_noreturn' does not impact the type.
1971 if (!isFunctionOrMethodOrBlock(D)) {
1972 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1973 if (!VD || (!VD->getType()->isBlockPointerType() &&
1974 !VD->getType()->isFunctionPointerType())) {
1975 S.Diag(Attr.getLoc(),
1976 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1977 : diag::warn_attribute_wrong_decl_type)
1978 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1983 D->addAttr(::new (S.Context)
1984 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1985 Attr.getAttributeSpellingListIndex()));
1988 // PS3 PPU-specific.
1989 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1991 Returning a Vector Class in Registers
1993 According to the PPU ABI specifications, a class with a single member of
1994 vector type is returned in memory when used as the return value of a function.
1995 This results in inefficient code when implementing vector classes. To return
1996 the value in a single vector register, add the vecreturn attribute to the
1997 class definition. This attribute is also applicable to struct types.
2003 __vector float xyzw;
2004 } __attribute__((vecreturn));
2006 Vector Add(Vector lhs, Vector rhs)
2009 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2010 return result; // This will be returned in a register
2013 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2014 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
2018 RecordDecl *record = cast<RecordDecl>(D);
2021 if (!isa<CXXRecordDecl>(record)) {
2022 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2026 if (!cast<CXXRecordDecl>(record)->isPOD()) {
2027 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2031 for (const auto *I : record->fields()) {
2032 if ((count == 1) || !I->getType()->isVectorType()) {
2033 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2039 D->addAttr(::new (S.Context)
2040 VecReturnAttr(Attr.getRange(), S.Context,
2041 Attr.getAttributeSpellingListIndex()));
2044 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2045 const AttributeList &Attr) {
2046 if (isa<ParmVarDecl>(D)) {
2047 // [[carries_dependency]] can only be applied to a parameter if it is a
2048 // parameter of a function declaration or lambda.
2049 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2050 S.Diag(Attr.getLoc(),
2051 diag::err_carries_dependency_param_not_function_decl);
2056 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2057 Attr.getRange(), S.Context,
2058 Attr.getAttributeSpellingListIndex()));
2061 static void handleNotTailCalledAttr(Sema &S, Decl *D,
2062 const AttributeList &Attr) {
2063 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
2067 D->addAttr(::new (S.Context) NotTailCalledAttr(
2068 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2071 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
2072 const AttributeList &Attr) {
2073 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
2077 D->addAttr(::new (S.Context) DisableTailCallsAttr(
2078 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2081 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2082 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2083 if (VD->hasLocalStorage()) {
2084 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2087 } else if (!isFunctionOrMethod(D)) {
2088 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2089 << Attr.getName() << ExpectedVariableOrFunction;
2093 D->addAttr(::new (S.Context)
2094 UsedAttr(Attr.getRange(), S.Context,
2095 Attr.getAttributeSpellingListIndex()));
2098 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2099 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2101 if (IsCXX1zAttr && isa<VarDecl>(D)) {
2102 // The C++1z spelling of this attribute cannot be applied to a static data
2103 // member per [dcl.attr.unused]p2.
2104 if (cast<VarDecl>(D)->isStaticDataMember()) {
2105 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2106 << Attr.getName() << ExpectedForMaybeUnused;
2111 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2112 // about using it as an extension.
2113 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
2114 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2116 D->addAttr(::new (S.Context) UnusedAttr(
2117 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2120 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2121 uint32_t priority = ConstructorAttr::DefaultPriority;
2122 if (Attr.getNumArgs() &&
2123 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2126 D->addAttr(::new (S.Context)
2127 ConstructorAttr(Attr.getRange(), S.Context, priority,
2128 Attr.getAttributeSpellingListIndex()));
2131 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2132 uint32_t priority = DestructorAttr::DefaultPriority;
2133 if (Attr.getNumArgs() &&
2134 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2137 D->addAttr(::new (S.Context)
2138 DestructorAttr(Attr.getRange(), S.Context, priority,
2139 Attr.getAttributeSpellingListIndex()));
2142 template <typename AttrTy>
2143 static void handleAttrWithMessage(Sema &S, Decl *D,
2144 const AttributeList &Attr) {
2145 // Handle the case where the attribute has a text message.
2147 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2150 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2151 Attr.getAttributeSpellingListIndex()));
2154 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2155 const AttributeList &Attr) {
2156 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2157 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2158 << Attr.getName() << Attr.getRange();
2162 D->addAttr(::new (S.Context)
2163 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2164 Attr.getAttributeSpellingListIndex()));
2167 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2168 IdentifierInfo *Platform,
2169 VersionTuple Introduced,
2170 VersionTuple Deprecated,
2171 VersionTuple Obsoleted) {
2172 StringRef PlatformName
2173 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2174 if (PlatformName.empty())
2175 PlatformName = Platform->getName();
2177 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2178 // of these steps are needed).
2179 if (!Introduced.empty() && !Deprecated.empty() &&
2180 !(Introduced <= Deprecated)) {
2181 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2182 << 1 << PlatformName << Deprecated.getAsString()
2183 << 0 << Introduced.getAsString();
2187 if (!Introduced.empty() && !Obsoleted.empty() &&
2188 !(Introduced <= Obsoleted)) {
2189 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2190 << 2 << PlatformName << Obsoleted.getAsString()
2191 << 0 << Introduced.getAsString();
2195 if (!Deprecated.empty() && !Obsoleted.empty() &&
2196 !(Deprecated <= Obsoleted)) {
2197 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2198 << 2 << PlatformName << Obsoleted.getAsString()
2199 << 1 << Deprecated.getAsString();
2206 /// \brief Check whether the two versions match.
2208 /// If either version tuple is empty, then they are assumed to match. If
2209 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2210 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2211 bool BeforeIsOkay) {
2212 if (X.empty() || Y.empty())
2218 if (BeforeIsOkay && X < Y)
2224 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2225 IdentifierInfo *Platform,
2227 VersionTuple Introduced,
2228 VersionTuple Deprecated,
2229 VersionTuple Obsoleted,
2233 StringRef Replacement,
2234 AvailabilityMergeKind AMK,
2235 unsigned AttrSpellingListIndex) {
2236 VersionTuple MergedIntroduced = Introduced;
2237 VersionTuple MergedDeprecated = Deprecated;
2238 VersionTuple MergedObsoleted = Obsoleted;
2239 bool FoundAny = false;
2240 bool OverrideOrImpl = false;
2243 case AMK_Redeclaration:
2244 OverrideOrImpl = false;
2248 case AMK_ProtocolImplementation:
2249 OverrideOrImpl = true;
2253 if (D->hasAttrs()) {
2254 AttrVec &Attrs = D->getAttrs();
2255 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2256 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2262 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2263 if (OldPlatform != Platform) {
2268 // If there is an existing availability attribute for this platform that
2269 // is explicit and the new one is implicit use the explicit one and
2270 // discard the new implicit attribute.
2271 if (!OldAA->isImplicit() && Implicit) {
2275 // If there is an existing attribute for this platform that is implicit
2276 // and the new attribute is explicit then erase the old one and
2277 // continue processing the attributes.
2278 if (!Implicit && OldAA->isImplicit()) {
2279 Attrs.erase(Attrs.begin() + i);
2285 VersionTuple OldIntroduced = OldAA->getIntroduced();
2286 VersionTuple OldDeprecated = OldAA->getDeprecated();
2287 VersionTuple OldObsoleted = OldAA->getObsoleted();
2288 bool OldIsUnavailable = OldAA->getUnavailable();
2290 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2291 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2292 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2293 !(OldIsUnavailable == IsUnavailable ||
2294 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2295 if (OverrideOrImpl) {
2297 VersionTuple FirstVersion;
2298 VersionTuple SecondVersion;
2299 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2301 FirstVersion = OldIntroduced;
2302 SecondVersion = Introduced;
2303 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2305 FirstVersion = Deprecated;
2306 SecondVersion = OldDeprecated;
2307 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2309 FirstVersion = Obsoleted;
2310 SecondVersion = OldObsoleted;
2314 Diag(OldAA->getLocation(),
2315 diag::warn_mismatched_availability_override_unavail)
2316 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2317 << (AMK == AMK_Override);
2319 Diag(OldAA->getLocation(),
2320 diag::warn_mismatched_availability_override)
2322 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2323 << FirstVersion.getAsString() << SecondVersion.getAsString()
2324 << (AMK == AMK_Override);
2326 if (AMK == AMK_Override)
2327 Diag(Range.getBegin(), diag::note_overridden_method);
2329 Diag(Range.getBegin(), diag::note_protocol_method);
2331 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2332 Diag(Range.getBegin(), diag::note_previous_attribute);
2335 Attrs.erase(Attrs.begin() + i);
2340 VersionTuple MergedIntroduced2 = MergedIntroduced;
2341 VersionTuple MergedDeprecated2 = MergedDeprecated;
2342 VersionTuple MergedObsoleted2 = MergedObsoleted;
2344 if (MergedIntroduced2.empty())
2345 MergedIntroduced2 = OldIntroduced;
2346 if (MergedDeprecated2.empty())
2347 MergedDeprecated2 = OldDeprecated;
2348 if (MergedObsoleted2.empty())
2349 MergedObsoleted2 = OldObsoleted;
2351 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2352 MergedIntroduced2, MergedDeprecated2,
2353 MergedObsoleted2)) {
2354 Attrs.erase(Attrs.begin() + i);
2359 MergedIntroduced = MergedIntroduced2;
2360 MergedDeprecated = MergedDeprecated2;
2361 MergedObsoleted = MergedObsoleted2;
2367 MergedIntroduced == Introduced &&
2368 MergedDeprecated == Deprecated &&
2369 MergedObsoleted == Obsoleted)
2372 // Only create a new attribute if !OverrideOrImpl, but we want to do
2374 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2375 MergedDeprecated, MergedObsoleted) &&
2377 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2378 Introduced, Deprecated,
2379 Obsoleted, IsUnavailable, Message,
2380 IsStrict, Replacement,
2381 AttrSpellingListIndex);
2382 Avail->setImplicit(Implicit);
2388 static void handleAvailabilityAttr(Sema &S, Decl *D,
2389 const AttributeList &Attr) {
2390 if (!checkAttributeNumArgs(S, Attr, 1))
2392 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2393 unsigned Index = Attr.getAttributeSpellingListIndex();
2395 IdentifierInfo *II = Platform->Ident;
2396 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2397 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2400 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2402 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2406 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2407 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2408 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2409 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2410 bool IsStrict = Attr.getStrictLoc().isValid();
2412 if (const StringLiteral *SE =
2413 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2414 Str = SE->getString();
2415 StringRef Replacement;
2416 if (const StringLiteral *SE =
2417 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2418 Replacement = SE->getString();
2420 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2426 IsStrict, Replacement,
2430 D->addAttr(NewAttr);
2432 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2433 // matches before the start of the watchOS platform.
2434 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2435 IdentifierInfo *NewII = nullptr;
2436 if (II->getName() == "ios")
2437 NewII = &S.Context.Idents.get("watchos");
2438 else if (II->getName() == "ios_app_extension")
2439 NewII = &S.Context.Idents.get("watchos_app_extension");
2442 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2443 if (Version.empty())
2445 auto Major = Version.getMajor();
2446 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2447 if (NewMajor >= 2) {
2448 if (Version.getMinor().hasValue()) {
2449 if (Version.getSubminor().hasValue())
2450 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2451 Version.getSubminor().getValue());
2453 return VersionTuple(NewMajor, Version.getMinor().getValue());
2457 return VersionTuple(2, 0);
2460 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2461 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2462 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2464 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2477 D->addAttr(NewAttr);
2479 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2480 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2481 // matches before the start of the tvOS platform.
2482 IdentifierInfo *NewII = nullptr;
2483 if (II->getName() == "ios")
2484 NewII = &S.Context.Idents.get("tvos");
2485 else if (II->getName() == "ios_app_extension")
2486 NewII = &S.Context.Idents.get("tvos_app_extension");
2489 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2502 D->addAttr(NewAttr);
2507 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2508 const AttributeList &Attr) {
2509 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2511 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2512 "Invalid number of arguments in an external_source_symbol attribute");
2514 if (!isa<NamedDecl>(D)) {
2515 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2516 << Attr.getName() << ExpectedNamedDecl;
2521 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2522 Language = SE->getString();
2523 StringRef DefinedIn;
2524 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2525 DefinedIn = SE->getString();
2526 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2528 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2529 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2530 Attr.getAttributeSpellingListIndex()));
2534 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2535 typename T::VisibilityType value,
2536 unsigned attrSpellingListIndex) {
2537 T *existingAttr = D->getAttr<T>();
2539 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2540 if (existingValue == value)
2542 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2543 S.Diag(range.getBegin(), diag::note_previous_attribute);
2546 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2549 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2550 VisibilityAttr::VisibilityType Vis,
2551 unsigned AttrSpellingListIndex) {
2552 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2553 AttrSpellingListIndex);
2556 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2557 TypeVisibilityAttr::VisibilityType Vis,
2558 unsigned AttrSpellingListIndex) {
2559 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2560 AttrSpellingListIndex);
2563 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2564 bool isTypeVisibility) {
2565 // Visibility attributes don't mean anything on a typedef.
2566 if (isa<TypedefNameDecl>(D)) {
2567 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2572 // 'type_visibility' can only go on a type or namespace.
2573 if (isTypeVisibility &&
2574 !(isa<TagDecl>(D) ||
2575 isa<ObjCInterfaceDecl>(D) ||
2576 isa<NamespaceDecl>(D))) {
2577 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2578 << Attr.getName() << ExpectedTypeOrNamespace;
2582 // Check that the argument is a string literal.
2584 SourceLocation LiteralLoc;
2585 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2588 VisibilityAttr::VisibilityType type;
2589 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2590 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2591 << Attr.getName() << TypeStr;
2595 // Complain about attempts to use protected visibility on targets
2596 // (like Darwin) that don't support it.
2597 if (type == VisibilityAttr::Protected &&
2598 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2599 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2600 type = VisibilityAttr::Default;
2603 unsigned Index = Attr.getAttributeSpellingListIndex();
2604 clang::Attr *newAttr;
2605 if (isTypeVisibility) {
2606 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2607 (TypeVisibilityAttr::VisibilityType) type,
2610 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2613 D->addAttr(newAttr);
2616 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2617 const AttributeList &Attr) {
2618 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2619 if (!Attr.isArgIdent(0)) {
2620 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2621 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2625 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2626 ObjCMethodFamilyAttr::FamilyKind F;
2627 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2628 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2633 if (F == ObjCMethodFamilyAttr::OMF_init &&
2634 !method->getReturnType()->isObjCObjectPointerType()) {
2635 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2636 << method->getReturnType();
2637 // Ignore the attribute.
2641 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2643 Attr.getAttributeSpellingListIndex()));
2646 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2647 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2648 QualType T = TD->getUnderlyingType();
2649 if (!T->isCARCBridgableType()) {
2650 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2654 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2655 QualType T = PD->getType();
2656 if (!T->isCARCBridgableType()) {
2657 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2662 // It is okay to include this attribute on properties, e.g.:
2664 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2666 // In this case it follows tradition and suppresses an error in the above
2668 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2670 D->addAttr(::new (S.Context)
2671 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2672 Attr.getAttributeSpellingListIndex()));
2675 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2676 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2677 QualType T = TD->getUnderlyingType();
2678 if (!T->isObjCObjectPointerType()) {
2679 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2683 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2686 D->addAttr(::new (S.Context)
2687 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2688 Attr.getAttributeSpellingListIndex()));
2691 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2692 if (!Attr.isArgIdent(0)) {
2693 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2694 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2698 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2699 BlocksAttr::BlockType type;
2700 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2701 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2702 << Attr.getName() << II;
2706 D->addAttr(::new (S.Context)
2707 BlocksAttr(Attr.getRange(), S.Context, type,
2708 Attr.getAttributeSpellingListIndex()));
2711 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2712 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2713 if (Attr.getNumArgs() > 0) {
2714 Expr *E = Attr.getArgAsExpr(0);
2715 llvm::APSInt Idx(32);
2716 if (E->isTypeDependent() || E->isValueDependent() ||
2717 !E->isIntegerConstantExpr(Idx, S.Context)) {
2718 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2719 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2720 << E->getSourceRange();
2724 if (Idx.isSigned() && Idx.isNegative()) {
2725 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2726 << E->getSourceRange();
2730 sentinel = Idx.getZExtValue();
2733 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2734 if (Attr.getNumArgs() > 1) {
2735 Expr *E = Attr.getArgAsExpr(1);
2736 llvm::APSInt Idx(32);
2737 if (E->isTypeDependent() || E->isValueDependent() ||
2738 !E->isIntegerConstantExpr(Idx, S.Context)) {
2739 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2740 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2741 << E->getSourceRange();
2744 nullPos = Idx.getZExtValue();
2746 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2747 // FIXME: This error message could be improved, it would be nice
2748 // to say what the bounds actually are.
2749 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2750 << E->getSourceRange();
2755 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2756 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2757 if (isa<FunctionNoProtoType>(FT)) {
2758 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2762 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2763 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2766 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2767 if (!MD->isVariadic()) {
2768 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2771 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2772 if (!BD->isVariadic()) {
2773 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2776 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2777 QualType Ty = V->getType();
2778 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2779 const FunctionType *FT = Ty->isFunctionPointerType()
2780 ? D->getFunctionType()
2781 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2782 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2783 int m = Ty->isFunctionPointerType() ? 0 : 1;
2784 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2788 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2789 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2793 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2794 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2797 D->addAttr(::new (S.Context)
2798 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2799 Attr.getAttributeSpellingListIndex()));
2802 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2803 if (D->getFunctionType() &&
2804 D->getFunctionType()->getReturnType()->isVoidType()) {
2805 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2806 << Attr.getName() << 0;
2809 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2810 if (MD->getReturnType()->isVoidType()) {
2811 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2812 << Attr.getName() << 1;
2816 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2817 // about using it as an extension.
2818 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2819 !Attr.getScopeName())
2820 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2822 D->addAttr(::new (S.Context)
2823 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2824 Attr.getAttributeSpellingListIndex()));
2827 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2828 // weak_import only applies to variable & function declarations.
2830 if (!D->canBeWeakImported(isDef)) {
2832 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2834 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2835 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2836 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2837 // Nothing to warn about here.
2839 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2840 << Attr.getName() << ExpectedVariableOrFunction;
2845 D->addAttr(::new (S.Context)
2846 WeakImportAttr(Attr.getRange(), S.Context,
2847 Attr.getAttributeSpellingListIndex()));
2850 // Handles reqd_work_group_size and work_group_size_hint.
2851 template <typename WorkGroupAttr>
2852 static void handleWorkGroupSize(Sema &S, Decl *D,
2853 const AttributeList &Attr) {
2855 for (unsigned i = 0; i < 3; ++i) {
2856 const Expr *E = Attr.getArgAsExpr(i);
2857 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2859 if (WGSize[i] == 0) {
2860 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2861 << Attr.getName() << E->getSourceRange();
2866 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2867 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2868 Existing->getYDim() == WGSize[1] &&
2869 Existing->getZDim() == WGSize[2]))
2870 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2872 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2873 WGSize[0], WGSize[1], WGSize[2],
2874 Attr.getAttributeSpellingListIndex()));
2877 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2878 if (!Attr.hasParsedType()) {
2879 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2880 << Attr.getName() << 1;
2884 TypeSourceInfo *ParmTSI = nullptr;
2885 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2886 assert(ParmTSI && "no type source info for attribute argument");
2888 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2889 (ParmType->isBooleanType() ||
2890 !ParmType->isIntegralType(S.getASTContext()))) {
2891 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2896 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2897 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2898 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2903 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2905 Attr.getAttributeSpellingListIndex()));
2908 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2910 unsigned AttrSpellingListIndex) {
2911 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2912 if (ExistingAttr->getName() == Name)
2914 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2915 Diag(Range.getBegin(), diag::note_previous_attribute);
2918 return ::new (Context) SectionAttr(Range, Context, Name,
2919 AttrSpellingListIndex);
2922 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2923 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2924 if (!Error.empty()) {
2925 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2931 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2932 // Make sure that there is a string literal as the sections's single
2935 SourceLocation LiteralLoc;
2936 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2939 if (!S.checkSectionName(LiteralLoc, Str))
2942 // If the target wants to validate the section specifier, make it happen.
2943 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2944 if (!Error.empty()) {
2945 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2950 unsigned Index = Attr.getAttributeSpellingListIndex();
2951 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2953 D->addAttr(NewAttr);
2956 // Check for things we'd like to warn about, no errors or validation for now.
2957 // TODO: Validation should use a backend target library that specifies
2958 // the allowable subtarget features and cpus. We could use something like a
2959 // TargetCodeGenInfo hook here to do validation.
2960 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2961 for (auto Str : {"tune=", "fpmath="})
2962 if (AttrStr.find(Str) != StringRef::npos)
2963 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2966 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2968 SourceLocation LiteralLoc;
2969 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2971 S.checkTargetAttr(LiteralLoc, Str);
2972 unsigned Index = Attr.getAttributeSpellingListIndex();
2973 TargetAttr *NewAttr =
2974 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2975 D->addAttr(NewAttr);
2978 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2979 VarDecl *VD = cast<VarDecl>(D);
2980 if (!VD->hasLocalStorage()) {
2981 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2985 Expr *E = Attr.getArgAsExpr(0);
2986 SourceLocation Loc = E->getExprLoc();
2987 FunctionDecl *FD = nullptr;
2988 DeclarationNameInfo NI;
2990 // gcc only allows for simple identifiers. Since we support more than gcc, we
2991 // will warn the user.
2992 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2993 if (DRE->hasQualifier())
2994 S.Diag(Loc, diag::warn_cleanup_ext);
2995 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2996 NI = DRE->getNameInfo();
2998 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3002 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3003 if (ULE->hasExplicitTemplateArgs())
3004 S.Diag(Loc, diag::warn_cleanup_ext);
3005 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3006 NI = ULE->getNameInfo();
3008 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3010 if (ULE->getType() == S.Context.OverloadTy)
3011 S.NoteAllOverloadCandidates(ULE);
3015 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3019 if (FD->getNumParams() != 1) {
3020 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3025 // We're currently more strict than GCC about what function types we accept.
3026 // If this ever proves to be a problem it should be easy to fix.
3027 QualType Ty = S.Context.getPointerType(VD->getType());
3028 QualType ParamTy = FD->getParamDecl(0)->getType();
3029 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3030 ParamTy, Ty) != Sema::Compatible) {
3031 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3032 << NI.getName() << ParamTy << Ty;
3036 D->addAttr(::new (S.Context)
3037 CleanupAttr(Attr.getRange(), S.Context, FD,
3038 Attr.getAttributeSpellingListIndex()));
3041 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3042 const AttributeList &Attr) {
3043 if (!Attr.isArgIdent(0)) {
3044 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3045 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3049 EnumExtensibilityAttr::Kind ExtensibilityKind;
3050 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3051 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3052 ExtensibilityKind)) {
3053 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3054 << Attr.getName() << II;
3058 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3059 Attr.getRange(), S.Context, ExtensibilityKind,
3060 Attr.getAttributeSpellingListIndex()));
3063 /// Handle __attribute__((format_arg((idx)))) attribute based on
3064 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3065 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3066 Expr *IdxExpr = Attr.getArgAsExpr(0);
3068 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
3071 // Make sure the format string is really a string.
3072 QualType Ty = getFunctionOrMethodParamType(D, Idx);
3074 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3075 if (NotNSStringTy &&
3076 !isCFStringType(Ty, S.Context) &&
3077 (!Ty->isPointerType() ||
3078 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3079 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3080 << "a string type" << IdxExpr->getSourceRange()
3081 << getFunctionOrMethodParamRange(D, 0);
3084 Ty = getFunctionOrMethodResultType(D);
3085 if (!isNSStringType(Ty, S.Context) &&
3086 !isCFStringType(Ty, S.Context) &&
3087 (!Ty->isPointerType() ||
3088 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3089 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
3090 << (NotNSStringTy ? "string type" : "NSString")
3091 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3095 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
3096 // because that has corrected for the implicit this parameter, and is zero-
3097 // based. The attribute expects what the user wrote explicitly.
3099 IdxExpr->EvaluateAsInt(Val, S.Context);
3101 D->addAttr(::new (S.Context)
3102 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
3103 Attr.getAttributeSpellingListIndex()));
3106 enum FormatAttrKind {
3115 /// getFormatAttrKind - Map from format attribute names to supported format
3117 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3118 return llvm::StringSwitch<FormatAttrKind>(Format)
3119 // Check for formats that get handled specially.
3120 .Case("NSString", NSStringFormat)
3121 .Case("CFString", CFStringFormat)
3122 .Case("strftime", StrftimeFormat)
3124 // Otherwise, check for supported formats.
3125 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3126 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3127 .Case("kprintf", SupportedFormat) // OpenBSD.
3128 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3129 .Case("os_trace", SupportedFormat)
3130 .Case("os_log", SupportedFormat)
3132 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3133 .Default(InvalidFormat);
3136 /// Handle __attribute__((init_priority(priority))) attributes based on
3137 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3138 static void handleInitPriorityAttr(Sema &S, Decl *D,
3139 const AttributeList &Attr) {
3140 if (!S.getLangOpts().CPlusPlus) {
3141 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3145 if (S.getCurFunctionOrMethodDecl()) {
3146 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3150 QualType T = cast<VarDecl>(D)->getType();
3151 if (S.Context.getAsArrayType(T))
3152 T = S.Context.getBaseElementType(T);
3153 if (!T->getAs<RecordType>()) {
3154 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3159 Expr *E = Attr.getArgAsExpr(0);
3160 uint32_t prioritynum;
3161 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
3166 if (prioritynum < 101 || prioritynum > 65535) {
3167 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3168 << E->getSourceRange() << Attr.getName() << 101 << 65535;
3172 D->addAttr(::new (S.Context)
3173 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3174 Attr.getAttributeSpellingListIndex()));
3177 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3178 IdentifierInfo *Format, int FormatIdx,
3180 unsigned AttrSpellingListIndex) {
3181 // Check whether we already have an equivalent format attribute.
3182 for (auto *F : D->specific_attrs<FormatAttr>()) {
3183 if (F->getType() == Format &&
3184 F->getFormatIdx() == FormatIdx &&
3185 F->getFirstArg() == FirstArg) {
3186 // If we don't have a valid location for this attribute, adopt the
3188 if (F->getLocation().isInvalid())
3194 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3195 FirstArg, AttrSpellingListIndex);
3198 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3199 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3200 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3201 if (!Attr.isArgIdent(0)) {
3202 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3203 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3207 // In C++ the implicit 'this' function parameter also counts, and they are
3208 // counted from one.
3209 bool HasImplicitThisParam = isInstanceMethod(D);
3210 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3212 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3213 StringRef Format = II->getName();
3215 if (normalizeName(Format)) {
3216 // If we've modified the string name, we need a new identifier for it.
3217 II = &S.Context.Idents.get(Format);
3220 // Check for supported formats.
3221 FormatAttrKind Kind = getFormatAttrKind(Format);
3223 if (Kind == IgnoredFormat)
3226 if (Kind == InvalidFormat) {
3227 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3228 << Attr.getName() << II->getName();
3232 // checks for the 2nd argument
3233 Expr *IdxExpr = Attr.getArgAsExpr(1);
3235 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3238 if (Idx < 1 || Idx > NumArgs) {
3239 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3240 << Attr.getName() << 2 << IdxExpr->getSourceRange();
3244 // FIXME: Do we need to bounds check?
3245 unsigned ArgIdx = Idx - 1;
3247 if (HasImplicitThisParam) {
3249 S.Diag(Attr.getLoc(),
3250 diag::err_format_attribute_implicit_this_format_string)
3251 << IdxExpr->getSourceRange();
3257 // make sure the format string is really a string
3258 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3260 if (Kind == CFStringFormat) {
3261 if (!isCFStringType(Ty, S.Context)) {
3262 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3263 << "a CFString" << IdxExpr->getSourceRange()
3264 << getFunctionOrMethodParamRange(D, ArgIdx);
3267 } else if (Kind == NSStringFormat) {
3268 // FIXME: do we need to check if the type is NSString*? What are the
3270 if (!isNSStringType(Ty, S.Context)) {
3271 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3272 << "an NSString" << IdxExpr->getSourceRange()
3273 << getFunctionOrMethodParamRange(D, ArgIdx);
3276 } else if (!Ty->isPointerType() ||
3277 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3278 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3279 << "a string type" << IdxExpr->getSourceRange()
3280 << getFunctionOrMethodParamRange(D, ArgIdx);
3284 // check the 3rd argument
3285 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3287 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3290 // check if the function is variadic if the 3rd argument non-zero
3291 if (FirstArg != 0) {
3292 if (isFunctionOrMethodVariadic(D)) {
3293 ++NumArgs; // +1 for ...
3295 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3300 // strftime requires FirstArg to be 0 because it doesn't read from any
3301 // variable the input is just the current time + the format string.
3302 if (Kind == StrftimeFormat) {
3303 if (FirstArg != 0) {
3304 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3305 << FirstArgExpr->getSourceRange();
3308 // if 0 it disables parameter checking (to use with e.g. va_list)
3309 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3310 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3311 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3315 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3317 Attr.getAttributeSpellingListIndex());
3319 D->addAttr(NewAttr);
3322 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3323 const AttributeList &Attr) {
3324 // Try to find the underlying union declaration.
3325 RecordDecl *RD = nullptr;
3326 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3327 if (TD && TD->getUnderlyingType()->isUnionType())
3328 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3330 RD = dyn_cast<RecordDecl>(D);
3332 if (!RD || !RD->isUnion()) {
3333 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3334 << Attr.getName() << ExpectedUnion;
3338 if (!RD->isCompleteDefinition()) {
3339 if (!RD->isBeingDefined())
3340 S.Diag(Attr.getLoc(),
3341 diag::warn_transparent_union_attribute_not_definition);
3345 RecordDecl::field_iterator Field = RD->field_begin(),
3346 FieldEnd = RD->field_end();
3347 if (Field == FieldEnd) {
3348 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3352 FieldDecl *FirstField = *Field;
3353 QualType FirstType = FirstField->getType();
3354 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3355 S.Diag(FirstField->getLocation(),
3356 diag::warn_transparent_union_attribute_floating)
3357 << FirstType->isVectorType() << FirstType;
3361 if (FirstType->isIncompleteType())
3363 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3364 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3365 for (; Field != FieldEnd; ++Field) {
3366 QualType FieldType = Field->getType();
3367 if (FieldType->isIncompleteType())
3369 // FIXME: this isn't fully correct; we also need to test whether the
3370 // members of the union would all have the same calling convention as the
3371 // first member of the union. Checking just the size and alignment isn't
3372 // sufficient (consider structs passed on the stack instead of in registers
3374 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3375 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3376 // Warn if we drop the attribute.
3377 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3378 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3379 : S.Context.getTypeAlign(FieldType);
3380 S.Diag(Field->getLocation(),
3381 diag::warn_transparent_union_attribute_field_size_align)
3382 << isSize << Field->getDeclName() << FieldBits;
3383 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3384 S.Diag(FirstField->getLocation(),
3385 diag::note_transparent_union_first_field_size_align)
3386 << isSize << FirstBits;
3391 RD->addAttr(::new (S.Context)
3392 TransparentUnionAttr(Attr.getRange(), S.Context,
3393 Attr.getAttributeSpellingListIndex()));
3396 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3397 // Make sure that there is a string literal as the annotation's single
3400 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3403 // Don't duplicate annotations that are already set.
3404 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3405 if (I->getAnnotation() == Str)
3409 D->addAttr(::new (S.Context)
3410 AnnotateAttr(Attr.getRange(), S.Context, Str,
3411 Attr.getAttributeSpellingListIndex()));
3414 static void handleAlignValueAttr(Sema &S, Decl *D,
3415 const AttributeList &Attr) {
3416 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3417 Attr.getAttributeSpellingListIndex());
3420 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3421 unsigned SpellingListIndex) {
3422 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3423 SourceLocation AttrLoc = AttrRange.getBegin();
3426 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3427 T = TD->getUnderlyingType();
3428 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3431 llvm_unreachable("Unknown decl type for align_value");
3433 if (!T->isDependentType() && !T->isAnyPointerType() &&
3434 !T->isReferenceType() && !T->isMemberPointerType()) {
3435 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3436 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3440 if (!E->isValueDependent()) {
3441 llvm::APSInt Alignment;
3443 = VerifyIntegerConstantExpression(E, &Alignment,
3444 diag::err_align_value_attribute_argument_not_int,
3445 /*AllowFold*/ false);
3446 if (ICE.isInvalid())
3449 if (!Alignment.isPowerOf2()) {
3450 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3451 << E->getSourceRange();
3455 D->addAttr(::new (Context)
3456 AlignValueAttr(AttrRange, Context, ICE.get(),
3457 SpellingListIndex));
3461 // Save dependent expressions in the AST to be instantiated.
3462 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3465 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3466 // check the attribute arguments.
3467 if (Attr.getNumArgs() > 1) {
3468 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3469 << Attr.getName() << 1;
3473 if (Attr.getNumArgs() == 0) {
3474 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3475 true, nullptr, Attr.getAttributeSpellingListIndex()));
3479 Expr *E = Attr.getArgAsExpr(0);
3480 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3481 S.Diag(Attr.getEllipsisLoc(),
3482 diag::err_pack_expansion_without_parameter_packs);
3486 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3489 if (E->isValueDependent()) {
3490 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3491 if (!TND->getUnderlyingType()->isDependentType()) {
3492 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3493 << E->getSourceRange();
3499 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3500 Attr.isPackExpansion());
3503 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3504 unsigned SpellingListIndex, bool IsPackExpansion) {
3505 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3506 SourceLocation AttrLoc = AttrRange.getBegin();
3508 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3509 if (TmpAttr.isAlignas()) {
3510 // C++11 [dcl.align]p1:
3511 // An alignment-specifier may be applied to a variable or to a class
3512 // data member, but it shall not be applied to a bit-field, a function
3513 // parameter, the formal parameter of a catch clause, or a variable
3514 // declared with the register storage class specifier. An
3515 // alignment-specifier may also be applied to the declaration of a class
3516 // or enumeration type.
3518 // An alignment attribute shall not be specified in a declaration of
3519 // a typedef, or a bit-field, or a function, or a parameter, or an
3520 // object declared with the register storage-class specifier.
3522 if (isa<ParmVarDecl>(D)) {
3524 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3525 if (VD->getStorageClass() == SC_Register)
3527 if (VD->isExceptionVariable())
3529 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3530 if (FD->isBitField())
3532 } else if (!isa<TagDecl>(D)) {
3533 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3534 << (TmpAttr.isC11() ? ExpectedVariableOrField
3535 : ExpectedVariableFieldOrTag);
3538 if (DiagKind != -1) {
3539 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3540 << &TmpAttr << DiagKind;
3545 if (E->isTypeDependent() || E->isValueDependent()) {
3546 // Save dependent expressions in the AST to be instantiated.
3547 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3548 AA->setPackExpansion(IsPackExpansion);
3553 // FIXME: Cache the number on the Attr object?
3554 llvm::APSInt Alignment;
3556 = VerifyIntegerConstantExpression(E, &Alignment,
3557 diag::err_aligned_attribute_argument_not_int,
3558 /*AllowFold*/ false);
3559 if (ICE.isInvalid())
3562 uint64_t AlignVal = Alignment.getZExtValue();
3564 // C++11 [dcl.align]p2:
3565 // -- if the constant expression evaluates to zero, the alignment
3566 // specifier shall have no effect
3568 // An alignment specification of zero has no effect.
3569 if (!(TmpAttr.isAlignas() && !Alignment)) {
3570 if (!llvm::isPowerOf2_64(AlignVal)) {
3571 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3572 << E->getSourceRange();
3577 // Alignment calculations can wrap around if it's greater than 2**28.
3578 unsigned MaxValidAlignment =
3579 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3581 if (AlignVal > MaxValidAlignment) {
3582 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3583 << E->getSourceRange();
3587 if (Context.getTargetInfo().isTLSSupported()) {
3588 unsigned MaxTLSAlign =
3589 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3591 auto *VD = dyn_cast<VarDecl>(D);
3592 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3593 VD->getTLSKind() != VarDecl::TLS_None) {
3594 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3595 << (unsigned)AlignVal << VD << MaxTLSAlign;
3600 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3601 ICE.get(), SpellingListIndex);
3602 AA->setPackExpansion(IsPackExpansion);
3606 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3607 unsigned SpellingListIndex, bool IsPackExpansion) {
3608 // FIXME: Cache the number on the Attr object if non-dependent?
3609 // FIXME: Perform checking of type validity
3610 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3612 AA->setPackExpansion(IsPackExpansion);
3616 void Sema::CheckAlignasUnderalignment(Decl *D) {
3617 assert(D->hasAttrs() && "no attributes on decl");
3619 QualType UnderlyingTy, DiagTy;
3620 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3621 UnderlyingTy = DiagTy = VD->getType();
3623 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3624 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3625 UnderlyingTy = ED->getIntegerType();
3627 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3630 // C++11 [dcl.align]p5, C11 6.7.5/4:
3631 // The combined effect of all alignment attributes in a declaration shall
3632 // not specify an alignment that is less strict than the alignment that
3633 // would otherwise be required for the entity being declared.
3634 AlignedAttr *AlignasAttr = nullptr;
3636 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3637 if (I->isAlignmentDependent())
3641 Align = std::max(Align, I->getAlignment(Context));
3644 if (AlignasAttr && Align) {
3645 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3646 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3647 if (NaturalAlign > RequestedAlign)
3648 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3649 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3653 bool Sema::checkMSInheritanceAttrOnDefinition(
3654 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3655 MSInheritanceAttr::Spelling SemanticSpelling) {
3656 assert(RD->hasDefinition() && "RD has no definition!");
3658 // We may not have seen base specifiers or any virtual methods yet. We will
3659 // have to wait until the record is defined to catch any mismatches.
3660 if (!RD->getDefinition()->isCompleteDefinition())
3663 // The unspecified model never matches what a definition could need.
3664 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3668 if (RD->calculateInheritanceModel() == SemanticSpelling)
3671 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3675 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3676 << 0 /*definition*/;
3677 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3678 << RD->getNameAsString();
3682 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3684 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3685 bool &IntegerMode, bool &ComplexMode) {
3687 ComplexMode = false;
3688 switch (Str.size()) {
3710 if (Str[1] == 'F') {
3711 IntegerMode = false;
3712 } else if (Str[1] == 'C') {
3713 IntegerMode = false;
3715 } else if (Str[1] != 'I') {
3720 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3721 // pointer on PIC16 and other embedded platforms.
3723 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3724 else if (Str == "byte")
3725 DestWidth = S.Context.getTargetInfo().getCharWidth();
3728 if (Str == "pointer")
3729 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3732 if (Str == "unwind_word")
3733 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3738 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3741 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3742 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3743 /// HImode, not an intermediate pointer.
3744 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3745 // This attribute isn't documented, but glibc uses it. It changes
3746 // the width of an int or unsigned int to the specified size.
3747 if (!Attr.isArgIdent(0)) {
3748 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3749 << AANT_ArgumentIdentifier;
3753 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3755 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3758 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3759 unsigned SpellingListIndex, bool InInstantiation) {
3760 StringRef Str = Name->getName();
3762 SourceLocation AttrLoc = AttrRange.getBegin();
3764 unsigned DestWidth = 0;
3765 bool IntegerMode = true;
3766 bool ComplexMode = false;
3767 llvm::APInt VectorSize(64, 0);
3768 if (Str.size() >= 4 && Str[0] == 'V') {
3769 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3770 size_t StrSize = Str.size();
3771 size_t VectorStringLength = 0;
3772 while ((VectorStringLength + 1) < StrSize &&
3773 isdigit(Str[VectorStringLength + 1]))
3774 ++VectorStringLength;
3775 if (VectorStringLength &&
3776 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3777 VectorSize.isPowerOf2()) {
3778 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3779 IntegerMode, ComplexMode);
3780 // Avoid duplicate warning from template instantiation.
3781 if (!InInstantiation)
3782 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3789 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3791 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3792 // and friends, at least with glibc.
3793 // FIXME: Make sure floating-point mappings are accurate
3794 // FIXME: Support XF and TF types
3796 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3801 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3802 OldTy = TD->getUnderlyingType();
3803 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3804 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3805 // Try to get type from enum declaration, default to int.
3806 OldTy = ED->getIntegerType();
3808 OldTy = Context.IntTy;
3810 OldTy = cast<ValueDecl>(D)->getType();
3812 if (OldTy->isDependentType()) {
3813 D->addAttr(::new (Context)
3814 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3818 // Base type can also be a vector type (see PR17453).
3819 // Distinguish between base type and base element type.
3820 QualType OldElemTy = OldTy;
3821 if (const VectorType *VT = OldTy->getAs<VectorType>())
3822 OldElemTy = VT->getElementType();
3824 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3825 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3826 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3827 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3828 VectorSize.getBoolValue()) {
3829 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3832 bool IntegralOrAnyEnumType =
3833 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3835 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3836 !IntegralOrAnyEnumType)
3837 Diag(AttrLoc, diag::err_mode_not_primitive);
3838 else if (IntegerMode) {
3839 if (!IntegralOrAnyEnumType)
3840 Diag(AttrLoc, diag::err_mode_wrong_type);
3841 } else if (ComplexMode) {
3842 if (!OldElemTy->isComplexType())
3843 Diag(AttrLoc, diag::err_mode_wrong_type);
3845 if (!OldElemTy->isFloatingType())
3846 Diag(AttrLoc, diag::err_mode_wrong_type);
3852 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3853 OldElemTy->isSignedIntegerType());
3855 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3857 if (NewElemTy.isNull()) {
3858 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3863 NewElemTy = Context.getComplexType(NewElemTy);
3866 QualType NewTy = NewElemTy;
3867 if (VectorSize.getBoolValue()) {
3868 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3869 VectorType::GenericVector);
3870 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3871 // Complex machine mode does not support base vector types.
3873 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3876 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3877 OldVT->getNumElements() /
3878 Context.getTypeSize(NewElemTy);
3880 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3883 if (NewTy.isNull()) {
3884 Diag(AttrLoc, diag::err_mode_wrong_type);
3888 // Install the new type.
3889 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3890 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3891 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3892 ED->setIntegerType(NewTy);
3894 cast<ValueDecl>(D)->setType(NewTy);
3896 D->addAttr(::new (Context)
3897 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3900 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3901 D->addAttr(::new (S.Context)
3902 NoDebugAttr(Attr.getRange(), S.Context,
3903 Attr.getAttributeSpellingListIndex()));
3906 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3907 IdentifierInfo *Ident,
3908 unsigned AttrSpellingListIndex) {
3909 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3910 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3911 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3915 if (D->hasAttr<AlwaysInlineAttr>())
3918 return ::new (Context) AlwaysInlineAttr(Range, Context,
3919 AttrSpellingListIndex);
3922 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3923 IdentifierInfo *Ident,
3924 unsigned AttrSpellingListIndex) {
3925 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3928 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3931 InternalLinkageAttr *
3932 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3933 IdentifierInfo *Ident,
3934 unsigned AttrSpellingListIndex) {
3935 if (auto VD = dyn_cast<VarDecl>(D)) {
3936 // Attribute applies to Var but not any subclass of it (like ParmVar,
3937 // ImplicitParm or VarTemplateSpecialization).
3938 if (VD->getKind() != Decl::Var) {
3939 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3940 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3941 : ExpectedVariableOrFunction);
3944 // Attribute does not apply to non-static local variables.
3945 if (VD->hasLocalStorage()) {
3946 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3951 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3954 return ::new (Context)
3955 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3958 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3959 unsigned AttrSpellingListIndex) {
3960 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3961 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3962 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3966 if (D->hasAttr<MinSizeAttr>())
3969 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3972 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3973 unsigned AttrSpellingListIndex) {
3974 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3975 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3976 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3977 D->dropAttr<AlwaysInlineAttr>();
3979 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3980 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3981 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3982 D->dropAttr<MinSizeAttr>();
3985 if (D->hasAttr<OptimizeNoneAttr>())
3988 return ::new (Context) OptimizeNoneAttr(Range, Context,
3989 AttrSpellingListIndex);
3992 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3993 const AttributeList &Attr) {
3994 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3998 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3999 D, Attr.getRange(), Attr.getName(),
4000 Attr.getAttributeSpellingListIndex()))
4004 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4005 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4006 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4007 D->addAttr(MinSize);
4010 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4011 const AttributeList &Attr) {
4012 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4013 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4014 D->addAttr(Optnone);
4017 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4018 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4021 auto *VD = cast<VarDecl>(D);
4022 if (!VD->hasGlobalStorage()) {
4023 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4026 D->addAttr(::new (S.Context) CUDAConstantAttr(
4027 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4030 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4031 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4034 auto *VD = cast<VarDecl>(D);
4035 // extern __shared__ is only allowed on arrays with no length (e.g.
4037 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
4038 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4041 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4042 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4043 << S.CurrentCUDATarget())
4045 D->addAttr(::new (S.Context) CUDASharedAttr(
4046 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4049 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4050 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4052 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4056 FunctionDecl *FD = cast<FunctionDecl>(D);
4057 if (!FD->getReturnType()->isVoidType()) {
4058 SourceRange RTRange = FD->getReturnTypeSourceRange();
4059 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4061 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4065 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4066 if (Method->isInstance()) {
4067 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4071 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4073 // Only warn for "inline" when compiling for host, to cut down on noise.
4074 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4075 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
4077 D->addAttr(::new (S.Context)
4078 CUDAGlobalAttr(Attr.getRange(), S.Context,
4079 Attr.getAttributeSpellingListIndex()));
4082 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4083 FunctionDecl *Fn = cast<FunctionDecl>(D);
4084 if (!Fn->isInlineSpecified()) {
4085 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4089 D->addAttr(::new (S.Context)
4090 GNUInlineAttr(Attr.getRange(), S.Context,
4091 Attr.getAttributeSpellingListIndex()));
4094 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4095 if (hasDeclarator(D)) return;
4097 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
4098 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4100 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
4103 if (!isa<ObjCMethodDecl>(D)) {
4104 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4105 << Attr.getName() << ExpectedFunctionOrMethod;
4109 switch (Attr.getKind()) {
4110 case AttributeList::AT_FastCall:
4111 D->addAttr(::new (S.Context)
4112 FastCallAttr(Attr.getRange(), S.Context,
4113 Attr.getAttributeSpellingListIndex()));
4115 case AttributeList::AT_StdCall:
4116 D->addAttr(::new (S.Context)
4117 StdCallAttr(Attr.getRange(), S.Context,
4118 Attr.getAttributeSpellingListIndex()));
4120 case AttributeList::AT_ThisCall:
4121 D->addAttr(::new (S.Context)
4122 ThisCallAttr(Attr.getRange(), S.Context,
4123 Attr.getAttributeSpellingListIndex()));
4125 case AttributeList::AT_CDecl:
4126 D->addAttr(::new (S.Context)
4127 CDeclAttr(Attr.getRange(), S.Context,
4128 Attr.getAttributeSpellingListIndex()));
4130 case AttributeList::AT_Pascal:
4131 D->addAttr(::new (S.Context)
4132 PascalAttr(Attr.getRange(), S.Context,
4133 Attr.getAttributeSpellingListIndex()));
4135 case AttributeList::AT_SwiftCall:
4136 D->addAttr(::new (S.Context)
4137 SwiftCallAttr(Attr.getRange(), S.Context,
4138 Attr.getAttributeSpellingListIndex()));
4140 case AttributeList::AT_VectorCall:
4141 D->addAttr(::new (S.Context)
4142 VectorCallAttr(Attr.getRange(), S.Context,
4143 Attr.getAttributeSpellingListIndex()));
4145 case AttributeList::AT_MSABI:
4146 D->addAttr(::new (S.Context)
4147 MSABIAttr(Attr.getRange(), S.Context,
4148 Attr.getAttributeSpellingListIndex()));
4150 case AttributeList::AT_SysVABI:
4151 D->addAttr(::new (S.Context)
4152 SysVABIAttr(Attr.getRange(), S.Context,
4153 Attr.getAttributeSpellingListIndex()));
4155 case AttributeList::AT_RegCall:
4156 D->addAttr(::new (S.Context) RegCallAttr(
4157 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4159 case AttributeList::AT_Pcs: {
4160 PcsAttr::PCSType PCS;
4163 PCS = PcsAttr::AAPCS;
4166 PCS = PcsAttr::AAPCS_VFP;
4169 llvm_unreachable("unexpected calling convention in pcs attribute");
4172 D->addAttr(::new (S.Context)
4173 PcsAttr(Attr.getRange(), S.Context, PCS,
4174 Attr.getAttributeSpellingListIndex()));
4177 case AttributeList::AT_IntelOclBicc:
4178 D->addAttr(::new (S.Context)
4179 IntelOclBiccAttr(Attr.getRange(), S.Context,
4180 Attr.getAttributeSpellingListIndex()));
4182 case AttributeList::AT_PreserveMost:
4183 D->addAttr(::new (S.Context) PreserveMostAttr(
4184 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4186 case AttributeList::AT_PreserveAll:
4187 D->addAttr(::new (S.Context) PreserveAllAttr(
4188 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4191 llvm_unreachable("unexpected attribute kind");
4195 static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4196 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4199 std::vector<StringRef> DiagnosticIdentifiers;
4200 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4203 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4206 // FIXME: Warn if the rule name is unknown. This is tricky because only
4207 // clang-tidy knows about available rules.
4208 DiagnosticIdentifiers.push_back(RuleName);
4210 D->addAttr(::new (S.Context) SuppressAttr(
4211 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4212 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4215 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4216 const FunctionDecl *FD) {
4217 if (attr.isInvalid())
4220 if (attr.hasProcessingCache()) {
4221 CC = (CallingConv) attr.getProcessingCache();
4225 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4226 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
4231 // TODO: diagnose uses of these conventions on the wrong target.
4232 switch (attr.getKind()) {
4233 case AttributeList::AT_CDecl: CC = CC_C; break;
4234 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4235 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4236 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4237 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4238 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
4239 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
4240 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
4241 case AttributeList::AT_MSABI:
4242 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4245 case AttributeList::AT_SysVABI:
4246 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4249 case AttributeList::AT_Pcs: {
4251 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
4255 if (StrRef == "aapcs") {
4258 } else if (StrRef == "aapcs-vfp") {
4264 Diag(attr.getLoc(), diag::err_invalid_pcs);
4267 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4268 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4269 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4270 default: llvm_unreachable("unexpected attribute kind");
4273 const TargetInfo &TI = Context.getTargetInfo();
4274 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4275 if (A != TargetInfo::CCCR_OK) {
4276 if (A == TargetInfo::CCCR_Warning)
4277 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
4279 // This convention is not valid for the target. Use the default function or
4280 // method calling convention.
4281 bool IsCXXMethod = false, IsVariadic = false;
4283 IsCXXMethod = FD->isCXXInstanceMember();
4284 IsVariadic = FD->isVariadic();
4286 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4289 attr.setProcessingCache((unsigned) CC);
4293 /// Pointer-like types in the default address space.
4294 static bool isValidSwiftContextType(QualType type) {
4295 if (!type->hasPointerRepresentation())
4296 return type->isDependentType();
4297 return type->getPointeeType().getAddressSpace() == 0;
4300 /// Pointers and references in the default address space.
4301 static bool isValidSwiftIndirectResultType(QualType type) {
4302 if (auto ptrType = type->getAs<PointerType>()) {
4303 type = ptrType->getPointeeType();
4304 } else if (auto refType = type->getAs<ReferenceType>()) {
4305 type = refType->getPointeeType();
4307 return type->isDependentType();
4309 return type.getAddressSpace() == 0;
4312 /// Pointers and references to pointers in the default address space.
4313 static bool isValidSwiftErrorResultType(QualType type) {
4314 if (auto ptrType = type->getAs<PointerType>()) {
4315 type = ptrType->getPointeeType();
4316 } else if (auto refType = type->getAs<ReferenceType>()) {
4317 type = refType->getPointeeType();
4319 return type->isDependentType();
4321 if (!type.getQualifiers().empty())
4323 return isValidSwiftContextType(type);
4326 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4328 S.AddParameterABIAttr(attr.getRange(), D, abi,
4329 attr.getAttributeSpellingListIndex());
4332 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4333 unsigned spellingIndex) {
4335 QualType type = cast<ParmVarDecl>(D)->getType();
4337 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4338 if (existingAttr->getABI() != abi) {
4339 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4340 << getParameterABISpelling(abi) << existingAttr;
4341 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4347 case ParameterABI::Ordinary:
4348 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4350 case ParameterABI::SwiftContext:
4351 if (!isValidSwiftContextType(type)) {
4352 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4353 << getParameterABISpelling(abi)
4354 << /*pointer to pointer */ 0 << type;
4356 D->addAttr(::new (Context)
4357 SwiftContextAttr(range, Context, spellingIndex));
4360 case ParameterABI::SwiftErrorResult:
4361 if (!isValidSwiftErrorResultType(type)) {
4362 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4363 << getParameterABISpelling(abi)
4364 << /*pointer to pointer */ 1 << type;
4366 D->addAttr(::new (Context)
4367 SwiftErrorResultAttr(range, Context, spellingIndex));
4370 case ParameterABI::SwiftIndirectResult:
4371 if (!isValidSwiftIndirectResultType(type)) {
4372 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4373 << getParameterABISpelling(abi)
4374 << /*pointer*/ 0 << type;
4376 D->addAttr(::new (Context)
4377 SwiftIndirectResultAttr(range, Context, spellingIndex));
4380 llvm_unreachable("bad parameter ABI attribute");
4383 /// Checks a regparm attribute, returning true if it is ill-formed and
4384 /// otherwise setting numParams to the appropriate value.
4385 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4386 if (Attr.isInvalid())
4389 if (!checkAttributeNumArgs(*this, Attr, 1)) {
4395 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4396 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4401 if (Context.getTargetInfo().getRegParmMax() == 0) {
4402 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4403 << NumParamsExpr->getSourceRange();
4409 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4410 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4411 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4419 // Checks whether an argument of launch_bounds attribute is
4420 // acceptable, performs implicit conversion to Rvalue, and returns
4421 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4422 // and may output an error.
4423 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4424 const CUDALaunchBoundsAttr &Attr,
4425 const unsigned Idx) {
4426 if (S.DiagnoseUnexpandedParameterPack(E))
4429 // Accept template arguments for now as they depend on something else.
4430 // We'll get to check them when they eventually get instantiated.
4431 if (E->isValueDependent())
4435 if (!E->isIntegerConstantExpr(I, S.Context)) {
4436 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4437 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4440 // Make sure we can fit it in 32 bits.
4441 if (!I.isIntN(32)) {
4442 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4443 << 32 << /* Unsigned */ 1;
4447 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4448 << &Attr << Idx << E->getSourceRange();
4450 // We may need to perform implicit conversion of the argument.
4451 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4452 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4453 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4454 assert(!ValArg.isInvalid() &&
4455 "Unexpected PerformCopyInitialization() failure.");
4457 return ValArg.getAs<Expr>();
4460 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4461 Expr *MinBlocks, unsigned SpellingListIndex) {
4462 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4464 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4465 if (MaxThreads == nullptr)
4469 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4470 if (MinBlocks == nullptr)
4474 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4475 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4478 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4479 const AttributeList &Attr) {
4480 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4481 !checkAttributeAtMostNumArgs(S, Attr, 2))
4484 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4485 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4486 Attr.getAttributeSpellingListIndex());
4489 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4490 const AttributeList &Attr) {
4491 if (!Attr.isArgIdent(0)) {
4492 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4493 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4497 if (!checkAttributeNumArgs(S, Attr, 3))
4500 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4502 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4503 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4504 << Attr.getName() << ExpectedFunctionOrMethod;
4508 uint64_t ArgumentIdx;
4509 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4513 uint64_t TypeTagIdx;
4514 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4518 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4520 // Ensure that buffer has a pointer type.
4521 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4522 if (!BufferTy->isPointerType()) {
4523 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4524 << Attr.getName() << 0;
4528 D->addAttr(::new (S.Context)
4529 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4530 ArgumentIdx, TypeTagIdx, IsPointer,
4531 Attr.getAttributeSpellingListIndex()));
4534 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4535 const AttributeList &Attr) {
4536 if (!Attr.isArgIdent(0)) {
4537 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4538 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4542 if (!checkAttributeNumArgs(S, Attr, 1))
4545 if (!isa<VarDecl>(D)) {
4546 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4547 << Attr.getName() << ExpectedVariable;
4551 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4552 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4553 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4554 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4556 D->addAttr(::new (S.Context)
4557 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4559 Attr.getLayoutCompatible(),
4560 Attr.getMustBeNull(),
4561 Attr.getAttributeSpellingListIndex()));
4564 static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4565 const AttributeList &Attr) {
4567 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4571 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4572 D->addAttr(::new (S.Context)
4573 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4574 Attr.getAttributeSpellingListIndex()));
4577 //===----------------------------------------------------------------------===//
4578 // Checker-specific attribute handlers.
4579 //===----------------------------------------------------------------------===//
4581 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4582 return type->isDependentType() ||
4583 type->isObjCRetainableType();
4586 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4587 return type->isDependentType() ||
4588 type->isObjCObjectPointerType() ||
4589 S.Context.isObjCNSObjectType(type);
4592 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4593 return type->isDependentType() ||
4594 type->isPointerType() ||
4595 isValidSubjectOfNSAttribute(S, type);
4598 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4599 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4600 Attr.getKind() == AttributeList::AT_NSConsumed,
4601 /*template instantiation*/ false);
4604 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4605 unsigned spellingIndex, bool isNSConsumed,
4606 bool isTemplateInstantiation) {
4607 ParmVarDecl *param = cast<ParmVarDecl>(D);
4611 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4613 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4617 // These attributes are normally just advisory, but in ARC, ns_consumed
4618 // is significant. Allow non-dependent code to contain inappropriate
4619 // attributes even in ARC, but require template instantiations to be
4620 // set up correctly.
4621 Diag(D->getLocStart(),
4622 (isTemplateInstantiation && isNSConsumed &&
4623 getLangOpts().ObjCAutoRefCount
4624 ? diag::err_ns_attribute_wrong_parameter_type
4625 : diag::warn_ns_attribute_wrong_parameter_type))
4627 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4628 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4633 param->addAttr(::new (Context)
4634 NSConsumedAttr(attrRange, Context, spellingIndex));
4636 param->addAttr(::new (Context)
4637 CFConsumedAttr(attrRange, Context, spellingIndex));
4640 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4641 const AttributeList &Attr) {
4642 QualType returnType;
4644 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4645 returnType = MD->getReturnType();
4646 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4647 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4648 return; // ignore: was handled as a type attribute
4649 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4650 returnType = PD->getType();
4651 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4652 returnType = FD->getReturnType();
4653 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4654 returnType = Param->getType()->getPointeeType();
4655 if (returnType.isNull()) {
4656 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4657 << Attr.getName() << /*pointer-to-CF*/2
4662 AttributeDeclKind ExpectedDeclKind;
4663 switch (Attr.getKind()) {
4664 default: llvm_unreachable("invalid ownership attribute");
4665 case AttributeList::AT_NSReturnsRetained:
4666 case AttributeList::AT_NSReturnsAutoreleased:
4667 case AttributeList::AT_NSReturnsNotRetained:
4668 ExpectedDeclKind = ExpectedFunctionOrMethod;
4671 case AttributeList::AT_CFReturnsRetained:
4672 case AttributeList::AT_CFReturnsNotRetained:
4673 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4676 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4677 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4683 switch (Attr.getKind()) {
4684 default: llvm_unreachable("invalid ownership attribute");
4685 case AttributeList::AT_NSReturnsRetained:
4686 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4690 case AttributeList::AT_NSReturnsAutoreleased:
4691 case AttributeList::AT_NSReturnsNotRetained:
4692 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4696 case AttributeList::AT_CFReturnsRetained:
4697 case AttributeList::AT_CFReturnsNotRetained:
4698 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4704 if (isa<ParmVarDecl>(D)) {
4705 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4706 << Attr.getName() << /*pointer-to-CF*/2
4709 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4714 } SubjectKind = Function;
4715 if (isa<ObjCMethodDecl>(D))
4716 SubjectKind = Method;
4717 else if (isa<ObjCPropertyDecl>(D))
4718 SubjectKind = Property;
4719 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4720 << Attr.getName() << SubjectKind << cf
4726 switch (Attr.getKind()) {
4728 llvm_unreachable("invalid ownership attribute");
4729 case AttributeList::AT_NSReturnsAutoreleased:
4730 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4731 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4733 case AttributeList::AT_CFReturnsNotRetained:
4734 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4735 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4737 case AttributeList::AT_NSReturnsNotRetained:
4738 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4739 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4741 case AttributeList::AT_CFReturnsRetained:
4742 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4743 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4745 case AttributeList::AT_NSReturnsRetained:
4746 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4747 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4752 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4753 const AttributeList &attr) {
4754 const int EP_ObjCMethod = 1;
4755 const int EP_ObjCProperty = 2;
4757 SourceLocation loc = attr.getLoc();
4758 QualType resultType;
4759 if (isa<ObjCMethodDecl>(D))
4760 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4762 resultType = cast<ObjCPropertyDecl>(D)->getType();
4764 if (!resultType->isReferenceType() &&
4765 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4766 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4769 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4770 << /*non-retainable pointer*/ 2;
4772 // Drop the attribute.
4776 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4777 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4780 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4781 const AttributeList &attr) {
4782 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4784 DeclContext *DC = method->getDeclContext();
4785 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4786 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4787 << attr.getName() << 0;
4788 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4791 if (method->getMethodFamily() == OMF_dealloc) {
4792 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4793 << attr.getName() << 1;
4797 method->addAttr(::new (S.Context)
4798 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4799 attr.getAttributeSpellingListIndex()));
4802 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4803 const AttributeList &Attr) {
4804 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4808 D->addAttr(::new (S.Context)
4809 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4810 Attr.getAttributeSpellingListIndex()));
4813 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4814 const AttributeList &Attr) {
4815 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4819 D->addAttr(::new (S.Context)
4820 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4821 Attr.getAttributeSpellingListIndex()));
4824 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4825 const AttributeList &Attr) {
4826 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4829 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4833 // Typedefs only allow objc_bridge(id) and have some additional checking.
4834 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4835 if (!Parm->Ident->isStr("id")) {
4836 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4841 // Only allow 'cv void *'.
4842 QualType T = TD->getUnderlyingType();
4843 if (!T->isVoidPointerType()) {
4844 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4849 D->addAttr(::new (S.Context)
4850 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4851 Attr.getAttributeSpellingListIndex()));
4854 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4855 const AttributeList &Attr) {
4856 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4859 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4863 D->addAttr(::new (S.Context)
4864 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4865 Attr.getAttributeSpellingListIndex()));
4868 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4869 const AttributeList &Attr) {
4870 IdentifierInfo *RelatedClass =
4871 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4872 if (!RelatedClass) {
4873 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4876 IdentifierInfo *ClassMethod =
4877 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4878 IdentifierInfo *InstanceMethod =
4879 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4880 D->addAttr(::new (S.Context)
4881 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4882 ClassMethod, InstanceMethod,
4883 Attr.getAttributeSpellingListIndex()));
4886 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4887 const AttributeList &Attr) {
4888 ObjCInterfaceDecl *IFace;
4889 if (ObjCCategoryDecl *CatDecl =
4890 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4891 IFace = CatDecl->getClassInterface();
4893 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4898 IFace->setHasDesignatedInitializers();
4899 D->addAttr(::new (S.Context)
4900 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4901 Attr.getAttributeSpellingListIndex()));
4904 static void handleObjCRuntimeName(Sema &S, Decl *D,
4905 const AttributeList &Attr) {
4906 StringRef MetaDataName;
4907 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4909 D->addAttr(::new (S.Context)
4910 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4912 Attr.getAttributeSpellingListIndex()));
4915 // When a user wants to use objc_boxable with a union or struct
4916 // but they don't have access to the declaration (legacy/third-party code)
4917 // then they can 'enable' this feature with a typedef:
4918 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4919 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4920 bool notify = false;
4922 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4923 if (RD && RD->getDefinition()) {
4924 RD = RD->getDefinition();
4929 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4930 ObjCBoxableAttr(Attr.getRange(), S.Context,
4931 Attr.getAttributeSpellingListIndex());
4932 RD->addAttr(BoxableAttr);
4934 // we need to notify ASTReader/ASTWriter about
4935 // modification of existing declaration
4936 if (ASTMutationListener *L = S.getASTMutationListener())
4937 L->AddedAttributeToRecord(BoxableAttr, RD);
4942 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4943 const AttributeList &Attr) {
4944 if (hasDeclarator(D)) return;
4946 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4947 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4950 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4951 const AttributeList &Attr) {
4952 ValueDecl *vd = cast<ValueDecl>(D);
4953 QualType type = vd->getType();
4955 if (!type->isDependentType() &&
4956 !type->isObjCLifetimeType()) {
4957 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4962 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4964 // If we have no lifetime yet, check the lifetime we're presumably
4966 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4967 lifetime = type->getObjCARCImplicitLifetime();
4970 case Qualifiers::OCL_None:
4971 assert(type->isDependentType() &&
4972 "didn't infer lifetime for non-dependent type?");
4975 case Qualifiers::OCL_Weak: // meaningful
4976 case Qualifiers::OCL_Strong: // meaningful
4979 case Qualifiers::OCL_ExplicitNone:
4980 case Qualifiers::OCL_Autoreleasing:
4981 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4982 << (lifetime == Qualifiers::OCL_Autoreleasing);
4986 D->addAttr(::new (S.Context)
4987 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4988 Attr.getAttributeSpellingListIndex()));
4991 //===----------------------------------------------------------------------===//
4992 // Microsoft specific attribute handlers.
4993 //===----------------------------------------------------------------------===//
4995 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4996 unsigned AttrSpellingListIndex, StringRef Uuid) {
4997 if (const auto *UA = D->getAttr<UuidAttr>()) {
4998 if (UA->getGuid().equals_lower(Uuid))
5000 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5001 Diag(Range.getBegin(), diag::note_previous_uuid);
5002 D->dropAttr<UuidAttr>();
5005 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5008 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5009 if (!S.LangOpts.CPlusPlus) {
5010 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5011 << Attr.getName() << AttributeLangSupport::C;
5016 SourceLocation LiteralLoc;
5017 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
5020 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5021 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5022 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5023 StrRef = StrRef.drop_front().drop_back();
5025 // Validate GUID length.
5026 if (StrRef.size() != 36) {
5027 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5031 for (unsigned i = 0; i < 36; ++i) {
5032 if (i == 8 || i == 13 || i == 18 || i == 23) {
5033 if (StrRef[i] != '-') {
5034 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5037 } else if (!isHexDigit(StrRef[i])) {
5038 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5043 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5044 Attr.getAttributeSpellingListIndex(), StrRef);
5049 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5050 if (!S.LangOpts.CPlusPlus) {
5051 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5052 << Attr.getName() << AttributeLangSupport::C;
5055 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5056 D, Attr.getRange(), /*BestCase=*/true,
5057 Attr.getAttributeSpellingListIndex(),
5058 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
5061 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5065 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5066 const AttributeList &Attr) {
5067 VarDecl *VD = cast<VarDecl>(D);
5068 if (!S.Context.getTargetInfo().isTLSSupported()) {
5069 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5072 if (VD->getTSCSpec() != TSCS_unspecified) {
5073 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5076 if (VD->hasLocalStorage()) {
5077 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5080 VD->addAttr(::new (S.Context) ThreadAttr(
5081 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5084 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5085 SmallVector<StringRef, 4> Tags;
5086 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5088 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5090 Tags.push_back(Tag);
5093 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5094 if (!NS->isInline()) {
5095 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5098 if (NS->isAnonymousNamespace()) {
5099 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5102 if (Attr.getNumArgs() == 0)
5103 Tags.push_back(NS->getName());
5104 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5107 // Store tags sorted and without duplicates.
5108 std::sort(Tags.begin(), Tags.end());
5109 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5111 D->addAttr(::new (S.Context)
5112 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5113 Attr.getAttributeSpellingListIndex()));
5116 static void handleARMInterruptAttr(Sema &S, Decl *D,
5117 const AttributeList &Attr) {
5118 // Check the attribute arguments.
5119 if (Attr.getNumArgs() > 1) {
5120 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5121 << Attr.getName() << 1;
5126 SourceLocation ArgLoc;
5128 if (Attr.getNumArgs() == 0)
5130 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5133 ARMInterruptAttr::InterruptType Kind;
5134 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5135 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5136 << Attr.getName() << Str << ArgLoc;
5140 unsigned Index = Attr.getAttributeSpellingListIndex();
5141 D->addAttr(::new (S.Context)
5142 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5145 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5146 const AttributeList &Attr) {
5147 if (!checkAttributeNumArgs(S, Attr, 1))
5150 if (!Attr.isArgExpr(0)) {
5151 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5152 << AANT_ArgumentIntegerConstant;
5156 // FIXME: Check for decl - it should be void ()(void).
5158 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5159 llvm::APSInt NumParams(32);
5160 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5162 << Attr.getName() << AANT_ArgumentIntegerConstant
5163 << NumParamsExpr->getSourceRange();
5167 unsigned Num = NumParams.getLimitedValue(255);
5168 if ((Num & 1) || Num > 30) {
5169 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5170 << Attr.getName() << (int)NumParams.getSExtValue()
5171 << NumParamsExpr->getSourceRange();
5175 D->addAttr(::new (S.Context)
5176 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5177 Attr.getAttributeSpellingListIndex()));
5178 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5181 static void handleMipsInterruptAttr(Sema &S, Decl *D,
5182 const AttributeList &Attr) {
5183 // Only one optional argument permitted.
5184 if (Attr.getNumArgs() > 1) {
5185 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5186 << Attr.getName() << 1;
5191 SourceLocation ArgLoc;
5193 if (Attr.getNumArgs() == 0)
5195 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5198 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5199 // a) Must be a function.
5200 // b) Must have no parameters.
5201 // c) Must have the 'void' return type.
5202 // d) Cannot have the 'mips16' attribute, as that instruction set
5203 // lacks the 'eret' instruction.
5204 // e) The attribute itself must either have no argument or one of the
5205 // valid interrupt types, see [MipsInterruptDocs].
5207 if (!isFunctionOrMethod(D)) {
5208 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5209 << "'interrupt'" << ExpectedFunctionOrMethod;
5213 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5214 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5219 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5220 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5225 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5229 MipsInterruptAttr::InterruptType Kind;
5230 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5231 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5232 << Attr.getName() << "'" + std::string(Str) + "'";
5236 D->addAttr(::new (S.Context) MipsInterruptAttr(
5237 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5240 static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5241 const AttributeList &Attr) {
5242 // Semantic checks for a function with the 'interrupt' attribute.
5243 // a) Must be a function.
5244 // b) Must have the 'void' return type.
5245 // c) Must take 1 or 2 arguments.
5246 // d) The 1st argument must be a pointer.
5247 // e) The 2nd argument (if any) must be an unsigned integer.
5248 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5249 CXXMethodDecl::isStaticOverloadedOperator(
5250 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5251 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5252 << Attr.getName() << ExpectedFunctionWithProtoType;
5255 // Interrupt handler must have void return type.
5256 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5257 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5258 diag::err_anyx86_interrupt_attribute)
5259 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5265 // Interrupt handler must have 1 or 2 parameters.
5266 unsigned NumParams = getFunctionOrMethodNumParams(D);
5267 if (NumParams < 1 || NumParams > 2) {
5268 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5269 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5275 // The first argument must be a pointer.
5276 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5277 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5278 diag::err_anyx86_interrupt_attribute)
5279 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5285 // The second argument, if present, must be an unsigned integer.
5287 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5290 if (NumParams == 2 &&
5291 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5292 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5293 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5294 diag::err_anyx86_interrupt_attribute)
5295 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5298 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5301 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5302 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5303 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5306 static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5307 if (!isFunctionOrMethod(D)) {
5308 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5309 << "'interrupt'" << ExpectedFunction;
5313 if (!checkAttributeNumArgs(S, Attr, 0))
5316 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5319 static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5320 if (!isFunctionOrMethod(D)) {
5321 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5322 << "'signal'" << ExpectedFunction;
5326 if (!checkAttributeNumArgs(S, Attr, 0))
5329 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5332 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5333 // Dispatch the interrupt attribute based on the current target.
5334 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5335 case llvm::Triple::msp430:
5336 handleMSP430InterruptAttr(S, D, Attr);
5338 case llvm::Triple::mipsel:
5339 case llvm::Triple::mips:
5340 handleMipsInterruptAttr(S, D, Attr);
5342 case llvm::Triple::x86:
5343 case llvm::Triple::x86_64:
5344 handleAnyX86InterruptAttr(S, D, Attr);
5346 case llvm::Triple::avr:
5347 handleAVRInterruptAttr(S, D, Attr);
5350 handleARMInterruptAttr(S, D, Attr);
5355 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5356 const AttributeList &Attr) {
5358 Expr *MinExpr = Attr.getArgAsExpr(0);
5359 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5363 Expr *MaxExpr = Attr.getArgAsExpr(1);
5364 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5367 if (Min == 0 && Max != 0) {
5368 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5369 << Attr.getName() << 0;
5373 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5374 << Attr.getName() << 1;
5378 D->addAttr(::new (S.Context)
5379 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5380 Attr.getAttributeSpellingListIndex()));
5383 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5384 const AttributeList &Attr) {
5386 Expr *MinExpr = Attr.getArgAsExpr(0);
5387 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5391 if (Attr.getNumArgs() == 2) {
5392 Expr *MaxExpr = Attr.getArgAsExpr(1);
5393 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5397 if (Min == 0 && Max != 0) {
5398 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5399 << Attr.getName() << 0;
5402 if (Max != 0 && Min > Max) {
5403 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5404 << Attr.getName() << 1;
5408 D->addAttr(::new (S.Context)
5409 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5410 Attr.getAttributeSpellingListIndex()));
5413 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5414 const AttributeList &Attr) {
5415 uint32_t NumSGPR = 0;
5416 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5417 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
5420 D->addAttr(::new (S.Context)
5421 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5422 Attr.getAttributeSpellingListIndex()));
5425 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5426 const AttributeList &Attr) {
5427 uint32_t NumVGPR = 0;
5428 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5429 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5432 D->addAttr(::new (S.Context)
5433 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
5434 Attr.getAttributeSpellingListIndex()));
5437 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5438 const AttributeList& Attr) {
5439 // If we try to apply it to a function pointer, don't warn, but don't
5440 // do anything, either. It doesn't matter anyway, because there's nothing
5441 // special about calling a force_align_arg_pointer function.
5442 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5443 if (VD && VD->getType()->isFunctionPointerType())
5445 // Also don't warn on function pointer typedefs.
5446 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5447 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5448 TD->getUnderlyingType()->isFunctionType()))
5450 // Attribute can only be applied to function types.
5451 if (!isa<FunctionDecl>(D)) {
5452 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5453 << Attr.getName() << /* function */0;
5457 D->addAttr(::new (S.Context)
5458 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5459 Attr.getAttributeSpellingListIndex()));
5462 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5464 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5465 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5468 // TODO: Investigate what happens with the next major version of MSVC.
5469 if (Version != LangOptions::MSVC2015) {
5470 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5471 << Attr.getName() << Version << VersionExpr->getSourceRange();
5475 D->addAttr(::new (S.Context)
5476 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5477 Attr.getAttributeSpellingListIndex()));
5480 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5481 unsigned AttrSpellingListIndex) {
5482 if (D->hasAttr<DLLExportAttr>()) {
5483 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5487 if (D->hasAttr<DLLImportAttr>())
5490 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5493 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5494 unsigned AttrSpellingListIndex) {
5495 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5496 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5497 D->dropAttr<DLLImportAttr>();
5500 if (D->hasAttr<DLLExportAttr>())
5503 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5506 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5507 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5508 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5509 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5514 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5515 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5516 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5517 // MinGW doesn't allow dllimport on inline functions.
5518 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5524 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5525 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5526 MD->getParent()->isLambda()) {
5527 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5532 unsigned Index = A.getAttributeSpellingListIndex();
5533 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5534 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5535 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5537 D->addAttr(NewAttr);
5541 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5542 unsigned AttrSpellingListIndex,
5543 MSInheritanceAttr::Spelling SemanticSpelling) {
5544 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5545 if (IA->getSemanticSpelling() == SemanticSpelling)
5547 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5548 << 1 /*previous declaration*/;
5549 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5550 D->dropAttr<MSInheritanceAttr>();
5553 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5554 if (RD->hasDefinition()) {
5555 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5556 SemanticSpelling)) {
5560 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5561 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5562 << 1 /*partial specialization*/;
5565 if (RD->getDescribedClassTemplate()) {
5566 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5567 << 0 /*primary template*/;
5572 return ::new (Context)
5573 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5576 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5577 // The capability attributes take a single string parameter for the name of
5578 // the capability they represent. The lockable attribute does not take any
5579 // parameters. However, semantically, both attributes represent the same
5580 // concept, and so they use the same semantic attribute. Eventually, the
5581 // lockable attribute will be removed.
5583 // For backward compatibility, any capability which has no specified string
5584 // literal will be considered a "mutex."
5585 StringRef N("mutex");
5586 SourceLocation LiteralLoc;
5587 if (Attr.getKind() == AttributeList::AT_Capability &&
5588 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5591 // Currently, there are only two names allowed for a capability: role and
5592 // mutex (case insensitive). Diagnose other capability names.
5593 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5594 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5596 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5597 Attr.getAttributeSpellingListIndex()));
5600 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5601 const AttributeList &Attr) {
5602 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5603 Attr.getArgAsExpr(0),
5604 Attr.getAttributeSpellingListIndex()));
5607 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5608 const AttributeList &Attr) {
5609 SmallVector<Expr*, 1> Args;
5610 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5613 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5615 Args.data(), Args.size(),
5616 Attr.getAttributeSpellingListIndex()));
5619 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5620 const AttributeList &Attr) {
5621 SmallVector<Expr*, 2> Args;
5622 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5625 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5627 Attr.getArgAsExpr(0),
5630 Attr.getAttributeSpellingListIndex()));
5633 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5634 const AttributeList &Attr) {
5635 // Check that all arguments are lockable objects.
5636 SmallVector<Expr *, 1> Args;
5637 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5639 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5640 Attr.getRange(), S.Context, Args.data(), Args.size(),
5641 Attr.getAttributeSpellingListIndex()));
5644 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5645 const AttributeList &Attr) {
5646 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5649 // check that all arguments are lockable objects
5650 SmallVector<Expr*, 1> Args;
5651 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5655 RequiresCapabilityAttr *RCA = ::new (S.Context)
5656 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5657 Args.size(), Attr.getAttributeSpellingListIndex());
5662 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5663 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5664 if (NSD->isAnonymousNamespace()) {
5665 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5666 // Do not want to attach the attribute to the namespace because that will
5667 // cause confusing diagnostic reports for uses of declarations within the
5673 // Handle the cases where the attribute has a text message.
5674 StringRef Str, Replacement;
5675 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5676 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5679 // Only support a single optional message for Declspec and CXX11.
5680 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5681 checkAttributeAtMostNumArgs(S, Attr, 1);
5682 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5683 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5686 if (!S.getLangOpts().CPlusPlus14)
5687 if (Attr.isCXX11Attribute() &&
5688 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5689 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5691 D->addAttr(::new (S.Context)
5692 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5693 Attr.getAttributeSpellingListIndex()));
5696 static bool isGlobalVar(const Decl *D) {
5697 if (const auto *S = dyn_cast<VarDecl>(D))
5698 return S->hasGlobalStorage();
5702 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5703 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5706 std::vector<StringRef> Sanitizers;
5708 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5709 StringRef SanitizerName;
5710 SourceLocation LiteralLoc;
5712 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5715 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5716 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5717 else if (isGlobalVar(D) && SanitizerName != "address")
5718 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5719 << Attr.getName() << ExpectedFunctionOrMethod;
5720 Sanitizers.push_back(SanitizerName);
5723 D->addAttr(::new (S.Context) NoSanitizeAttr(
5724 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5725 Attr.getAttributeSpellingListIndex()));
5728 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5729 const AttributeList &Attr) {
5730 StringRef AttrName = Attr.getName()->getName();
5731 normalizeName(AttrName);
5732 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5733 .Case("no_address_safety_analysis", "address")
5734 .Case("no_sanitize_address", "address")
5735 .Case("no_sanitize_thread", "thread")
5736 .Case("no_sanitize_memory", "memory");
5737 if (isGlobalVar(D) && SanitizerName != "address")
5738 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5739 << Attr.getName() << ExpectedFunction;
5740 D->addAttr(::new (S.Context)
5741 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5742 Attr.getAttributeSpellingListIndex()));
5745 static void handleInternalLinkageAttr(Sema &S, Decl *D,
5746 const AttributeList &Attr) {
5747 if (InternalLinkageAttr *Internal =
5748 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5749 Attr.getAttributeSpellingListIndex()))
5750 D->addAttr(Internal);
5753 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5754 if (S.LangOpts.OpenCLVersion != 200)
5755 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5756 << Attr.getName() << "2.0" << 0;
5758 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5759 << Attr.getName() << "2.0";
5762 /// Handles semantic checking for features that are common to all attributes,
5763 /// such as checking whether a parameter was properly specified, or the correct
5764 /// number of arguments were passed, etc.
5765 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5766 const AttributeList &Attr) {
5767 // Several attributes carry different semantics than the parsing requires, so
5768 // those are opted out of the common handling.
5770 // We also bail on unknown and ignored attributes because those are handled
5771 // as part of the target-specific handling logic.
5772 if (Attr.hasCustomParsing() ||
5773 Attr.getKind() == AttributeList::UnknownAttribute)
5776 // Check whether the attribute requires specific language extensions to be
5778 if (!Attr.diagnoseLangOpts(S))
5781 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5782 // If there are no optional arguments, then checking for the argument count
5784 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5787 // There are optional arguments, so checking is slightly more involved.
5788 if (Attr.getMinArgs() &&
5789 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5791 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5792 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5796 // Check whether the attribute appertains to the given subject.
5797 if (!Attr.diagnoseAppertainsTo(S, D))
5803 static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5804 const AttributeList &Attr) {
5805 if (D->isInvalidDecl())
5808 // Check if there is only one access qualifier.
5809 if (D->hasAttr<OpenCLAccessAttr>()) {
5810 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5811 << D->getSourceRange();
5812 D->setInvalidDecl(true);
5816 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5817 // image object can be read and written.
5818 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5819 // object. Using the read_write (or __read_write) qualifier with the pipe
5820 // qualifier is a compilation error.
5821 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5822 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5823 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5824 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5825 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5826 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5827 D->setInvalidDecl(true);
5833 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5834 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5837 //===----------------------------------------------------------------------===//
5838 // Top Level Sema Entry Points
5839 //===----------------------------------------------------------------------===//
5841 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5842 /// the attribute applies to decls. If the attribute is a type attribute, just
5843 /// silently ignore it if a GNU attribute.
5844 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5845 const AttributeList &Attr,
5846 bool IncludeCXX11Attributes) {
5847 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5850 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5852 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5855 // Unknown attributes are automatically warned on. Target-specific attributes
5856 // which do not apply to the current target architecture are treated as
5857 // though they were unknown attributes.
5858 if (Attr.getKind() == AttributeList::UnknownAttribute ||
5859 !Attr.existsInTarget(S.Context.getTargetInfo())) {
5860 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5861 ? diag::warn_unhandled_ms_attribute_ignored
5862 : diag::warn_unknown_attribute_ignored)
5867 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5870 switch (Attr.getKind()) {
5872 if (!Attr.isStmtAttr()) {
5873 // Type attributes are handled elsewhere; silently move on.
5874 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5877 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5878 << Attr.getName() << D->getLocation();
5880 case AttributeList::AT_Interrupt:
5881 handleInterruptAttr(S, D, Attr);
5883 case AttributeList::AT_X86ForceAlignArgPointer:
5884 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5886 case AttributeList::AT_DLLExport:
5887 case AttributeList::AT_DLLImport:
5888 handleDLLAttr(S, D, Attr);
5890 case AttributeList::AT_Mips16:
5891 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5894 case AttributeList::AT_NoMips16:
5895 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5897 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5898 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5900 case AttributeList::AT_AMDGPUWavesPerEU:
5901 handleAMDGPUWavesPerEUAttr(S, D, Attr);
5903 case AttributeList::AT_AMDGPUNumSGPR:
5904 handleAMDGPUNumSGPRAttr(S, D, Attr);
5906 case AttributeList::AT_AMDGPUNumVGPR:
5907 handleAMDGPUNumVGPRAttr(S, D, Attr);
5909 case AttributeList::AT_AVRSignal:
5910 handleAVRSignalAttr(S, D, Attr);
5912 case AttributeList::AT_IBAction:
5913 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5915 case AttributeList::AT_IBOutlet:
5916 handleIBOutlet(S, D, Attr);
5918 case AttributeList::AT_IBOutletCollection:
5919 handleIBOutletCollection(S, D, Attr);
5921 case AttributeList::AT_IFunc:
5922 handleIFuncAttr(S, D, Attr);
5924 case AttributeList::AT_Alias:
5925 handleAliasAttr(S, D, Attr);
5927 case AttributeList::AT_Aligned:
5928 handleAlignedAttr(S, D, Attr);
5930 case AttributeList::AT_AlignValue:
5931 handleAlignValueAttr(S, D, Attr);
5933 case AttributeList::AT_AllocSize:
5934 handleAllocSizeAttr(S, D, Attr);
5936 case AttributeList::AT_AlwaysInline:
5937 handleAlwaysInlineAttr(S, D, Attr);
5939 case AttributeList::AT_AnalyzerNoReturn:
5940 handleAnalyzerNoReturnAttr(S, D, Attr);
5942 case AttributeList::AT_TLSModel:
5943 handleTLSModelAttr(S, D, Attr);
5945 case AttributeList::AT_Annotate:
5946 handleAnnotateAttr(S, D, Attr);
5948 case AttributeList::AT_Availability:
5949 handleAvailabilityAttr(S, D, Attr);
5951 case AttributeList::AT_CarriesDependency:
5952 handleDependencyAttr(S, scope, D, Attr);
5954 case AttributeList::AT_Common:
5955 handleCommonAttr(S, D, Attr);
5957 case AttributeList::AT_CUDAConstant:
5958 handleConstantAttr(S, D, Attr);
5960 case AttributeList::AT_PassObjectSize:
5961 handlePassObjectSizeAttr(S, D, Attr);
5963 case AttributeList::AT_Constructor:
5964 handleConstructorAttr(S, D, Attr);
5966 case AttributeList::AT_CXX11NoReturn:
5967 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5969 case AttributeList::AT_Deprecated:
5970 handleDeprecatedAttr(S, D, Attr);
5972 case AttributeList::AT_Destructor:
5973 handleDestructorAttr(S, D, Attr);
5975 case AttributeList::AT_EnableIf:
5976 handleEnableIfAttr(S, D, Attr);
5978 case AttributeList::AT_DiagnoseIf:
5979 handleDiagnoseIfAttr(S, D, Attr);
5981 case AttributeList::AT_ExtVectorType:
5982 handleExtVectorTypeAttr(S, scope, D, Attr);
5984 case AttributeList::AT_ExternalSourceSymbol:
5985 handleExternalSourceSymbolAttr(S, D, Attr);
5987 case AttributeList::AT_MinSize:
5988 handleMinSizeAttr(S, D, Attr);
5990 case AttributeList::AT_OptimizeNone:
5991 handleOptimizeNoneAttr(S, D, Attr);
5993 case AttributeList::AT_FlagEnum:
5994 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5996 case AttributeList::AT_EnumExtensibility:
5997 handleEnumExtensibilityAttr(S, D, Attr);
5999 case AttributeList::AT_Flatten:
6000 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
6002 case AttributeList::AT_Format:
6003 handleFormatAttr(S, D, Attr);
6005 case AttributeList::AT_FormatArg:
6006 handleFormatArgAttr(S, D, Attr);
6008 case AttributeList::AT_CUDAGlobal:
6009 handleGlobalAttr(S, D, Attr);
6011 case AttributeList::AT_CUDADevice:
6012 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6015 case AttributeList::AT_CUDAHost:
6016 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6019 case AttributeList::AT_GNUInline:
6020 handleGNUInlineAttr(S, D, Attr);
6022 case AttributeList::AT_CUDALaunchBounds:
6023 handleLaunchBoundsAttr(S, D, Attr);
6025 case AttributeList::AT_Restrict:
6026 handleRestrictAttr(S, D, Attr);
6028 case AttributeList::AT_MayAlias:
6029 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6031 case AttributeList::AT_Mode:
6032 handleModeAttr(S, D, Attr);
6034 case AttributeList::AT_NoAlias:
6035 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6037 case AttributeList::AT_NoCommon:
6038 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6040 case AttributeList::AT_NoSplitStack:
6041 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6043 case AttributeList::AT_NonNull:
6044 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6045 handleNonNullAttrParameter(S, PVD, Attr);
6047 handleNonNullAttr(S, D, Attr);
6049 case AttributeList::AT_ReturnsNonNull:
6050 handleReturnsNonNullAttr(S, D, Attr);
6052 case AttributeList::AT_AssumeAligned:
6053 handleAssumeAlignedAttr(S, D, Attr);
6055 case AttributeList::AT_AllocAlign:
6056 handleAllocAlignAttr(S, D, Attr);
6058 case AttributeList::AT_Overloadable:
6059 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6061 case AttributeList::AT_Ownership:
6062 handleOwnershipAttr(S, D, Attr);
6064 case AttributeList::AT_Cold:
6065 handleColdAttr(S, D, Attr);
6067 case AttributeList::AT_Hot:
6068 handleHotAttr(S, D, Attr);
6070 case AttributeList::AT_Naked:
6071 handleNakedAttr(S, D, Attr);
6073 case AttributeList::AT_NoReturn:
6074 handleNoReturnAttr(S, D, Attr);
6076 case AttributeList::AT_NoThrow:
6077 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
6079 case AttributeList::AT_CUDAShared:
6080 handleSharedAttr(S, D, Attr);
6082 case AttributeList::AT_VecReturn:
6083 handleVecReturnAttr(S, D, Attr);
6085 case AttributeList::AT_ObjCOwnership:
6086 handleObjCOwnershipAttr(S, D, Attr);
6088 case AttributeList::AT_ObjCPreciseLifetime:
6089 handleObjCPreciseLifetimeAttr(S, D, Attr);
6091 case AttributeList::AT_ObjCReturnsInnerPointer:
6092 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6094 case AttributeList::AT_ObjCRequiresSuper:
6095 handleObjCRequiresSuperAttr(S, D, Attr);
6097 case AttributeList::AT_ObjCBridge:
6098 handleObjCBridgeAttr(S, scope, D, Attr);
6100 case AttributeList::AT_ObjCBridgeMutable:
6101 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6103 case AttributeList::AT_ObjCBridgeRelated:
6104 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6106 case AttributeList::AT_ObjCDesignatedInitializer:
6107 handleObjCDesignatedInitializer(S, D, Attr);
6109 case AttributeList::AT_ObjCRuntimeName:
6110 handleObjCRuntimeName(S, D, Attr);
6112 case AttributeList::AT_ObjCRuntimeVisible:
6113 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6115 case AttributeList::AT_ObjCBoxable:
6116 handleObjCBoxable(S, D, Attr);
6118 case AttributeList::AT_CFAuditedTransfer:
6119 handleCFAuditedTransferAttr(S, D, Attr);
6121 case AttributeList::AT_CFUnknownTransfer:
6122 handleCFUnknownTransferAttr(S, D, Attr);
6124 case AttributeList::AT_CFConsumed:
6125 case AttributeList::AT_NSConsumed:
6126 handleNSConsumedAttr(S, D, Attr);
6128 case AttributeList::AT_NSConsumesSelf:
6129 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6131 case AttributeList::AT_NSReturnsAutoreleased:
6132 case AttributeList::AT_NSReturnsNotRetained:
6133 case AttributeList::AT_CFReturnsNotRetained:
6134 case AttributeList::AT_NSReturnsRetained:
6135 case AttributeList::AT_CFReturnsRetained:
6136 handleNSReturnsRetainedAttr(S, D, Attr);
6138 case AttributeList::AT_WorkGroupSizeHint:
6139 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6141 case AttributeList::AT_ReqdWorkGroupSize:
6142 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6144 case AttributeList::AT_VecTypeHint:
6145 handleVecTypeHint(S, D, Attr);
6147 case AttributeList::AT_RequireConstantInit:
6148 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6150 case AttributeList::AT_InitPriority:
6151 handleInitPriorityAttr(S, D, Attr);
6153 case AttributeList::AT_Packed:
6154 handlePackedAttr(S, D, Attr);
6156 case AttributeList::AT_Section:
6157 handleSectionAttr(S, D, Attr);
6159 case AttributeList::AT_Target:
6160 handleTargetAttr(S, D, Attr);
6162 case AttributeList::AT_Unavailable:
6163 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
6165 case AttributeList::AT_ArcWeakrefUnavailable:
6166 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6168 case AttributeList::AT_ObjCRootClass:
6169 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6171 case AttributeList::AT_ObjCSubclassingRestricted:
6172 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6174 case AttributeList::AT_ObjCExplicitProtocolImpl:
6175 handleObjCSuppresProtocolAttr(S, D, Attr);
6177 case AttributeList::AT_ObjCRequiresPropertyDefs:
6178 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6180 case AttributeList::AT_Unused:
6181 handleUnusedAttr(S, D, Attr);
6183 case AttributeList::AT_ReturnsTwice:
6184 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6186 case AttributeList::AT_NotTailCalled:
6187 handleNotTailCalledAttr(S, D, Attr);
6189 case AttributeList::AT_DisableTailCalls:
6190 handleDisableTailCallsAttr(S, D, Attr);
6192 case AttributeList::AT_Used:
6193 handleUsedAttr(S, D, Attr);
6195 case AttributeList::AT_Visibility:
6196 handleVisibilityAttr(S, D, Attr, false);
6198 case AttributeList::AT_TypeVisibility:
6199 handleVisibilityAttr(S, D, Attr, true);
6201 case AttributeList::AT_WarnUnused:
6202 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6204 case AttributeList::AT_WarnUnusedResult:
6205 handleWarnUnusedResult(S, D, Attr);
6207 case AttributeList::AT_Weak:
6208 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6210 case AttributeList::AT_WeakRef:
6211 handleWeakRefAttr(S, D, Attr);
6213 case AttributeList::AT_WeakImport:
6214 handleWeakImportAttr(S, D, Attr);
6216 case AttributeList::AT_TransparentUnion:
6217 handleTransparentUnionAttr(S, D, Attr);
6219 case AttributeList::AT_ObjCException:
6220 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6222 case AttributeList::AT_ObjCMethodFamily:
6223 handleObjCMethodFamilyAttr(S, D, Attr);
6225 case AttributeList::AT_ObjCNSObject:
6226 handleObjCNSObject(S, D, Attr);
6228 case AttributeList::AT_ObjCIndependentClass:
6229 handleObjCIndependentClass(S, D, Attr);
6231 case AttributeList::AT_Blocks:
6232 handleBlocksAttr(S, D, Attr);
6234 case AttributeList::AT_Sentinel:
6235 handleSentinelAttr(S, D, Attr);
6237 case AttributeList::AT_Const:
6238 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6240 case AttributeList::AT_Pure:
6241 handleSimpleAttribute<PureAttr>(S, D, Attr);
6243 case AttributeList::AT_Cleanup:
6244 handleCleanupAttr(S, D, Attr);
6246 case AttributeList::AT_NoDebug:
6247 handleNoDebugAttr(S, D, Attr);
6249 case AttributeList::AT_NoDuplicate:
6250 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6252 case AttributeList::AT_Convergent:
6253 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6255 case AttributeList::AT_NoInline:
6256 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6258 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6259 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6261 case AttributeList::AT_StdCall:
6262 case AttributeList::AT_CDecl:
6263 case AttributeList::AT_FastCall:
6264 case AttributeList::AT_ThisCall:
6265 case AttributeList::AT_Pascal:
6266 case AttributeList::AT_RegCall:
6267 case AttributeList::AT_SwiftCall:
6268 case AttributeList::AT_VectorCall:
6269 case AttributeList::AT_MSABI:
6270 case AttributeList::AT_SysVABI:
6271 case AttributeList::AT_Pcs:
6272 case AttributeList::AT_IntelOclBicc:
6273 case AttributeList::AT_PreserveMost:
6274 case AttributeList::AT_PreserveAll:
6275 handleCallConvAttr(S, D, Attr);
6277 case AttributeList::AT_Suppress:
6278 handleSuppressAttr(S, D, Attr);
6280 case AttributeList::AT_OpenCLKernel:
6281 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6283 case AttributeList::AT_OpenCLAccess:
6284 handleOpenCLAccessAttr(S, D, Attr);
6286 case AttributeList::AT_OpenCLNoSVM:
6287 handleOpenCLNoSVMAttr(S, D, Attr);
6289 case AttributeList::AT_SwiftContext:
6290 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6292 case AttributeList::AT_SwiftErrorResult:
6293 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6295 case AttributeList::AT_SwiftIndirectResult:
6296 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6298 case AttributeList::AT_InternalLinkage:
6299 handleInternalLinkageAttr(S, D, Attr);
6301 case AttributeList::AT_LTOVisibilityPublic:
6302 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6305 // Microsoft attributes:
6306 case AttributeList::AT_EmptyBases:
6307 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6309 case AttributeList::AT_LayoutVersion:
6310 handleLayoutVersion(S, D, Attr);
6312 case AttributeList::AT_MSNoVTable:
6313 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
6315 case AttributeList::AT_MSStruct:
6316 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
6318 case AttributeList::AT_Uuid:
6319 handleUuidAttr(S, D, Attr);
6321 case AttributeList::AT_MSInheritance:
6322 handleMSInheritanceAttr(S, D, Attr);
6324 case AttributeList::AT_SelectAny:
6325 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6327 case AttributeList::AT_Thread:
6328 handleDeclspecThreadAttr(S, D, Attr);
6331 case AttributeList::AT_AbiTag:
6332 handleAbiTagAttr(S, D, Attr);
6335 // Thread safety attributes:
6336 case AttributeList::AT_AssertExclusiveLock:
6337 handleAssertExclusiveLockAttr(S, D, Attr);
6339 case AttributeList::AT_AssertSharedLock:
6340 handleAssertSharedLockAttr(S, D, Attr);
6342 case AttributeList::AT_GuardedVar:
6343 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6345 case AttributeList::AT_PtGuardedVar:
6346 handlePtGuardedVarAttr(S, D, Attr);
6348 case AttributeList::AT_ScopedLockable:
6349 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6351 case AttributeList::AT_NoSanitize:
6352 handleNoSanitizeAttr(S, D, Attr);
6354 case AttributeList::AT_NoSanitizeSpecific:
6355 handleNoSanitizeSpecificAttr(S, D, Attr);
6357 case AttributeList::AT_NoThreadSafetyAnalysis:
6358 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
6360 case AttributeList::AT_GuardedBy:
6361 handleGuardedByAttr(S, D, Attr);
6363 case AttributeList::AT_PtGuardedBy:
6364 handlePtGuardedByAttr(S, D, Attr);
6366 case AttributeList::AT_ExclusiveTrylockFunction:
6367 handleExclusiveTrylockFunctionAttr(S, D, Attr);
6369 case AttributeList::AT_LockReturned:
6370 handleLockReturnedAttr(S, D, Attr);
6372 case AttributeList::AT_LocksExcluded:
6373 handleLocksExcludedAttr(S, D, Attr);
6375 case AttributeList::AT_SharedTrylockFunction:
6376 handleSharedTrylockFunctionAttr(S, D, Attr);
6378 case AttributeList::AT_AcquiredBefore:
6379 handleAcquiredBeforeAttr(S, D, Attr);
6381 case AttributeList::AT_AcquiredAfter:
6382 handleAcquiredAfterAttr(S, D, Attr);
6385 // Capability analysis attributes.
6386 case AttributeList::AT_Capability:
6387 case AttributeList::AT_Lockable:
6388 handleCapabilityAttr(S, D, Attr);
6390 case AttributeList::AT_RequiresCapability:
6391 handleRequiresCapabilityAttr(S, D, Attr);
6394 case AttributeList::AT_AssertCapability:
6395 handleAssertCapabilityAttr(S, D, Attr);
6397 case AttributeList::AT_AcquireCapability:
6398 handleAcquireCapabilityAttr(S, D, Attr);
6400 case AttributeList::AT_ReleaseCapability:
6401 handleReleaseCapabilityAttr(S, D, Attr);
6403 case AttributeList::AT_TryAcquireCapability:
6404 handleTryAcquireCapabilityAttr(S, D, Attr);
6407 // Consumed analysis attributes.
6408 case AttributeList::AT_Consumable:
6409 handleConsumableAttr(S, D, Attr);
6411 case AttributeList::AT_ConsumableAutoCast:
6412 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6414 case AttributeList::AT_ConsumableSetOnRead:
6415 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6417 case AttributeList::AT_CallableWhen:
6418 handleCallableWhenAttr(S, D, Attr);
6420 case AttributeList::AT_ParamTypestate:
6421 handleParamTypestateAttr(S, D, Attr);
6423 case AttributeList::AT_ReturnTypestate:
6424 handleReturnTypestateAttr(S, D, Attr);
6426 case AttributeList::AT_SetTypestate:
6427 handleSetTypestateAttr(S, D, Attr);
6429 case AttributeList::AT_TestTypestate:
6430 handleTestTypestateAttr(S, D, Attr);
6433 // Type safety attributes.
6434 case AttributeList::AT_ArgumentWithTypeTag:
6435 handleArgumentWithTypeTagAttr(S, D, Attr);
6437 case AttributeList::AT_TypeTagForDatatype:
6438 handleTypeTagForDatatypeAttr(S, D, Attr);
6440 case AttributeList::AT_RenderScriptKernel:
6441 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
6444 case AttributeList::AT_XRayInstrument:
6445 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6447 case AttributeList::AT_XRayLogArgs:
6448 handleXRayLogArgsAttr(S, D, Attr);
6453 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6454 /// attribute list to the specified decl, ignoring any type attributes.
6455 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
6456 const AttributeList *AttrList,
6457 bool IncludeCXX11Attributes) {
6458 for (const AttributeList* l = AttrList; l; l = l->getNext())
6459 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
6461 // FIXME: We should be able to handle these cases in TableGen.
6463 // static int a9 __attribute__((weakref));
6464 // but that looks really pointless. We reject it.
6465 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
6466 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6467 << cast<NamedDecl>(D);
6468 D->dropAttr<WeakRefAttr>();
6472 // FIXME: We should be able to handle this in TableGen as well. It would be
6473 // good to have a way to specify "these attributes must appear as a group",
6474 // for these. Additionally, it would be good to have a way to specify "these
6475 // attribute must never appear as a group" for attributes like cold and hot.
6476 if (!D->hasAttr<OpenCLKernelAttr>()) {
6477 // These attributes cannot be applied to a non-kernel function.
6478 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
6479 // FIXME: This emits a different error message than
6480 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
6481 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6482 D->setInvalidDecl();
6483 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
6484 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6485 D->setInvalidDecl();
6486 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
6487 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6488 D->setInvalidDecl();
6489 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6490 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6491 << A << ExpectedKernelFunction;
6492 D->setInvalidDecl();
6493 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
6494 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6495 << A << ExpectedKernelFunction;
6496 D->setInvalidDecl();
6497 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6498 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6499 << A << ExpectedKernelFunction;
6500 D->setInvalidDecl();
6501 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6502 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6503 << A << ExpectedKernelFunction;
6504 D->setInvalidDecl();
6509 // Helper for delayed proccessing TransparentUnion attribute.
6510 void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6511 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6512 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6513 handleTransparentUnionAttr(*this, D, *Attr);
6518 // Annotation attributes are the only attributes allowed after an access
6520 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6521 const AttributeList *AttrList) {
6522 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6523 if (l->getKind() == AttributeList::AT_Annotate) {
6524 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
6526 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6534 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
6535 /// contains any decl attributes that we should warn about.
6536 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6537 for ( ; A; A = A->getNext()) {
6538 // Only warn if the attribute is an unignored, non-type attribute.
6539 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
6540 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6542 if (A->getKind() == AttributeList::UnknownAttribute) {
6543 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6544 << A->getName() << A->getRange();
6546 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6547 << A->getName() << A->getRange();
6552 /// checkUnusedDeclAttributes - Given a declarator which is not being
6553 /// used to build a declaration, complain about any decl attributes
6554 /// which might be lying around on it.
6555 void Sema::checkUnusedDeclAttributes(Declarator &D) {
6556 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6557 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6558 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6559 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6562 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
6563 /// \#pragma weak needs a non-definition decl and source may not have one.
6564 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6565 SourceLocation Loc) {
6566 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
6567 NamedDecl *NewD = nullptr;
6568 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6569 FunctionDecl *NewFD;
6570 // FIXME: Missing call to CheckFunctionDeclaration().
6572 // FIXME: Is the qualifier info correct?
6573 // FIXME: Is the DeclContext correct?
6574 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6575 Loc, Loc, DeclarationName(II),
6576 FD->getType(), FD->getTypeSourceInfo(),
6577 SC_None, false/*isInlineSpecified*/,
6579 false/*isConstexprSpecified*/);
6582 if (FD->getQualifier())
6583 NewFD->setQualifierInfo(FD->getQualifierLoc());
6585 // Fake up parameter variables; they are declared as if this were
6587 QualType FDTy = FD->getType();
6588 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6589 SmallVector<ParmVarDecl*, 16> Params;
6590 for (const auto &AI : FT->param_types()) {
6591 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6592 Param->setScopeInfo(0, Params.size());
6593 Params.push_back(Param);
6595 NewFD->setParams(Params);
6597 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6598 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6599 VD->getInnerLocStart(), VD->getLocation(), II,
6600 VD->getType(), VD->getTypeSourceInfo(),
6601 VD->getStorageClass());
6602 if (VD->getQualifier()) {
6603 VarDecl *NewVD = cast<VarDecl>(NewD);
6604 NewVD->setQualifierInfo(VD->getQualifierLoc());
6610 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6611 /// applied to it, possibly with an alias.
6612 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6613 if (W.getUsed()) return; // only do this once
6615 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6616 IdentifierInfo *NDId = ND->getIdentifier();
6617 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6618 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6620 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6621 WeakTopLevelDecl.push_back(NewD);
6622 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6623 // to insert Decl at TU scope, sorry.
6624 DeclContext *SavedContext = CurContext;
6625 CurContext = Context.getTranslationUnitDecl();
6626 NewD->setDeclContext(CurContext);
6627 NewD->setLexicalDeclContext(CurContext);
6628 PushOnScopeChains(NewD, S);
6629 CurContext = SavedContext;
6630 } else { // just add weak to existing
6631 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6635 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6636 // It's valid to "forward-declare" #pragma weak, in which case we
6638 LoadExternalWeakUndeclaredIdentifiers();
6639 if (!WeakUndeclaredIdentifiers.empty()) {
6640 NamedDecl *ND = nullptr;
6641 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6642 if (VD->isExternC())
6644 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6645 if (FD->isExternC())
6648 if (IdentifierInfo *Id = ND->getIdentifier()) {
6649 auto I = WeakUndeclaredIdentifiers.find(Id);
6650 if (I != WeakUndeclaredIdentifiers.end()) {
6651 WeakInfo W = I->second;
6652 DeclApplyPragmaWeak(S, ND, W);
6653 WeakUndeclaredIdentifiers[Id] = W;
6660 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6661 /// it, apply them to D. This is a bit tricky because PD can have attributes
6662 /// specified in many different places, and we need to find and apply them all.
6663 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6664 // Apply decl attributes from the DeclSpec if present.
6665 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6666 ProcessDeclAttributeList(S, D, Attrs);
6668 // Walk the declarator structure, applying decl attributes that were in a type
6669 // position to the decl itself. This handles cases like:
6670 // int *__attr__(x)** D;
6671 // when X is a decl attribute.
6672 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6673 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6674 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6676 // Finally, apply any attributes on the decl itself.
6677 if (const AttributeList *Attrs = PD.getAttributes())
6678 ProcessDeclAttributeList(S, D, Attrs);
6681 /// Is the given declaration allowed to use a forbidden type?
6682 /// If so, it'll still be annotated with an attribute that makes it
6683 /// illegal to actually use.
6684 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6685 const DelayedDiagnostic &diag,
6686 UnavailableAttr::ImplicitReason &reason) {
6687 // Private ivars are always okay. Unfortunately, people don't
6688 // always properly make their ivars private, even in system headers.
6689 // Plus we need to make fields okay, too.
6690 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6691 !isa<FunctionDecl>(decl))
6694 // Silently accept unsupported uses of __weak in both user and system
6695 // declarations when it's been disabled, for ease of integration with
6696 // -fno-objc-arc files. We do have to take some care against attempts
6697 // to define such things; for now, we've only done that for ivars
6699 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6700 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6701 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6702 reason = UnavailableAttr::IR_ForbiddenWeak;
6707 // Allow all sorts of things in system headers.
6708 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6709 // Currently, all the failures dealt with this way are due to ARC
6711 reason = UnavailableAttr::IR_ARCForbiddenType;
6718 /// Handle a delayed forbidden-type diagnostic.
6719 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6721 auto reason = UnavailableAttr::IR_None;
6722 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6723 assert(reason && "didn't set reason?");
6724 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6728 if (S.getLangOpts().ObjCAutoRefCount)
6729 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6730 // FIXME: we may want to suppress diagnostics for all
6731 // kind of forbidden type messages on unavailable functions.
6732 if (FD->hasAttr<UnavailableAttr>() &&
6733 diag.getForbiddenTypeDiagnostic() ==
6734 diag::err_arc_array_param_no_ownership) {
6735 diag.Triggered = true;
6740 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6741 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6742 diag.Triggered = true;
6745 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6747 // Check each AvailabilityAttr to find the one for this platform.
6748 for (const auto *A : D->attrs()) {
6749 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6750 // FIXME: this is copied from CheckAvailability. We should try to
6753 // Check if this is an App Extension "platform", and if so chop off
6754 // the suffix for matching with the actual platform.
6755 StringRef ActualPlatform = Avail->getPlatform()->getName();
6756 StringRef RealizedPlatform = ActualPlatform;
6757 if (Context.getLangOpts().AppExt) {
6758 size_t suffix = RealizedPlatform.rfind("_app_extension");
6759 if (suffix != StringRef::npos)
6760 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6763 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6765 // Match the platform name.
6766 if (RealizedPlatform == TargetPlatform)
6773 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6774 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6775 /// in a deprecated context, but not the other way around.
6776 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6777 VersionTuple DeclVersion,
6779 assert(K != AR_Available && "Expected an unavailable declaration here!");
6781 // Checks if we should emit the availability diagnostic in the context of C.
6782 auto CheckContext = [&](const Decl *C) {
6783 if (K == AR_NotYetIntroduced) {
6784 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6785 if (AA->getIntroduced() >= DeclVersion)
6787 } else if (K == AR_Deprecated)
6788 if (C->isDeprecated())
6791 if (C->isUnavailable())
6796 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6797 // on nested declarations in an @interface having the availability of the
6798 // interface when they really shouldn't: they are members of the enclosing
6799 // context, and can referenced from there.
6800 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6801 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6802 if (CheckContext(OrigCtx))
6805 // An implementation implicitly has the availability of the interface.
6806 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6807 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6808 if (CheckContext(Interface))
6811 // A category implicitly has the availability of the interface.
6812 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6813 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6814 if (CheckContext(Interface))
6819 if (CheckContext(Ctx))
6822 // An implementation implicitly has the availability of the interface.
6823 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6824 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6825 if (CheckContext(Interface))
6828 // A category implicitly has the availability of the interface.
6829 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6830 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6831 if (CheckContext(Interface))
6833 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6838 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
6839 Decl *Ctx, const NamedDecl *D,
6840 StringRef Message, SourceLocation Loc,
6841 const ObjCInterfaceDecl *UnknownObjCClass,
6842 const ObjCPropertyDecl *ObjCProperty,
6843 bool ObjCPropertyAccess) {
6844 // Diagnostics for deprecated or unavailable.
6845 unsigned diag, diag_message, diag_fwdclass_message;
6846 unsigned diag_available_here = diag::note_availability_specified_here;
6847 SourceLocation NoteLocation = D->getLocation();
6849 // Matches 'diag::note_property_attribute' options.
6850 unsigned property_note_select;
6852 // Matches diag::note_availability_specified_here.
6853 unsigned available_here_select_kind;
6855 VersionTuple DeclVersion;
6856 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6857 DeclVersion = AA->getIntroduced();
6859 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6864 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6865 : diag::warn_property_method_deprecated;
6866 diag_message = diag::warn_deprecated_message;
6867 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6868 property_note_select = /* deprecated */ 0;
6869 available_here_select_kind = /* deprecated */ 2;
6870 if (const auto *attr = D->getAttr<DeprecatedAttr>())
6871 NoteLocation = attr->getLocation();
6874 case AR_Unavailable:
6875 diag = !ObjCPropertyAccess ? diag::err_unavailable
6876 : diag::err_property_method_unavailable;
6877 diag_message = diag::err_unavailable_message;
6878 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6879 property_note_select = /* unavailable */ 1;
6880 available_here_select_kind = /* unavailable */ 0;
6882 if (auto attr = D->getAttr<UnavailableAttr>()) {
6883 if (attr->isImplicit() && attr->getImplicitReason()) {
6884 // Most of these failures are due to extra restrictions in ARC;
6885 // reflect that in the primary diagnostic when applicable.
6886 auto flagARCError = [&] {
6887 if (S.getLangOpts().ObjCAutoRefCount &&
6888 S.getSourceManager().isInSystemHeader(D->getLocation()))
6889 diag = diag::err_unavailable_in_arc;
6892 switch (attr->getImplicitReason()) {
6893 case UnavailableAttr::IR_None: break;
6895 case UnavailableAttr::IR_ARCForbiddenType:
6897 diag_available_here = diag::note_arc_forbidden_type;
6900 case UnavailableAttr::IR_ForbiddenWeak:
6901 if (S.getLangOpts().ObjCWeakRuntime)
6902 diag_available_here = diag::note_arc_weak_disabled;
6904 diag_available_here = diag::note_arc_weak_no_runtime;
6907 case UnavailableAttr::IR_ARCForbiddenConversion:
6909 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6912 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6914 diag_available_here = diag::note_arc_init_returns_unrelated;
6917 case UnavailableAttr::IR_ARCFieldWithOwnership:
6919 diag_available_here = diag::note_arc_field_with_ownership;
6926 case AR_NotYetIntroduced:
6927 diag = diag::warn_partial_availability;
6928 diag_message = diag::warn_partial_message;
6929 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6930 property_note_select = /* partial */ 2;
6931 available_here_select_kind = /* partial */ 3;
6935 llvm_unreachable("Warning for availability of available declaration?");
6938 CharSourceRange UseRange;
6939 StringRef Replacement;
6940 if (K == AR_Deprecated) {
6941 if (auto attr = D->getAttr<DeprecatedAttr>())
6942 Replacement = attr->getReplacement();
6943 if (auto attr = getAttrForPlatform(S.Context, D))
6944 Replacement = attr->getReplacement();
6946 if (!Replacement.empty())
6948 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6951 if (!Message.empty()) {
6952 S.Diag(Loc, diag_message) << D << Message
6953 << (UseRange.isValid() ?
6954 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6956 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6957 << ObjCProperty->getDeclName() << property_note_select;
6958 } else if (!UnknownObjCClass) {
6959 S.Diag(Loc, diag) << D
6960 << (UseRange.isValid() ?
6961 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6963 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6964 << ObjCProperty->getDeclName() << property_note_select;
6966 S.Diag(Loc, diag_fwdclass_message) << D
6967 << (UseRange.isValid() ?
6968 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6969 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6972 // The declaration can have multiple availability attributes, we are looking
6974 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6975 if (A && A->isInherited()) {
6976 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6977 Redecl = Redecl->getPreviousDecl()) {
6978 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6980 if (AForRedecl && !AForRedecl->isInherited()) {
6981 // If D is a declaration with inherited attributes, the note should
6982 // point to the declaration with actual attributes.
6983 S.Diag(Redecl->getLocation(), diag_available_here) << D
6984 << available_here_select_kind;
6990 S.Diag(NoteLocation, diag_available_here)
6991 << D << available_here_select_kind;
6993 if (K == AR_NotYetIntroduced)
6994 S.Diag(Loc, diag::note_partial_availability_silence) << D;
6997 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6999 assert(DD.Kind == DelayedDiagnostic::Availability &&
7000 "Expected an availability diagnostic here");
7002 DD.Triggered = true;
7003 DoEmitAvailabilityWarning(
7004 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
7005 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
7006 DD.getObjCProperty(), false);
7009 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7010 assert(DelayedDiagnostics.getCurrentPool());
7011 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7012 DelayedDiagnostics.popWithoutEmitting(state);
7014 // When delaying diagnostics to run in the context of a parsed
7015 // declaration, we only want to actually emit anything if parsing
7019 // We emit all the active diagnostics in this pool or any of its
7020 // parents. In general, we'll get one pool for the decl spec
7021 // and a child pool for each declarator; in a decl group like:
7022 // deprecated_typedef foo, *bar, baz();
7023 // only the declarator pops will be passed decls. This is correct;
7024 // we really do need to consider delayed diagnostics from the decl spec
7025 // for each of the different declarations.
7026 const DelayedDiagnosticPool *pool = &poppedPool;
7028 for (DelayedDiagnosticPool::pool_iterator
7029 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7030 // This const_cast is a bit lame. Really, Triggered should be mutable.
7031 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7035 switch (diag.Kind) {
7036 case DelayedDiagnostic::Availability:
7037 // Don't bother giving deprecation/unavailable diagnostics if
7038 // the decl is invalid.
7039 if (!decl->isInvalidDecl())
7040 handleDelayedAvailabilityCheck(*this, diag, decl);
7043 case DelayedDiagnostic::Access:
7044 HandleDelayedAccessCheck(diag, decl);
7047 case DelayedDiagnostic::ForbiddenType:
7048 handleDelayedForbiddenType(*this, diag, decl);
7052 } while ((pool = pool->getParent()));
7055 /// Given a set of delayed diagnostics, re-emit them as if they had
7056 /// been delayed in the current context instead of in the given pool.
7057 /// Essentially, this just moves them to the current pool.
7058 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7059 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7060 assert(curPool && "re-emitting in undelayed context not supported");
7061 curPool->steal(pool);
7064 void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
7065 NamedDecl *D, StringRef Message,
7067 const ObjCInterfaceDecl *UnknownObjCClass,
7068 const ObjCPropertyDecl *ObjCProperty,
7069 bool ObjCPropertyAccess) {
7070 // Delay if we're currently parsing a declaration.
7071 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
7072 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
7073 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
7074 ObjCPropertyAccess));
7078 Decl *Ctx = cast<Decl>(getCurLexicalContext());
7079 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
7080 ObjCProperty, ObjCPropertyAccess);
7085 /// \brief This class implements -Wunguarded-availability.
7087 /// This is done with a traversal of the AST of a function that makes reference
7088 /// to a partially available declaration. Whenever we encounter an \c if of the
7089 /// form: \c if(@available(...)), we use the version from the condition to visit
7090 /// the then statement.
7091 class DiagnoseUnguardedAvailability
7092 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7093 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7098 /// Stack of potentially nested 'if (@available(...))'s.
7099 SmallVector<VersionTuple, 8> AvailabilityStack;
7101 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7104 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7105 : SemaRef(SemaRef), Ctx(Ctx) {
7106 AvailabilityStack.push_back(
7107 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
7110 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7112 bool TraverseIfStmt(IfStmt *If);
7114 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7115 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7116 DiagnoseDeclAvailability(
7117 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7121 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7122 DiagnoseDeclAvailability(DRE->getDecl(),
7123 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7127 bool VisitMemberExpr(MemberExpr *ME) {
7128 DiagnoseDeclAvailability(ME->getMemberDecl(),
7129 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7133 bool VisitTypeLoc(TypeLoc Ty);
7136 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7137 NamedDecl *D, SourceRange Range) {
7139 VersionTuple ContextVersion = AvailabilityStack.back();
7140 if (AvailabilityResult Result =
7141 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
7142 // All other diagnostic kinds have already been handled in
7143 // DiagnoseAvailabilityOfDecl.
7144 if (Result != AR_NotYetIntroduced)
7147 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
7148 VersionTuple Introduced = AA->getIntroduced();
7150 if (ContextVersion >= Introduced)
7153 // If the context of this function is less available than D, we should not
7154 // emit a diagnostic.
7155 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7158 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
7160 << AvailabilityAttr::getPrettyPlatformName(
7161 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7162 << Introduced.getAsString();
7164 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
7165 << D << /* partial */ 3;
7167 // FIXME: Replace this with a fixit diagnostic.
7168 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7173 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7174 const Type *TyPtr = Ty.getTypePtr();
7175 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7177 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7178 TagDecl *TD = TT->getDecl();
7179 DiagnoseDeclAvailability(TD, Range);
7181 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7182 TypedefNameDecl *D = TD->getDecl();
7183 DiagnoseDeclAvailability(D, Range);
7185 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7186 if (NamedDecl *D = ObjCO->getInterface())
7187 DiagnoseDeclAvailability(D, Range);
7193 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7194 VersionTuple CondVersion;
7195 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7196 CondVersion = E->getVersion();
7198 // If we're using the '*' case here or if this check is redundant, then we
7199 // use the enclosing version to check both branches.
7200 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7201 return Base::TraverseStmt(If->getThen()) &&
7202 Base::TraverseStmt(If->getElse());
7204 // This isn't an availability checking 'if', we can just continue.
7205 return Base::TraverseIfStmt(If);
7208 AvailabilityStack.push_back(CondVersion);
7209 bool ShouldContinue = TraverseStmt(If->getThen());
7210 AvailabilityStack.pop_back();
7212 return ShouldContinue && TraverseStmt(If->getElse());
7215 } // end anonymous namespace
7217 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7218 Stmt *Body = nullptr;
7220 if (auto *FD = D->getAsFunction()) {
7221 // FIXME: We only examine the pattern decl for availability violations now,
7222 // but we should also examine instantiated templates.
7223 if (FD->isTemplateInstantiation())
7226 Body = FD->getBody();
7227 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7228 Body = MD->getBody();
7230 assert(Body && "Need a body here!");
7232 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);