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);
2401 if (!ND) // We warned about this already, so just return.
2404 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2405 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2406 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2407 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2408 bool IsStrict = Attr.getStrictLoc().isValid();
2410 if (const StringLiteral *SE =
2411 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2412 Str = SE->getString();
2413 StringRef Replacement;
2414 if (const StringLiteral *SE =
2415 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2416 Replacement = SE->getString();
2418 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2424 IsStrict, Replacement,
2428 D->addAttr(NewAttr);
2430 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2431 // matches before the start of the watchOS platform.
2432 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2433 IdentifierInfo *NewII = nullptr;
2434 if (II->getName() == "ios")
2435 NewII = &S.Context.Idents.get("watchos");
2436 else if (II->getName() == "ios_app_extension")
2437 NewII = &S.Context.Idents.get("watchos_app_extension");
2440 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2441 if (Version.empty())
2443 auto Major = Version.getMajor();
2444 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2445 if (NewMajor >= 2) {
2446 if (Version.getMinor().hasValue()) {
2447 if (Version.getSubminor().hasValue())
2448 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2449 Version.getSubminor().getValue());
2451 return VersionTuple(NewMajor, Version.getMinor().getValue());
2455 return VersionTuple(2, 0);
2458 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2459 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2460 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2462 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2475 D->addAttr(NewAttr);
2477 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2478 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2479 // matches before the start of the tvOS platform.
2480 IdentifierInfo *NewII = nullptr;
2481 if (II->getName() == "ios")
2482 NewII = &S.Context.Idents.get("tvos");
2483 else if (II->getName() == "ios_app_extension")
2484 NewII = &S.Context.Idents.get("tvos_app_extension");
2487 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2500 D->addAttr(NewAttr);
2505 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2506 const AttributeList &Attr) {
2507 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
2509 assert(checkAttributeAtMostNumArgs(S, Attr, 3) &&
2510 "Invalid number of arguments in an external_source_symbol attribute");
2513 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(0)))
2514 Language = SE->getString();
2515 StringRef DefinedIn;
2516 if (const auto *SE = dyn_cast_or_null<StringLiteral>(Attr.getArgAsExpr(1)))
2517 DefinedIn = SE->getString();
2518 bool IsGeneratedDeclaration = Attr.getArgAsIdent(2) != nullptr;
2520 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2521 Attr.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2522 Attr.getAttributeSpellingListIndex()));
2526 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2527 typename T::VisibilityType value,
2528 unsigned attrSpellingListIndex) {
2529 T *existingAttr = D->getAttr<T>();
2531 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2532 if (existingValue == value)
2534 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2535 S.Diag(range.getBegin(), diag::note_previous_attribute);
2538 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2541 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2542 VisibilityAttr::VisibilityType Vis,
2543 unsigned AttrSpellingListIndex) {
2544 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2545 AttrSpellingListIndex);
2548 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2549 TypeVisibilityAttr::VisibilityType Vis,
2550 unsigned AttrSpellingListIndex) {
2551 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2552 AttrSpellingListIndex);
2555 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2556 bool isTypeVisibility) {
2557 // Visibility attributes don't mean anything on a typedef.
2558 if (isa<TypedefNameDecl>(D)) {
2559 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2564 // 'type_visibility' can only go on a type or namespace.
2565 if (isTypeVisibility &&
2566 !(isa<TagDecl>(D) ||
2567 isa<ObjCInterfaceDecl>(D) ||
2568 isa<NamespaceDecl>(D))) {
2569 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2570 << Attr.getName() << ExpectedTypeOrNamespace;
2574 // Check that the argument is a string literal.
2576 SourceLocation LiteralLoc;
2577 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2580 VisibilityAttr::VisibilityType type;
2581 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2582 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2583 << Attr.getName() << TypeStr;
2587 // Complain about attempts to use protected visibility on targets
2588 // (like Darwin) that don't support it.
2589 if (type == VisibilityAttr::Protected &&
2590 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2591 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2592 type = VisibilityAttr::Default;
2595 unsigned Index = Attr.getAttributeSpellingListIndex();
2596 clang::Attr *newAttr;
2597 if (isTypeVisibility) {
2598 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2599 (TypeVisibilityAttr::VisibilityType) type,
2602 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2605 D->addAttr(newAttr);
2608 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2609 const AttributeList &Attr) {
2610 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2611 if (!Attr.isArgIdent(0)) {
2612 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2613 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2617 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2618 ObjCMethodFamilyAttr::FamilyKind F;
2619 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2620 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2625 if (F == ObjCMethodFamilyAttr::OMF_init &&
2626 !method->getReturnType()->isObjCObjectPointerType()) {
2627 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2628 << method->getReturnType();
2629 // Ignore the attribute.
2633 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2635 Attr.getAttributeSpellingListIndex()));
2638 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2639 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2640 QualType T = TD->getUnderlyingType();
2641 if (!T->isCARCBridgableType()) {
2642 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2646 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2647 QualType T = PD->getType();
2648 if (!T->isCARCBridgableType()) {
2649 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2654 // It is okay to include this attribute on properties, e.g.:
2656 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2658 // In this case it follows tradition and suppresses an error in the above
2660 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2662 D->addAttr(::new (S.Context)
2663 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2664 Attr.getAttributeSpellingListIndex()));
2667 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2668 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2669 QualType T = TD->getUnderlyingType();
2670 if (!T->isObjCObjectPointerType()) {
2671 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2675 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2678 D->addAttr(::new (S.Context)
2679 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2680 Attr.getAttributeSpellingListIndex()));
2683 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2684 if (!Attr.isArgIdent(0)) {
2685 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2686 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2690 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2691 BlocksAttr::BlockType type;
2692 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2693 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2694 << Attr.getName() << II;
2698 D->addAttr(::new (S.Context)
2699 BlocksAttr(Attr.getRange(), S.Context, type,
2700 Attr.getAttributeSpellingListIndex()));
2703 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2704 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2705 if (Attr.getNumArgs() > 0) {
2706 Expr *E = Attr.getArgAsExpr(0);
2707 llvm::APSInt Idx(32);
2708 if (E->isTypeDependent() || E->isValueDependent() ||
2709 !E->isIntegerConstantExpr(Idx, S.Context)) {
2710 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2711 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2712 << E->getSourceRange();
2716 if (Idx.isSigned() && Idx.isNegative()) {
2717 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2718 << E->getSourceRange();
2722 sentinel = Idx.getZExtValue();
2725 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2726 if (Attr.getNumArgs() > 1) {
2727 Expr *E = Attr.getArgAsExpr(1);
2728 llvm::APSInt Idx(32);
2729 if (E->isTypeDependent() || E->isValueDependent() ||
2730 !E->isIntegerConstantExpr(Idx, S.Context)) {
2731 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2732 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2733 << E->getSourceRange();
2736 nullPos = Idx.getZExtValue();
2738 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2739 // FIXME: This error message could be improved, it would be nice
2740 // to say what the bounds actually are.
2741 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2742 << E->getSourceRange();
2747 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2748 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2749 if (isa<FunctionNoProtoType>(FT)) {
2750 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2754 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2755 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2758 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2759 if (!MD->isVariadic()) {
2760 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2763 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2764 if (!BD->isVariadic()) {
2765 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2768 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2769 QualType Ty = V->getType();
2770 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2771 const FunctionType *FT = Ty->isFunctionPointerType()
2772 ? D->getFunctionType()
2773 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2774 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2775 int m = Ty->isFunctionPointerType() ? 0 : 1;
2776 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2780 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2781 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2785 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2786 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2789 D->addAttr(::new (S.Context)
2790 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2791 Attr.getAttributeSpellingListIndex()));
2794 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2795 if (D->getFunctionType() &&
2796 D->getFunctionType()->getReturnType()->isVoidType()) {
2797 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2798 << Attr.getName() << 0;
2801 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2802 if (MD->getReturnType()->isVoidType()) {
2803 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2804 << Attr.getName() << 1;
2808 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2809 // about using it as an extension.
2810 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2811 !Attr.getScopeName())
2812 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2814 D->addAttr(::new (S.Context)
2815 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2816 Attr.getAttributeSpellingListIndex()));
2819 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2820 // weak_import only applies to variable & function declarations.
2822 if (!D->canBeWeakImported(isDef)) {
2824 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2826 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2827 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2828 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2829 // Nothing to warn about here.
2831 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2832 << Attr.getName() << ExpectedVariableOrFunction;
2837 D->addAttr(::new (S.Context)
2838 WeakImportAttr(Attr.getRange(), S.Context,
2839 Attr.getAttributeSpellingListIndex()));
2842 // Handles reqd_work_group_size and work_group_size_hint.
2843 template <typename WorkGroupAttr>
2844 static void handleWorkGroupSize(Sema &S, Decl *D,
2845 const AttributeList &Attr) {
2847 for (unsigned i = 0; i < 3; ++i) {
2848 const Expr *E = Attr.getArgAsExpr(i);
2849 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2851 if (WGSize[i] == 0) {
2852 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2853 << Attr.getName() << E->getSourceRange();
2858 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2859 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2860 Existing->getYDim() == WGSize[1] &&
2861 Existing->getZDim() == WGSize[2]))
2862 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2864 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2865 WGSize[0], WGSize[1], WGSize[2],
2866 Attr.getAttributeSpellingListIndex()));
2869 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2870 if (!Attr.hasParsedType()) {
2871 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2872 << Attr.getName() << 1;
2876 TypeSourceInfo *ParmTSI = nullptr;
2877 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2878 assert(ParmTSI && "no type source info for attribute argument");
2880 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2881 (ParmType->isBooleanType() ||
2882 !ParmType->isIntegralType(S.getASTContext()))) {
2883 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2888 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2889 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2890 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2895 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2897 Attr.getAttributeSpellingListIndex()));
2900 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2902 unsigned AttrSpellingListIndex) {
2903 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2904 if (ExistingAttr->getName() == Name)
2906 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2907 Diag(Range.getBegin(), diag::note_previous_attribute);
2910 return ::new (Context) SectionAttr(Range, Context, Name,
2911 AttrSpellingListIndex);
2914 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2915 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2916 if (!Error.empty()) {
2917 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2923 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2924 // Make sure that there is a string literal as the sections's single
2927 SourceLocation LiteralLoc;
2928 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2931 if (!S.checkSectionName(LiteralLoc, Str))
2934 // If the target wants to validate the section specifier, make it happen.
2935 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2936 if (!Error.empty()) {
2937 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2942 unsigned Index = Attr.getAttributeSpellingListIndex();
2943 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2945 D->addAttr(NewAttr);
2948 // Check for things we'd like to warn about, no errors or validation for now.
2949 // TODO: Validation should use a backend target library that specifies
2950 // the allowable subtarget features and cpus. We could use something like a
2951 // TargetCodeGenInfo hook here to do validation.
2952 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2953 for (auto Str : {"tune=", "fpmath="})
2954 if (AttrStr.find(Str) != StringRef::npos)
2955 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2958 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2960 SourceLocation LiteralLoc;
2961 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2963 S.checkTargetAttr(LiteralLoc, Str);
2964 unsigned Index = Attr.getAttributeSpellingListIndex();
2965 TargetAttr *NewAttr =
2966 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2967 D->addAttr(NewAttr);
2970 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2971 VarDecl *VD = cast<VarDecl>(D);
2972 if (!VD->hasLocalStorage()) {
2973 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2977 Expr *E = Attr.getArgAsExpr(0);
2978 SourceLocation Loc = E->getExprLoc();
2979 FunctionDecl *FD = nullptr;
2980 DeclarationNameInfo NI;
2982 // gcc only allows for simple identifiers. Since we support more than gcc, we
2983 // will warn the user.
2984 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2985 if (DRE->hasQualifier())
2986 S.Diag(Loc, diag::warn_cleanup_ext);
2987 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2988 NI = DRE->getNameInfo();
2990 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2994 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2995 if (ULE->hasExplicitTemplateArgs())
2996 S.Diag(Loc, diag::warn_cleanup_ext);
2997 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2998 NI = ULE->getNameInfo();
3000 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3002 if (ULE->getType() == S.Context.OverloadTy)
3003 S.NoteAllOverloadCandidates(ULE);
3007 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3011 if (FD->getNumParams() != 1) {
3012 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3017 // We're currently more strict than GCC about what function types we accept.
3018 // If this ever proves to be a problem it should be easy to fix.
3019 QualType Ty = S.Context.getPointerType(VD->getType());
3020 QualType ParamTy = FD->getParamDecl(0)->getType();
3021 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3022 ParamTy, Ty) != Sema::Compatible) {
3023 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3024 << NI.getName() << ParamTy << Ty;
3028 D->addAttr(::new (S.Context)
3029 CleanupAttr(Attr.getRange(), S.Context, FD,
3030 Attr.getAttributeSpellingListIndex()));
3033 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3034 const AttributeList &Attr) {
3035 if (!Attr.isArgIdent(0)) {
3036 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3037 << Attr.getName() << 0 << AANT_ArgumentIdentifier;
3041 EnumExtensibilityAttr::Kind ExtensibilityKind;
3042 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3043 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3044 ExtensibilityKind)) {
3045 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3046 << Attr.getName() << II;
3050 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3051 Attr.getRange(), S.Context, ExtensibilityKind,
3052 Attr.getAttributeSpellingListIndex()));
3055 /// Handle __attribute__((format_arg((idx)))) attribute based on
3056 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3057 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3058 Expr *IdxExpr = Attr.getArgAsExpr(0);
3060 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
3063 // Make sure the format string is really a string.
3064 QualType Ty = getFunctionOrMethodParamType(D, Idx);
3066 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3067 if (NotNSStringTy &&
3068 !isCFStringType(Ty, S.Context) &&
3069 (!Ty->isPointerType() ||
3070 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3071 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3072 << "a string type" << IdxExpr->getSourceRange()
3073 << getFunctionOrMethodParamRange(D, 0);
3076 Ty = getFunctionOrMethodResultType(D);
3077 if (!isNSStringType(Ty, S.Context) &&
3078 !isCFStringType(Ty, S.Context) &&
3079 (!Ty->isPointerType() ||
3080 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3081 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
3082 << (NotNSStringTy ? "string type" : "NSString")
3083 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3087 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
3088 // because that has corrected for the implicit this parameter, and is zero-
3089 // based. The attribute expects what the user wrote explicitly.
3091 IdxExpr->EvaluateAsInt(Val, S.Context);
3093 D->addAttr(::new (S.Context)
3094 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
3095 Attr.getAttributeSpellingListIndex()));
3098 enum FormatAttrKind {
3107 /// getFormatAttrKind - Map from format attribute names to supported format
3109 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3110 return llvm::StringSwitch<FormatAttrKind>(Format)
3111 // Check for formats that get handled specially.
3112 .Case("NSString", NSStringFormat)
3113 .Case("CFString", CFStringFormat)
3114 .Case("strftime", StrftimeFormat)
3116 // Otherwise, check for supported formats.
3117 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3118 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3119 .Case("kprintf", SupportedFormat) // OpenBSD.
3120 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3121 .Case("os_trace", SupportedFormat)
3122 .Case("os_log", SupportedFormat)
3124 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3125 .Default(InvalidFormat);
3128 /// Handle __attribute__((init_priority(priority))) attributes based on
3129 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3130 static void handleInitPriorityAttr(Sema &S, Decl *D,
3131 const AttributeList &Attr) {
3132 if (!S.getLangOpts().CPlusPlus) {
3133 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3137 if (S.getCurFunctionOrMethodDecl()) {
3138 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3142 QualType T = cast<VarDecl>(D)->getType();
3143 if (S.Context.getAsArrayType(T))
3144 T = S.Context.getBaseElementType(T);
3145 if (!T->getAs<RecordType>()) {
3146 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3151 Expr *E = Attr.getArgAsExpr(0);
3152 uint32_t prioritynum;
3153 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
3158 if (prioritynum < 101 || prioritynum > 65535) {
3159 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3160 << E->getSourceRange() << Attr.getName() << 101 << 65535;
3164 D->addAttr(::new (S.Context)
3165 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3166 Attr.getAttributeSpellingListIndex()));
3169 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3170 IdentifierInfo *Format, int FormatIdx,
3172 unsigned AttrSpellingListIndex) {
3173 // Check whether we already have an equivalent format attribute.
3174 for (auto *F : D->specific_attrs<FormatAttr>()) {
3175 if (F->getType() == Format &&
3176 F->getFormatIdx() == FormatIdx &&
3177 F->getFirstArg() == FirstArg) {
3178 // If we don't have a valid location for this attribute, adopt the
3180 if (F->getLocation().isInvalid())
3186 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3187 FirstArg, AttrSpellingListIndex);
3190 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3191 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3192 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3193 if (!Attr.isArgIdent(0)) {
3194 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3195 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3199 // In C++ the implicit 'this' function parameter also counts, and they are
3200 // counted from one.
3201 bool HasImplicitThisParam = isInstanceMethod(D);
3202 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3204 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3205 StringRef Format = II->getName();
3207 if (normalizeName(Format)) {
3208 // If we've modified the string name, we need a new identifier for it.
3209 II = &S.Context.Idents.get(Format);
3212 // Check for supported formats.
3213 FormatAttrKind Kind = getFormatAttrKind(Format);
3215 if (Kind == IgnoredFormat)
3218 if (Kind == InvalidFormat) {
3219 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3220 << Attr.getName() << II->getName();
3224 // checks for the 2nd argument
3225 Expr *IdxExpr = Attr.getArgAsExpr(1);
3227 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3230 if (Idx < 1 || Idx > NumArgs) {
3231 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3232 << Attr.getName() << 2 << IdxExpr->getSourceRange();
3236 // FIXME: Do we need to bounds check?
3237 unsigned ArgIdx = Idx - 1;
3239 if (HasImplicitThisParam) {
3241 S.Diag(Attr.getLoc(),
3242 diag::err_format_attribute_implicit_this_format_string)
3243 << IdxExpr->getSourceRange();
3249 // make sure the format string is really a string
3250 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3252 if (Kind == CFStringFormat) {
3253 if (!isCFStringType(Ty, S.Context)) {
3254 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3255 << "a CFString" << IdxExpr->getSourceRange()
3256 << getFunctionOrMethodParamRange(D, ArgIdx);
3259 } else if (Kind == NSStringFormat) {
3260 // FIXME: do we need to check if the type is NSString*? What are the
3262 if (!isNSStringType(Ty, S.Context)) {
3263 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3264 << "an NSString" << IdxExpr->getSourceRange()
3265 << getFunctionOrMethodParamRange(D, ArgIdx);
3268 } else if (!Ty->isPointerType() ||
3269 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3270 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3271 << "a string type" << IdxExpr->getSourceRange()
3272 << getFunctionOrMethodParamRange(D, ArgIdx);
3276 // check the 3rd argument
3277 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3279 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3282 // check if the function is variadic if the 3rd argument non-zero
3283 if (FirstArg != 0) {
3284 if (isFunctionOrMethodVariadic(D)) {
3285 ++NumArgs; // +1 for ...
3287 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3292 // strftime requires FirstArg to be 0 because it doesn't read from any
3293 // variable the input is just the current time + the format string.
3294 if (Kind == StrftimeFormat) {
3295 if (FirstArg != 0) {
3296 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3297 << FirstArgExpr->getSourceRange();
3300 // if 0 it disables parameter checking (to use with e.g. va_list)
3301 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3302 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3303 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3307 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3309 Attr.getAttributeSpellingListIndex());
3311 D->addAttr(NewAttr);
3314 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3315 const AttributeList &Attr) {
3316 // Try to find the underlying union declaration.
3317 RecordDecl *RD = nullptr;
3318 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3319 if (TD && TD->getUnderlyingType()->isUnionType())
3320 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3322 RD = dyn_cast<RecordDecl>(D);
3324 if (!RD || !RD->isUnion()) {
3325 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3326 << Attr.getName() << ExpectedUnion;
3330 if (!RD->isCompleteDefinition()) {
3331 if (!RD->isBeingDefined())
3332 S.Diag(Attr.getLoc(),
3333 diag::warn_transparent_union_attribute_not_definition);
3337 RecordDecl::field_iterator Field = RD->field_begin(),
3338 FieldEnd = RD->field_end();
3339 if (Field == FieldEnd) {
3340 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3344 FieldDecl *FirstField = *Field;
3345 QualType FirstType = FirstField->getType();
3346 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3347 S.Diag(FirstField->getLocation(),
3348 diag::warn_transparent_union_attribute_floating)
3349 << FirstType->isVectorType() << FirstType;
3353 if (FirstType->isIncompleteType())
3355 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3356 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3357 for (; Field != FieldEnd; ++Field) {
3358 QualType FieldType = Field->getType();
3359 if (FieldType->isIncompleteType())
3361 // FIXME: this isn't fully correct; we also need to test whether the
3362 // members of the union would all have the same calling convention as the
3363 // first member of the union. Checking just the size and alignment isn't
3364 // sufficient (consider structs passed on the stack instead of in registers
3366 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3367 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3368 // Warn if we drop the attribute.
3369 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3370 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3371 : S.Context.getTypeAlign(FieldType);
3372 S.Diag(Field->getLocation(),
3373 diag::warn_transparent_union_attribute_field_size_align)
3374 << isSize << Field->getDeclName() << FieldBits;
3375 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3376 S.Diag(FirstField->getLocation(),
3377 diag::note_transparent_union_first_field_size_align)
3378 << isSize << FirstBits;
3383 RD->addAttr(::new (S.Context)
3384 TransparentUnionAttr(Attr.getRange(), S.Context,
3385 Attr.getAttributeSpellingListIndex()));
3388 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3389 // Make sure that there is a string literal as the annotation's single
3392 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3395 // Don't duplicate annotations that are already set.
3396 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3397 if (I->getAnnotation() == Str)
3401 D->addAttr(::new (S.Context)
3402 AnnotateAttr(Attr.getRange(), S.Context, Str,
3403 Attr.getAttributeSpellingListIndex()));
3406 static void handleAlignValueAttr(Sema &S, Decl *D,
3407 const AttributeList &Attr) {
3408 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3409 Attr.getAttributeSpellingListIndex());
3412 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3413 unsigned SpellingListIndex) {
3414 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3415 SourceLocation AttrLoc = AttrRange.getBegin();
3418 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3419 T = TD->getUnderlyingType();
3420 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3423 llvm_unreachable("Unknown decl type for align_value");
3425 if (!T->isDependentType() && !T->isAnyPointerType() &&
3426 !T->isReferenceType() && !T->isMemberPointerType()) {
3427 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3428 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3432 if (!E->isValueDependent()) {
3433 llvm::APSInt Alignment;
3435 = VerifyIntegerConstantExpression(E, &Alignment,
3436 diag::err_align_value_attribute_argument_not_int,
3437 /*AllowFold*/ false);
3438 if (ICE.isInvalid())
3441 if (!Alignment.isPowerOf2()) {
3442 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3443 << E->getSourceRange();
3447 D->addAttr(::new (Context)
3448 AlignValueAttr(AttrRange, Context, ICE.get(),
3449 SpellingListIndex));
3453 // Save dependent expressions in the AST to be instantiated.
3454 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3457 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3458 // check the attribute arguments.
3459 if (Attr.getNumArgs() > 1) {
3460 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3461 << Attr.getName() << 1;
3465 if (Attr.getNumArgs() == 0) {
3466 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3467 true, nullptr, Attr.getAttributeSpellingListIndex()));
3471 Expr *E = Attr.getArgAsExpr(0);
3472 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3473 S.Diag(Attr.getEllipsisLoc(),
3474 diag::err_pack_expansion_without_parameter_packs);
3478 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3481 if (E->isValueDependent()) {
3482 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3483 if (!TND->getUnderlyingType()->isDependentType()) {
3484 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3485 << E->getSourceRange();
3491 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3492 Attr.isPackExpansion());
3495 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3496 unsigned SpellingListIndex, bool IsPackExpansion) {
3497 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3498 SourceLocation AttrLoc = AttrRange.getBegin();
3500 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3501 if (TmpAttr.isAlignas()) {
3502 // C++11 [dcl.align]p1:
3503 // An alignment-specifier may be applied to a variable or to a class
3504 // data member, but it shall not be applied to a bit-field, a function
3505 // parameter, the formal parameter of a catch clause, or a variable
3506 // declared with the register storage class specifier. An
3507 // alignment-specifier may also be applied to the declaration of a class
3508 // or enumeration type.
3510 // An alignment attribute shall not be specified in a declaration of
3511 // a typedef, or a bit-field, or a function, or a parameter, or an
3512 // object declared with the register storage-class specifier.
3514 if (isa<ParmVarDecl>(D)) {
3516 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3517 if (VD->getStorageClass() == SC_Register)
3519 if (VD->isExceptionVariable())
3521 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3522 if (FD->isBitField())
3524 } else if (!isa<TagDecl>(D)) {
3525 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3526 << (TmpAttr.isC11() ? ExpectedVariableOrField
3527 : ExpectedVariableFieldOrTag);
3530 if (DiagKind != -1) {
3531 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3532 << &TmpAttr << DiagKind;
3537 if (E->isTypeDependent() || E->isValueDependent()) {
3538 // Save dependent expressions in the AST to be instantiated.
3539 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3540 AA->setPackExpansion(IsPackExpansion);
3545 // FIXME: Cache the number on the Attr object?
3546 llvm::APSInt Alignment;
3548 = VerifyIntegerConstantExpression(E, &Alignment,
3549 diag::err_aligned_attribute_argument_not_int,
3550 /*AllowFold*/ false);
3551 if (ICE.isInvalid())
3554 uint64_t AlignVal = Alignment.getZExtValue();
3556 // C++11 [dcl.align]p2:
3557 // -- if the constant expression evaluates to zero, the alignment
3558 // specifier shall have no effect
3560 // An alignment specification of zero has no effect.
3561 if (!(TmpAttr.isAlignas() && !Alignment)) {
3562 if (!llvm::isPowerOf2_64(AlignVal)) {
3563 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3564 << E->getSourceRange();
3569 // Alignment calculations can wrap around if it's greater than 2**28.
3570 unsigned MaxValidAlignment =
3571 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3573 if (AlignVal > MaxValidAlignment) {
3574 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3575 << E->getSourceRange();
3579 if (Context.getTargetInfo().isTLSSupported()) {
3580 unsigned MaxTLSAlign =
3581 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3583 auto *VD = dyn_cast<VarDecl>(D);
3584 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3585 VD->getTLSKind() != VarDecl::TLS_None) {
3586 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3587 << (unsigned)AlignVal << VD << MaxTLSAlign;
3592 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3593 ICE.get(), SpellingListIndex);
3594 AA->setPackExpansion(IsPackExpansion);
3598 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3599 unsigned SpellingListIndex, bool IsPackExpansion) {
3600 // FIXME: Cache the number on the Attr object if non-dependent?
3601 // FIXME: Perform checking of type validity
3602 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3604 AA->setPackExpansion(IsPackExpansion);
3608 void Sema::CheckAlignasUnderalignment(Decl *D) {
3609 assert(D->hasAttrs() && "no attributes on decl");
3611 QualType UnderlyingTy, DiagTy;
3612 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3613 UnderlyingTy = DiagTy = VD->getType();
3615 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3616 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3617 UnderlyingTy = ED->getIntegerType();
3619 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3622 // C++11 [dcl.align]p5, C11 6.7.5/4:
3623 // The combined effect of all alignment attributes in a declaration shall
3624 // not specify an alignment that is less strict than the alignment that
3625 // would otherwise be required for the entity being declared.
3626 AlignedAttr *AlignasAttr = nullptr;
3628 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3629 if (I->isAlignmentDependent())
3633 Align = std::max(Align, I->getAlignment(Context));
3636 if (AlignasAttr && Align) {
3637 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3638 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3639 if (NaturalAlign > RequestedAlign)
3640 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3641 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3645 bool Sema::checkMSInheritanceAttrOnDefinition(
3646 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3647 MSInheritanceAttr::Spelling SemanticSpelling) {
3648 assert(RD->hasDefinition() && "RD has no definition!");
3650 // We may not have seen base specifiers or any virtual methods yet. We will
3651 // have to wait until the record is defined to catch any mismatches.
3652 if (!RD->getDefinition()->isCompleteDefinition())
3655 // The unspecified model never matches what a definition could need.
3656 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3660 if (RD->calculateInheritanceModel() == SemanticSpelling)
3663 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3667 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3668 << 0 /*definition*/;
3669 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3670 << RD->getNameAsString();
3674 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3676 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3677 bool &IntegerMode, bool &ComplexMode) {
3679 ComplexMode = false;
3680 switch (Str.size()) {
3702 if (Str[1] == 'F') {
3703 IntegerMode = false;
3704 } else if (Str[1] == 'C') {
3705 IntegerMode = false;
3707 } else if (Str[1] != 'I') {
3712 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3713 // pointer on PIC16 and other embedded platforms.
3715 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3716 else if (Str == "byte")
3717 DestWidth = S.Context.getTargetInfo().getCharWidth();
3720 if (Str == "pointer")
3721 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3724 if (Str == "unwind_word")
3725 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3730 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3733 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3734 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3735 /// HImode, not an intermediate pointer.
3736 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3737 // This attribute isn't documented, but glibc uses it. It changes
3738 // the width of an int or unsigned int to the specified size.
3739 if (!Attr.isArgIdent(0)) {
3740 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3741 << AANT_ArgumentIdentifier;
3745 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3747 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3750 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3751 unsigned SpellingListIndex, bool InInstantiation) {
3752 StringRef Str = Name->getName();
3754 SourceLocation AttrLoc = AttrRange.getBegin();
3756 unsigned DestWidth = 0;
3757 bool IntegerMode = true;
3758 bool ComplexMode = false;
3759 llvm::APInt VectorSize(64, 0);
3760 if (Str.size() >= 4 && Str[0] == 'V') {
3761 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3762 size_t StrSize = Str.size();
3763 size_t VectorStringLength = 0;
3764 while ((VectorStringLength + 1) < StrSize &&
3765 isdigit(Str[VectorStringLength + 1]))
3766 ++VectorStringLength;
3767 if (VectorStringLength &&
3768 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3769 VectorSize.isPowerOf2()) {
3770 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3771 IntegerMode, ComplexMode);
3772 // Avoid duplicate warning from template instantiation.
3773 if (!InInstantiation)
3774 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3781 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3783 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3784 // and friends, at least with glibc.
3785 // FIXME: Make sure floating-point mappings are accurate
3786 // FIXME: Support XF and TF types
3788 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3793 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3794 OldTy = TD->getUnderlyingType();
3795 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3796 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3797 // Try to get type from enum declaration, default to int.
3798 OldTy = ED->getIntegerType();
3800 OldTy = Context.IntTy;
3802 OldTy = cast<ValueDecl>(D)->getType();
3804 if (OldTy->isDependentType()) {
3805 D->addAttr(::new (Context)
3806 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3810 // Base type can also be a vector type (see PR17453).
3811 // Distinguish between base type and base element type.
3812 QualType OldElemTy = OldTy;
3813 if (const VectorType *VT = OldTy->getAs<VectorType>())
3814 OldElemTy = VT->getElementType();
3816 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3817 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3818 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3819 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3820 VectorSize.getBoolValue()) {
3821 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3824 bool IntegralOrAnyEnumType =
3825 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3827 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3828 !IntegralOrAnyEnumType)
3829 Diag(AttrLoc, diag::err_mode_not_primitive);
3830 else if (IntegerMode) {
3831 if (!IntegralOrAnyEnumType)
3832 Diag(AttrLoc, diag::err_mode_wrong_type);
3833 } else if (ComplexMode) {
3834 if (!OldElemTy->isComplexType())
3835 Diag(AttrLoc, diag::err_mode_wrong_type);
3837 if (!OldElemTy->isFloatingType())
3838 Diag(AttrLoc, diag::err_mode_wrong_type);
3844 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3845 OldElemTy->isSignedIntegerType());
3847 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3849 if (NewElemTy.isNull()) {
3850 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3855 NewElemTy = Context.getComplexType(NewElemTy);
3858 QualType NewTy = NewElemTy;
3859 if (VectorSize.getBoolValue()) {
3860 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3861 VectorType::GenericVector);
3862 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3863 // Complex machine mode does not support base vector types.
3865 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3868 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3869 OldVT->getNumElements() /
3870 Context.getTypeSize(NewElemTy);
3872 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3875 if (NewTy.isNull()) {
3876 Diag(AttrLoc, diag::err_mode_wrong_type);
3880 // Install the new type.
3881 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3882 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3883 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3884 ED->setIntegerType(NewTy);
3886 cast<ValueDecl>(D)->setType(NewTy);
3888 D->addAttr(::new (Context)
3889 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3892 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3893 D->addAttr(::new (S.Context)
3894 NoDebugAttr(Attr.getRange(), S.Context,
3895 Attr.getAttributeSpellingListIndex()));
3898 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3899 IdentifierInfo *Ident,
3900 unsigned AttrSpellingListIndex) {
3901 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3902 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3903 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3907 if (D->hasAttr<AlwaysInlineAttr>())
3910 return ::new (Context) AlwaysInlineAttr(Range, Context,
3911 AttrSpellingListIndex);
3914 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3915 IdentifierInfo *Ident,
3916 unsigned AttrSpellingListIndex) {
3917 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3920 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3923 InternalLinkageAttr *
3924 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3925 IdentifierInfo *Ident,
3926 unsigned AttrSpellingListIndex) {
3927 if (auto VD = dyn_cast<VarDecl>(D)) {
3928 // Attribute applies to Var but not any subclass of it (like ParmVar,
3929 // ImplicitParm or VarTemplateSpecialization).
3930 if (VD->getKind() != Decl::Var) {
3931 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3932 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3933 : ExpectedVariableOrFunction);
3936 // Attribute does not apply to non-static local variables.
3937 if (VD->hasLocalStorage()) {
3938 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3943 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3946 return ::new (Context)
3947 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3950 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3951 unsigned AttrSpellingListIndex) {
3952 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3953 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3954 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3958 if (D->hasAttr<MinSizeAttr>())
3961 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3964 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3965 unsigned AttrSpellingListIndex) {
3966 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3967 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3968 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3969 D->dropAttr<AlwaysInlineAttr>();
3971 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3972 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3973 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3974 D->dropAttr<MinSizeAttr>();
3977 if (D->hasAttr<OptimizeNoneAttr>())
3980 return ::new (Context) OptimizeNoneAttr(Range, Context,
3981 AttrSpellingListIndex);
3984 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3985 const AttributeList &Attr) {
3986 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3990 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3991 D, Attr.getRange(), Attr.getName(),
3992 Attr.getAttributeSpellingListIndex()))
3996 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3997 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3998 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3999 D->addAttr(MinSize);
4002 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
4003 const AttributeList &Attr) {
4004 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4005 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
4006 D->addAttr(Optnone);
4009 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4010 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
4013 auto *VD = cast<VarDecl>(D);
4014 if (!VD->hasGlobalStorage()) {
4015 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
4018 D->addAttr(::new (S.Context) CUDAConstantAttr(
4019 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4022 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4023 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
4026 auto *VD = cast<VarDecl>(D);
4027 // extern __shared__ is only allowed on arrays with no length (e.g.
4029 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
4030 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
4033 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4034 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
4035 << S.CurrentCUDATarget())
4037 D->addAttr(::new (S.Context) CUDASharedAttr(
4038 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4041 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4042 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
4044 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
4048 FunctionDecl *FD = cast<FunctionDecl>(D);
4049 if (!FD->getReturnType()->isVoidType()) {
4050 SourceRange RTRange = FD->getReturnTypeSourceRange();
4051 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4053 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4057 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4058 if (Method->isInstance()) {
4059 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4063 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4065 // Only warn for "inline" when compiling for host, to cut down on noise.
4066 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4067 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
4069 D->addAttr(::new (S.Context)
4070 CUDAGlobalAttr(Attr.getRange(), S.Context,
4071 Attr.getAttributeSpellingListIndex()));
4074 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4075 FunctionDecl *Fn = cast<FunctionDecl>(D);
4076 if (!Fn->isInlineSpecified()) {
4077 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4081 D->addAttr(::new (S.Context)
4082 GNUInlineAttr(Attr.getRange(), S.Context,
4083 Attr.getAttributeSpellingListIndex()));
4086 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4087 if (hasDeclarator(D)) return;
4089 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
4090 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4092 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
4095 if (!isa<ObjCMethodDecl>(D)) {
4096 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4097 << Attr.getName() << ExpectedFunctionOrMethod;
4101 switch (Attr.getKind()) {
4102 case AttributeList::AT_FastCall:
4103 D->addAttr(::new (S.Context)
4104 FastCallAttr(Attr.getRange(), S.Context,
4105 Attr.getAttributeSpellingListIndex()));
4107 case AttributeList::AT_StdCall:
4108 D->addAttr(::new (S.Context)
4109 StdCallAttr(Attr.getRange(), S.Context,
4110 Attr.getAttributeSpellingListIndex()));
4112 case AttributeList::AT_ThisCall:
4113 D->addAttr(::new (S.Context)
4114 ThisCallAttr(Attr.getRange(), S.Context,
4115 Attr.getAttributeSpellingListIndex()));
4117 case AttributeList::AT_CDecl:
4118 D->addAttr(::new (S.Context)
4119 CDeclAttr(Attr.getRange(), S.Context,
4120 Attr.getAttributeSpellingListIndex()));
4122 case AttributeList::AT_Pascal:
4123 D->addAttr(::new (S.Context)
4124 PascalAttr(Attr.getRange(), S.Context,
4125 Attr.getAttributeSpellingListIndex()));
4127 case AttributeList::AT_SwiftCall:
4128 D->addAttr(::new (S.Context)
4129 SwiftCallAttr(Attr.getRange(), S.Context,
4130 Attr.getAttributeSpellingListIndex()));
4132 case AttributeList::AT_VectorCall:
4133 D->addAttr(::new (S.Context)
4134 VectorCallAttr(Attr.getRange(), S.Context,
4135 Attr.getAttributeSpellingListIndex()));
4137 case AttributeList::AT_MSABI:
4138 D->addAttr(::new (S.Context)
4139 MSABIAttr(Attr.getRange(), S.Context,
4140 Attr.getAttributeSpellingListIndex()));
4142 case AttributeList::AT_SysVABI:
4143 D->addAttr(::new (S.Context)
4144 SysVABIAttr(Attr.getRange(), S.Context,
4145 Attr.getAttributeSpellingListIndex()));
4147 case AttributeList::AT_RegCall:
4148 D->addAttr(::new (S.Context) RegCallAttr(
4149 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4151 case AttributeList::AT_Pcs: {
4152 PcsAttr::PCSType PCS;
4155 PCS = PcsAttr::AAPCS;
4158 PCS = PcsAttr::AAPCS_VFP;
4161 llvm_unreachable("unexpected calling convention in pcs attribute");
4164 D->addAttr(::new (S.Context)
4165 PcsAttr(Attr.getRange(), S.Context, PCS,
4166 Attr.getAttributeSpellingListIndex()));
4169 case AttributeList::AT_IntelOclBicc:
4170 D->addAttr(::new (S.Context)
4171 IntelOclBiccAttr(Attr.getRange(), S.Context,
4172 Attr.getAttributeSpellingListIndex()));
4174 case AttributeList::AT_PreserveMost:
4175 D->addAttr(::new (S.Context) PreserveMostAttr(
4176 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4178 case AttributeList::AT_PreserveAll:
4179 D->addAttr(::new (S.Context) PreserveAllAttr(
4180 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4183 llvm_unreachable("unexpected attribute kind");
4187 static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4188 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4191 std::vector<StringRef> DiagnosticIdentifiers;
4192 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4195 if (!S.checkStringLiteralArgumentAttr(Attr, I, RuleName, nullptr))
4198 // FIXME: Warn if the rule name is unknown. This is tricky because only
4199 // clang-tidy knows about available rules.
4200 DiagnosticIdentifiers.push_back(RuleName);
4202 D->addAttr(::new (S.Context) SuppressAttr(
4203 Attr.getRange(), S.Context, DiagnosticIdentifiers.data(),
4204 DiagnosticIdentifiers.size(), Attr.getAttributeSpellingListIndex()));
4207 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4208 const FunctionDecl *FD) {
4209 if (attr.isInvalid())
4212 if (attr.hasProcessingCache()) {
4213 CC = (CallingConv) attr.getProcessingCache();
4217 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4218 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
4223 // TODO: diagnose uses of these conventions on the wrong target.
4224 switch (attr.getKind()) {
4225 case AttributeList::AT_CDecl: CC = CC_C; break;
4226 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4227 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4228 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4229 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4230 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
4231 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
4232 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
4233 case AttributeList::AT_MSABI:
4234 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4237 case AttributeList::AT_SysVABI:
4238 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4241 case AttributeList::AT_Pcs: {
4243 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
4247 if (StrRef == "aapcs") {
4250 } else if (StrRef == "aapcs-vfp") {
4256 Diag(attr.getLoc(), diag::err_invalid_pcs);
4259 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4260 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4261 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4262 default: llvm_unreachable("unexpected attribute kind");
4265 const TargetInfo &TI = Context.getTargetInfo();
4266 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4267 if (A != TargetInfo::CCCR_OK) {
4268 if (A == TargetInfo::CCCR_Warning)
4269 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
4271 // This convention is not valid for the target. Use the default function or
4272 // method calling convention.
4273 bool IsCXXMethod = false, IsVariadic = false;
4275 IsCXXMethod = FD->isCXXInstanceMember();
4276 IsVariadic = FD->isVariadic();
4278 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4281 attr.setProcessingCache((unsigned) CC);
4285 /// Pointer-like types in the default address space.
4286 static bool isValidSwiftContextType(QualType type) {
4287 if (!type->hasPointerRepresentation())
4288 return type->isDependentType();
4289 return type->getPointeeType().getAddressSpace() == 0;
4292 /// Pointers and references in the default address space.
4293 static bool isValidSwiftIndirectResultType(QualType type) {
4294 if (auto ptrType = type->getAs<PointerType>()) {
4295 type = ptrType->getPointeeType();
4296 } else if (auto refType = type->getAs<ReferenceType>()) {
4297 type = refType->getPointeeType();
4299 return type->isDependentType();
4301 return type.getAddressSpace() == 0;
4304 /// Pointers and references to pointers in the default address space.
4305 static bool isValidSwiftErrorResultType(QualType type) {
4306 if (auto ptrType = type->getAs<PointerType>()) {
4307 type = ptrType->getPointeeType();
4308 } else if (auto refType = type->getAs<ReferenceType>()) {
4309 type = refType->getPointeeType();
4311 return type->isDependentType();
4313 if (!type.getQualifiers().empty())
4315 return isValidSwiftContextType(type);
4318 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4320 S.AddParameterABIAttr(attr.getRange(), D, abi,
4321 attr.getAttributeSpellingListIndex());
4324 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4325 unsigned spellingIndex) {
4327 QualType type = cast<ParmVarDecl>(D)->getType();
4329 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4330 if (existingAttr->getABI() != abi) {
4331 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4332 << getParameterABISpelling(abi) << existingAttr;
4333 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4339 case ParameterABI::Ordinary:
4340 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4342 case ParameterABI::SwiftContext:
4343 if (!isValidSwiftContextType(type)) {
4344 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4345 << getParameterABISpelling(abi)
4346 << /*pointer to pointer */ 0 << type;
4348 D->addAttr(::new (Context)
4349 SwiftContextAttr(range, Context, spellingIndex));
4352 case ParameterABI::SwiftErrorResult:
4353 if (!isValidSwiftErrorResultType(type)) {
4354 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4355 << getParameterABISpelling(abi)
4356 << /*pointer to pointer */ 1 << type;
4358 D->addAttr(::new (Context)
4359 SwiftErrorResultAttr(range, Context, spellingIndex));
4362 case ParameterABI::SwiftIndirectResult:
4363 if (!isValidSwiftIndirectResultType(type)) {
4364 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4365 << getParameterABISpelling(abi)
4366 << /*pointer*/ 0 << type;
4368 D->addAttr(::new (Context)
4369 SwiftIndirectResultAttr(range, Context, spellingIndex));
4372 llvm_unreachable("bad parameter ABI attribute");
4375 /// Checks a regparm attribute, returning true if it is ill-formed and
4376 /// otherwise setting numParams to the appropriate value.
4377 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4378 if (Attr.isInvalid())
4381 if (!checkAttributeNumArgs(*this, Attr, 1)) {
4387 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4388 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4393 if (Context.getTargetInfo().getRegParmMax() == 0) {
4394 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4395 << NumParamsExpr->getSourceRange();
4401 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4402 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4403 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4411 // Checks whether an argument of launch_bounds attribute is
4412 // acceptable, performs implicit conversion to Rvalue, and returns
4413 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4414 // and may output an error.
4415 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4416 const CUDALaunchBoundsAttr &Attr,
4417 const unsigned Idx) {
4418 if (S.DiagnoseUnexpandedParameterPack(E))
4421 // Accept template arguments for now as they depend on something else.
4422 // We'll get to check them when they eventually get instantiated.
4423 if (E->isValueDependent())
4427 if (!E->isIntegerConstantExpr(I, S.Context)) {
4428 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4429 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4432 // Make sure we can fit it in 32 bits.
4433 if (!I.isIntN(32)) {
4434 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4435 << 32 << /* Unsigned */ 1;
4439 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4440 << &Attr << Idx << E->getSourceRange();
4442 // We may need to perform implicit conversion of the argument.
4443 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4444 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4445 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4446 assert(!ValArg.isInvalid() &&
4447 "Unexpected PerformCopyInitialization() failure.");
4449 return ValArg.getAs<Expr>();
4452 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4453 Expr *MinBlocks, unsigned SpellingListIndex) {
4454 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4456 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4457 if (MaxThreads == nullptr)
4461 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4462 if (MinBlocks == nullptr)
4466 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4467 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4470 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4471 const AttributeList &Attr) {
4472 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4473 !checkAttributeAtMostNumArgs(S, Attr, 2))
4476 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4477 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4478 Attr.getAttributeSpellingListIndex());
4481 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4482 const AttributeList &Attr) {
4483 if (!Attr.isArgIdent(0)) {
4484 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4485 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4489 if (!checkAttributeNumArgs(S, Attr, 3))
4492 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4494 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4495 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4496 << Attr.getName() << ExpectedFunctionOrMethod;
4500 uint64_t ArgumentIdx;
4501 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4505 uint64_t TypeTagIdx;
4506 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4510 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4512 // Ensure that buffer has a pointer type.
4513 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4514 if (!BufferTy->isPointerType()) {
4515 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4516 << Attr.getName() << 0;
4520 D->addAttr(::new (S.Context)
4521 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4522 ArgumentIdx, TypeTagIdx, IsPointer,
4523 Attr.getAttributeSpellingListIndex()));
4526 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4527 const AttributeList &Attr) {
4528 if (!Attr.isArgIdent(0)) {
4529 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4530 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4534 if (!checkAttributeNumArgs(S, Attr, 1))
4537 if (!isa<VarDecl>(D)) {
4538 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4539 << Attr.getName() << ExpectedVariable;
4543 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4544 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4545 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4546 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4548 D->addAttr(::new (S.Context)
4549 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4551 Attr.getLayoutCompatible(),
4552 Attr.getMustBeNull(),
4553 Attr.getAttributeSpellingListIndex()));
4556 static void handleXRayLogArgsAttr(Sema &S, Decl *D,
4557 const AttributeList &Attr) {
4559 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, Attr.getArgAsExpr(0),
4563 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1.
4564 D->addAttr(::new (S.Context)
4565 XRayLogArgsAttr(Attr.getRange(), S.Context, ++ArgCount,
4566 Attr.getAttributeSpellingListIndex()));
4569 //===----------------------------------------------------------------------===//
4570 // Checker-specific attribute handlers.
4571 //===----------------------------------------------------------------------===//
4573 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4574 return type->isDependentType() ||
4575 type->isObjCRetainableType();
4578 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4579 return type->isDependentType() ||
4580 type->isObjCObjectPointerType() ||
4581 S.Context.isObjCNSObjectType(type);
4584 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4585 return type->isDependentType() ||
4586 type->isPointerType() ||
4587 isValidSubjectOfNSAttribute(S, type);
4590 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4591 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4592 Attr.getKind() == AttributeList::AT_NSConsumed,
4593 /*template instantiation*/ false);
4596 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4597 unsigned spellingIndex, bool isNSConsumed,
4598 bool isTemplateInstantiation) {
4599 ParmVarDecl *param = cast<ParmVarDecl>(D);
4603 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4605 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4609 // These attributes are normally just advisory, but in ARC, ns_consumed
4610 // is significant. Allow non-dependent code to contain inappropriate
4611 // attributes even in ARC, but require template instantiations to be
4612 // set up correctly.
4613 Diag(D->getLocStart(),
4614 (isTemplateInstantiation && isNSConsumed &&
4615 getLangOpts().ObjCAutoRefCount
4616 ? diag::err_ns_attribute_wrong_parameter_type
4617 : diag::warn_ns_attribute_wrong_parameter_type))
4619 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4620 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4625 param->addAttr(::new (Context)
4626 NSConsumedAttr(attrRange, Context, spellingIndex));
4628 param->addAttr(::new (Context)
4629 CFConsumedAttr(attrRange, Context, spellingIndex));
4632 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4633 const AttributeList &Attr) {
4634 QualType returnType;
4636 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4637 returnType = MD->getReturnType();
4638 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4639 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4640 return; // ignore: was handled as a type attribute
4641 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4642 returnType = PD->getType();
4643 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4644 returnType = FD->getReturnType();
4645 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4646 returnType = Param->getType()->getPointeeType();
4647 if (returnType.isNull()) {
4648 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4649 << Attr.getName() << /*pointer-to-CF*/2
4654 AttributeDeclKind ExpectedDeclKind;
4655 switch (Attr.getKind()) {
4656 default: llvm_unreachable("invalid ownership attribute");
4657 case AttributeList::AT_NSReturnsRetained:
4658 case AttributeList::AT_NSReturnsAutoreleased:
4659 case AttributeList::AT_NSReturnsNotRetained:
4660 ExpectedDeclKind = ExpectedFunctionOrMethod;
4663 case AttributeList::AT_CFReturnsRetained:
4664 case AttributeList::AT_CFReturnsNotRetained:
4665 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4668 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4669 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4675 switch (Attr.getKind()) {
4676 default: llvm_unreachable("invalid ownership attribute");
4677 case AttributeList::AT_NSReturnsRetained:
4678 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4682 case AttributeList::AT_NSReturnsAutoreleased:
4683 case AttributeList::AT_NSReturnsNotRetained:
4684 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4688 case AttributeList::AT_CFReturnsRetained:
4689 case AttributeList::AT_CFReturnsNotRetained:
4690 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4696 if (isa<ParmVarDecl>(D)) {
4697 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4698 << Attr.getName() << /*pointer-to-CF*/2
4701 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4706 } SubjectKind = Function;
4707 if (isa<ObjCMethodDecl>(D))
4708 SubjectKind = Method;
4709 else if (isa<ObjCPropertyDecl>(D))
4710 SubjectKind = Property;
4711 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4712 << Attr.getName() << SubjectKind << cf
4718 switch (Attr.getKind()) {
4720 llvm_unreachable("invalid ownership attribute");
4721 case AttributeList::AT_NSReturnsAutoreleased:
4722 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4723 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4725 case AttributeList::AT_CFReturnsNotRetained:
4726 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4727 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4729 case AttributeList::AT_NSReturnsNotRetained:
4730 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4731 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4733 case AttributeList::AT_CFReturnsRetained:
4734 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4735 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4737 case AttributeList::AT_NSReturnsRetained:
4738 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4739 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4744 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4745 const AttributeList &attr) {
4746 const int EP_ObjCMethod = 1;
4747 const int EP_ObjCProperty = 2;
4749 SourceLocation loc = attr.getLoc();
4750 QualType resultType;
4751 if (isa<ObjCMethodDecl>(D))
4752 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4754 resultType = cast<ObjCPropertyDecl>(D)->getType();
4756 if (!resultType->isReferenceType() &&
4757 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4758 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4761 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4762 << /*non-retainable pointer*/ 2;
4764 // Drop the attribute.
4768 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4769 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4772 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4773 const AttributeList &attr) {
4774 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4776 DeclContext *DC = method->getDeclContext();
4777 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4778 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4779 << attr.getName() << 0;
4780 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4783 if (method->getMethodFamily() == OMF_dealloc) {
4784 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4785 << attr.getName() << 1;
4789 method->addAttr(::new (S.Context)
4790 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4791 attr.getAttributeSpellingListIndex()));
4794 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4795 const AttributeList &Attr) {
4796 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4800 D->addAttr(::new (S.Context)
4801 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4802 Attr.getAttributeSpellingListIndex()));
4805 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4806 const AttributeList &Attr) {
4807 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4811 D->addAttr(::new (S.Context)
4812 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4813 Attr.getAttributeSpellingListIndex()));
4816 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4817 const AttributeList &Attr) {
4818 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4821 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4825 // Typedefs only allow objc_bridge(id) and have some additional checking.
4826 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4827 if (!Parm->Ident->isStr("id")) {
4828 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4833 // Only allow 'cv void *'.
4834 QualType T = TD->getUnderlyingType();
4835 if (!T->isVoidPointerType()) {
4836 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4841 D->addAttr(::new (S.Context)
4842 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4843 Attr.getAttributeSpellingListIndex()));
4846 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4847 const AttributeList &Attr) {
4848 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4851 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4855 D->addAttr(::new (S.Context)
4856 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4857 Attr.getAttributeSpellingListIndex()));
4860 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4861 const AttributeList &Attr) {
4862 IdentifierInfo *RelatedClass =
4863 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4864 if (!RelatedClass) {
4865 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4868 IdentifierInfo *ClassMethod =
4869 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4870 IdentifierInfo *InstanceMethod =
4871 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4872 D->addAttr(::new (S.Context)
4873 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4874 ClassMethod, InstanceMethod,
4875 Attr.getAttributeSpellingListIndex()));
4878 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4879 const AttributeList &Attr) {
4880 ObjCInterfaceDecl *IFace;
4881 if (ObjCCategoryDecl *CatDecl =
4882 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4883 IFace = CatDecl->getClassInterface();
4885 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4890 IFace->setHasDesignatedInitializers();
4891 D->addAttr(::new (S.Context)
4892 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4893 Attr.getAttributeSpellingListIndex()));
4896 static void handleObjCRuntimeName(Sema &S, Decl *D,
4897 const AttributeList &Attr) {
4898 StringRef MetaDataName;
4899 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4901 D->addAttr(::new (S.Context)
4902 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4904 Attr.getAttributeSpellingListIndex()));
4907 // When a user wants to use objc_boxable with a union or struct
4908 // but they don't have access to the declaration (legacy/third-party code)
4909 // then they can 'enable' this feature with a typedef:
4910 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4911 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4912 bool notify = false;
4914 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4915 if (RD && RD->getDefinition()) {
4916 RD = RD->getDefinition();
4921 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4922 ObjCBoxableAttr(Attr.getRange(), S.Context,
4923 Attr.getAttributeSpellingListIndex());
4924 RD->addAttr(BoxableAttr);
4926 // we need to notify ASTReader/ASTWriter about
4927 // modification of existing declaration
4928 if (ASTMutationListener *L = S.getASTMutationListener())
4929 L->AddedAttributeToRecord(BoxableAttr, RD);
4934 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4935 const AttributeList &Attr) {
4936 if (hasDeclarator(D)) return;
4938 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4939 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4942 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4943 const AttributeList &Attr) {
4944 ValueDecl *vd = cast<ValueDecl>(D);
4945 QualType type = vd->getType();
4947 if (!type->isDependentType() &&
4948 !type->isObjCLifetimeType()) {
4949 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4954 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4956 // If we have no lifetime yet, check the lifetime we're presumably
4958 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4959 lifetime = type->getObjCARCImplicitLifetime();
4962 case Qualifiers::OCL_None:
4963 assert(type->isDependentType() &&
4964 "didn't infer lifetime for non-dependent type?");
4967 case Qualifiers::OCL_Weak: // meaningful
4968 case Qualifiers::OCL_Strong: // meaningful
4971 case Qualifiers::OCL_ExplicitNone:
4972 case Qualifiers::OCL_Autoreleasing:
4973 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4974 << (lifetime == Qualifiers::OCL_Autoreleasing);
4978 D->addAttr(::new (S.Context)
4979 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4980 Attr.getAttributeSpellingListIndex()));
4983 //===----------------------------------------------------------------------===//
4984 // Microsoft specific attribute handlers.
4985 //===----------------------------------------------------------------------===//
4987 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4988 unsigned AttrSpellingListIndex, StringRef Uuid) {
4989 if (const auto *UA = D->getAttr<UuidAttr>()) {
4990 if (UA->getGuid().equals_lower(Uuid))
4992 Diag(UA->getLocation(), diag::err_mismatched_uuid);
4993 Diag(Range.getBegin(), diag::note_previous_uuid);
4994 D->dropAttr<UuidAttr>();
4997 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5000 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5001 if (!S.LangOpts.CPlusPlus) {
5002 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5003 << Attr.getName() << AttributeLangSupport::C;
5008 SourceLocation LiteralLoc;
5009 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
5012 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5013 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5014 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5015 StrRef = StrRef.drop_front().drop_back();
5017 // Validate GUID length.
5018 if (StrRef.size() != 36) {
5019 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5023 for (unsigned i = 0; i < 36; ++i) {
5024 if (i == 8 || i == 13 || i == 18 || i == 23) {
5025 if (StrRef[i] != '-') {
5026 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5029 } else if (!isHexDigit(StrRef[i])) {
5030 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5035 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
5036 Attr.getAttributeSpellingListIndex(), StrRef);
5041 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5042 if (!S.LangOpts.CPlusPlus) {
5043 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
5044 << Attr.getName() << AttributeLangSupport::C;
5047 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5048 D, Attr.getRange(), /*BestCase=*/true,
5049 Attr.getAttributeSpellingListIndex(),
5050 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
5053 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5057 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
5058 const AttributeList &Attr) {
5059 VarDecl *VD = cast<VarDecl>(D);
5060 if (!S.Context.getTargetInfo().isTLSSupported()) {
5061 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
5064 if (VD->getTSCSpec() != TSCS_unspecified) {
5065 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
5068 if (VD->hasLocalStorage()) {
5069 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5072 VD->addAttr(::new (S.Context) ThreadAttr(
5073 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5076 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5077 SmallVector<StringRef, 4> Tags;
5078 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5080 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
5082 Tags.push_back(Tag);
5085 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5086 if (!NS->isInline()) {
5087 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5090 if (NS->isAnonymousNamespace()) {
5091 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5094 if (Attr.getNumArgs() == 0)
5095 Tags.push_back(NS->getName());
5096 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5099 // Store tags sorted and without duplicates.
5100 std::sort(Tags.begin(), Tags.end());
5101 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5103 D->addAttr(::new (S.Context)
5104 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
5105 Attr.getAttributeSpellingListIndex()));
5108 static void handleARMInterruptAttr(Sema &S, Decl *D,
5109 const AttributeList &Attr) {
5110 // Check the attribute arguments.
5111 if (Attr.getNumArgs() > 1) {
5112 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5113 << Attr.getName() << 1;
5118 SourceLocation ArgLoc;
5120 if (Attr.getNumArgs() == 0)
5122 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5125 ARMInterruptAttr::InterruptType Kind;
5126 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5127 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5128 << Attr.getName() << Str << ArgLoc;
5132 unsigned Index = Attr.getAttributeSpellingListIndex();
5133 D->addAttr(::new (S.Context)
5134 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
5137 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
5138 const AttributeList &Attr) {
5139 if (!checkAttributeNumArgs(S, Attr, 1))
5142 if (!Attr.isArgExpr(0)) {
5143 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
5144 << AANT_ArgumentIntegerConstant;
5148 // FIXME: Check for decl - it should be void ()(void).
5150 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5151 llvm::APSInt NumParams(32);
5152 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5153 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5154 << Attr.getName() << AANT_ArgumentIntegerConstant
5155 << NumParamsExpr->getSourceRange();
5159 unsigned Num = NumParams.getLimitedValue(255);
5160 if ((Num & 1) || Num > 30) {
5161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5162 << Attr.getName() << (int)NumParams.getSExtValue()
5163 << NumParamsExpr->getSourceRange();
5167 D->addAttr(::new (S.Context)
5168 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5169 Attr.getAttributeSpellingListIndex()));
5170 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5173 static void handleMipsInterruptAttr(Sema &S, Decl *D,
5174 const AttributeList &Attr) {
5175 // Only one optional argument permitted.
5176 if (Attr.getNumArgs() > 1) {
5177 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5178 << Attr.getName() << 1;
5183 SourceLocation ArgLoc;
5185 if (Attr.getNumArgs() == 0)
5187 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5190 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5191 // a) Must be a function.
5192 // b) Must have no parameters.
5193 // c) Must have the 'void' return type.
5194 // d) Cannot have the 'mips16' attribute, as that instruction set
5195 // lacks the 'eret' instruction.
5196 // e) The attribute itself must either have no argument or one of the
5197 // valid interrupt types, see [MipsInterruptDocs].
5199 if (!isFunctionOrMethod(D)) {
5200 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5201 << "'interrupt'" << ExpectedFunctionOrMethod;
5205 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5206 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5211 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5212 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5217 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5221 MipsInterruptAttr::InterruptType Kind;
5222 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5223 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5224 << Attr.getName() << "'" + std::string(Str) + "'";
5228 D->addAttr(::new (S.Context) MipsInterruptAttr(
5229 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5232 static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5233 const AttributeList &Attr) {
5234 // Semantic checks for a function with the 'interrupt' attribute.
5235 // a) Must be a function.
5236 // b) Must have the 'void' return type.
5237 // c) Must take 1 or 2 arguments.
5238 // d) The 1st argument must be a pointer.
5239 // e) The 2nd argument (if any) must be an unsigned integer.
5240 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5241 CXXMethodDecl::isStaticOverloadedOperator(
5242 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5243 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5244 << Attr.getName() << ExpectedFunctionWithProtoType;
5247 // Interrupt handler must have void return type.
5248 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5249 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5250 diag::err_anyx86_interrupt_attribute)
5251 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5257 // Interrupt handler must have 1 or 2 parameters.
5258 unsigned NumParams = getFunctionOrMethodNumParams(D);
5259 if (NumParams < 1 || NumParams > 2) {
5260 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5261 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5267 // The first argument must be a pointer.
5268 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5269 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5270 diag::err_anyx86_interrupt_attribute)
5271 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5277 // The second argument, if present, must be an unsigned integer.
5279 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5282 if (NumParams == 2 &&
5283 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5284 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5285 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5286 diag::err_anyx86_interrupt_attribute)
5287 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5290 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5293 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5294 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5295 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5298 static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5299 if (!isFunctionOrMethod(D)) {
5300 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5301 << "'interrupt'" << ExpectedFunction;
5305 if (!checkAttributeNumArgs(S, Attr, 0))
5308 handleSimpleAttribute<AVRInterruptAttr>(S, D, Attr);
5311 static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5312 if (!isFunctionOrMethod(D)) {
5313 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5314 << "'signal'" << ExpectedFunction;
5318 if (!checkAttributeNumArgs(S, Attr, 0))
5321 handleSimpleAttribute<AVRSignalAttr>(S, D, Attr);
5324 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5325 // Dispatch the interrupt attribute based on the current target.
5326 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5327 case llvm::Triple::msp430:
5328 handleMSP430InterruptAttr(S, D, Attr);
5330 case llvm::Triple::mipsel:
5331 case llvm::Triple::mips:
5332 handleMipsInterruptAttr(S, D, Attr);
5334 case llvm::Triple::x86:
5335 case llvm::Triple::x86_64:
5336 handleAnyX86InterruptAttr(S, D, Attr);
5338 case llvm::Triple::avr:
5339 handleAVRInterruptAttr(S, D, Attr);
5342 handleARMInterruptAttr(S, D, Attr);
5347 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5348 const AttributeList &Attr) {
5350 Expr *MinExpr = Attr.getArgAsExpr(0);
5351 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5355 Expr *MaxExpr = Attr.getArgAsExpr(1);
5356 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5359 if (Min == 0 && Max != 0) {
5360 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5361 << Attr.getName() << 0;
5365 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5366 << Attr.getName() << 1;
5370 D->addAttr(::new (S.Context)
5371 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5372 Attr.getAttributeSpellingListIndex()));
5375 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5376 const AttributeList &Attr) {
5378 Expr *MinExpr = Attr.getArgAsExpr(0);
5379 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5383 if (Attr.getNumArgs() == 2) {
5384 Expr *MaxExpr = Attr.getArgAsExpr(1);
5385 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5389 if (Min == 0 && Max != 0) {
5390 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5391 << Attr.getName() << 0;
5394 if (Max != 0 && Min > Max) {
5395 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5396 << Attr.getName() << 1;
5400 D->addAttr(::new (S.Context)
5401 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5402 Attr.getAttributeSpellingListIndex()));
5405 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5406 const AttributeList &Attr) {
5407 uint32_t NumSGPR = 0;
5408 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5409 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
5412 D->addAttr(::new (S.Context)
5413 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5414 Attr.getAttributeSpellingListIndex()));
5417 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5418 const AttributeList &Attr) {
5419 uint32_t NumVGPR = 0;
5420 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5421 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5424 D->addAttr(::new (S.Context)
5425 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
5426 Attr.getAttributeSpellingListIndex()));
5429 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5430 const AttributeList& Attr) {
5431 // If we try to apply it to a function pointer, don't warn, but don't
5432 // do anything, either. It doesn't matter anyway, because there's nothing
5433 // special about calling a force_align_arg_pointer function.
5434 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5435 if (VD && VD->getType()->isFunctionPointerType())
5437 // Also don't warn on function pointer typedefs.
5438 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5439 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5440 TD->getUnderlyingType()->isFunctionType()))
5442 // Attribute can only be applied to function types.
5443 if (!isa<FunctionDecl>(D)) {
5444 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5445 << Attr.getName() << /* function */0;
5449 D->addAttr(::new (S.Context)
5450 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5451 Attr.getAttributeSpellingListIndex()));
5454 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5456 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5457 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5460 // TODO: Investigate what happens with the next major version of MSVC.
5461 if (Version != LangOptions::MSVC2015) {
5462 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5463 << Attr.getName() << Version << VersionExpr->getSourceRange();
5467 D->addAttr(::new (S.Context)
5468 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5469 Attr.getAttributeSpellingListIndex()));
5472 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5473 unsigned AttrSpellingListIndex) {
5474 if (D->hasAttr<DLLExportAttr>()) {
5475 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5479 if (D->hasAttr<DLLImportAttr>())
5482 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5485 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5486 unsigned AttrSpellingListIndex) {
5487 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5488 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5489 D->dropAttr<DLLImportAttr>();
5492 if (D->hasAttr<DLLExportAttr>())
5495 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5498 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5499 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5500 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5501 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5506 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5507 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5508 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5509 // MinGW doesn't allow dllimport on inline functions.
5510 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5516 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5517 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5518 MD->getParent()->isLambda()) {
5519 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5524 unsigned Index = A.getAttributeSpellingListIndex();
5525 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5526 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5527 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5529 D->addAttr(NewAttr);
5533 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5534 unsigned AttrSpellingListIndex,
5535 MSInheritanceAttr::Spelling SemanticSpelling) {
5536 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5537 if (IA->getSemanticSpelling() == SemanticSpelling)
5539 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5540 << 1 /*previous declaration*/;
5541 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5542 D->dropAttr<MSInheritanceAttr>();
5545 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5546 if (RD->hasDefinition()) {
5547 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5548 SemanticSpelling)) {
5552 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5553 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5554 << 1 /*partial specialization*/;
5557 if (RD->getDescribedClassTemplate()) {
5558 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5559 << 0 /*primary template*/;
5564 return ::new (Context)
5565 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5568 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5569 // The capability attributes take a single string parameter for the name of
5570 // the capability they represent. The lockable attribute does not take any
5571 // parameters. However, semantically, both attributes represent the same
5572 // concept, and so they use the same semantic attribute. Eventually, the
5573 // lockable attribute will be removed.
5575 // For backward compatibility, any capability which has no specified string
5576 // literal will be considered a "mutex."
5577 StringRef N("mutex");
5578 SourceLocation LiteralLoc;
5579 if (Attr.getKind() == AttributeList::AT_Capability &&
5580 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5583 // Currently, there are only two names allowed for a capability: role and
5584 // mutex (case insensitive). Diagnose other capability names.
5585 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5586 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5588 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5589 Attr.getAttributeSpellingListIndex()));
5592 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5593 const AttributeList &Attr) {
5594 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5595 Attr.getArgAsExpr(0),
5596 Attr.getAttributeSpellingListIndex()));
5599 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5600 const AttributeList &Attr) {
5601 SmallVector<Expr*, 1> Args;
5602 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5605 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5607 Args.data(), Args.size(),
5608 Attr.getAttributeSpellingListIndex()));
5611 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5612 const AttributeList &Attr) {
5613 SmallVector<Expr*, 2> Args;
5614 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5617 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5619 Attr.getArgAsExpr(0),
5622 Attr.getAttributeSpellingListIndex()));
5625 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5626 const AttributeList &Attr) {
5627 // Check that all arguments are lockable objects.
5628 SmallVector<Expr *, 1> Args;
5629 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5631 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5632 Attr.getRange(), S.Context, Args.data(), Args.size(),
5633 Attr.getAttributeSpellingListIndex()));
5636 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5637 const AttributeList &Attr) {
5638 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5641 // check that all arguments are lockable objects
5642 SmallVector<Expr*, 1> Args;
5643 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5647 RequiresCapabilityAttr *RCA = ::new (S.Context)
5648 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5649 Args.size(), Attr.getAttributeSpellingListIndex());
5654 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5655 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5656 if (NSD->isAnonymousNamespace()) {
5657 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5658 // Do not want to attach the attribute to the namespace because that will
5659 // cause confusing diagnostic reports for uses of declarations within the
5665 // Handle the cases where the attribute has a text message.
5666 StringRef Str, Replacement;
5667 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5668 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5671 // Only support a single optional message for Declspec and CXX11.
5672 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5673 checkAttributeAtMostNumArgs(S, Attr, 1);
5674 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5675 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5678 if (!S.getLangOpts().CPlusPlus14)
5679 if (Attr.isCXX11Attribute() &&
5680 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5681 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5683 D->addAttr(::new (S.Context)
5684 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5685 Attr.getAttributeSpellingListIndex()));
5688 static bool isGlobalVar(const Decl *D) {
5689 if (const auto *S = dyn_cast<VarDecl>(D))
5690 return S->hasGlobalStorage();
5694 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5695 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5698 std::vector<StringRef> Sanitizers;
5700 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5701 StringRef SanitizerName;
5702 SourceLocation LiteralLoc;
5704 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5707 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5708 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5709 else if (isGlobalVar(D) && SanitizerName != "address")
5710 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5711 << Attr.getName() << ExpectedFunctionOrMethod;
5712 Sanitizers.push_back(SanitizerName);
5715 D->addAttr(::new (S.Context) NoSanitizeAttr(
5716 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5717 Attr.getAttributeSpellingListIndex()));
5720 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5721 const AttributeList &Attr) {
5722 StringRef AttrName = Attr.getName()->getName();
5723 normalizeName(AttrName);
5724 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5725 .Case("no_address_safety_analysis", "address")
5726 .Case("no_sanitize_address", "address")
5727 .Case("no_sanitize_thread", "thread")
5728 .Case("no_sanitize_memory", "memory");
5729 if (isGlobalVar(D) && SanitizerName != "address")
5730 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5731 << Attr.getName() << ExpectedFunction;
5732 D->addAttr(::new (S.Context)
5733 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5734 Attr.getAttributeSpellingListIndex()));
5737 static void handleInternalLinkageAttr(Sema &S, Decl *D,
5738 const AttributeList &Attr) {
5739 if (InternalLinkageAttr *Internal =
5740 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5741 Attr.getAttributeSpellingListIndex()))
5742 D->addAttr(Internal);
5745 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5746 if (S.LangOpts.OpenCLVersion != 200)
5747 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5748 << Attr.getName() << "2.0" << 0;
5750 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5751 << Attr.getName() << "2.0";
5754 /// Handles semantic checking for features that are common to all attributes,
5755 /// such as checking whether a parameter was properly specified, or the correct
5756 /// number of arguments were passed, etc.
5757 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5758 const AttributeList &Attr) {
5759 // Several attributes carry different semantics than the parsing requires, so
5760 // those are opted out of the common argument checks.
5762 // We also bail on unknown and ignored attributes because those are handled
5763 // as part of the target-specific handling logic.
5764 if (Attr.getKind() == AttributeList::UnknownAttribute)
5766 // Check whether the attribute requires specific language extensions to be
5768 if (!Attr.diagnoseLangOpts(S))
5770 // Check whether the attribute appertains to the given subject.
5771 if (!Attr.diagnoseAppertainsTo(S, D))
5773 if (Attr.hasCustomParsing())
5776 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5777 // If there are no optional arguments, then checking for the argument count
5779 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5782 // There are optional arguments, so checking is slightly more involved.
5783 if (Attr.getMinArgs() &&
5784 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5786 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5787 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5794 static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5795 const AttributeList &Attr) {
5796 if (D->isInvalidDecl())
5799 // Check if there is only one access qualifier.
5800 if (D->hasAttr<OpenCLAccessAttr>()) {
5801 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5802 << D->getSourceRange();
5803 D->setInvalidDecl(true);
5807 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5808 // image object can be read and written.
5809 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5810 // object. Using the read_write (or __read_write) qualifier with the pipe
5811 // qualifier is a compilation error.
5812 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5813 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5814 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5815 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5816 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5817 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5818 D->setInvalidDecl(true);
5824 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5825 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5828 //===----------------------------------------------------------------------===//
5829 // Top Level Sema Entry Points
5830 //===----------------------------------------------------------------------===//
5832 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5833 /// the attribute applies to decls. If the attribute is a type attribute, just
5834 /// silently ignore it if a GNU attribute.
5835 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5836 const AttributeList &Attr,
5837 bool IncludeCXX11Attributes) {
5838 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5841 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5843 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5846 // Unknown attributes are automatically warned on. Target-specific attributes
5847 // which do not apply to the current target architecture are treated as
5848 // though they were unknown attributes.
5849 if (Attr.getKind() == AttributeList::UnknownAttribute ||
5850 !Attr.existsInTarget(S.Context.getTargetInfo())) {
5851 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5852 ? diag::warn_unhandled_ms_attribute_ignored
5853 : diag::warn_unknown_attribute_ignored)
5858 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5861 switch (Attr.getKind()) {
5863 if (!Attr.isStmtAttr()) {
5864 // Type attributes are handled elsewhere; silently move on.
5865 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5868 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5869 << Attr.getName() << D->getLocation();
5871 case AttributeList::AT_Interrupt:
5872 handleInterruptAttr(S, D, Attr);
5874 case AttributeList::AT_X86ForceAlignArgPointer:
5875 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5877 case AttributeList::AT_DLLExport:
5878 case AttributeList::AT_DLLImport:
5879 handleDLLAttr(S, D, Attr);
5881 case AttributeList::AT_Mips16:
5882 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5885 case AttributeList::AT_NoMips16:
5886 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5888 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5889 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5891 case AttributeList::AT_AMDGPUWavesPerEU:
5892 handleAMDGPUWavesPerEUAttr(S, D, Attr);
5894 case AttributeList::AT_AMDGPUNumSGPR:
5895 handleAMDGPUNumSGPRAttr(S, D, Attr);
5897 case AttributeList::AT_AMDGPUNumVGPR:
5898 handleAMDGPUNumVGPRAttr(S, D, Attr);
5900 case AttributeList::AT_AVRSignal:
5901 handleAVRSignalAttr(S, D, Attr);
5903 case AttributeList::AT_IBAction:
5904 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5906 case AttributeList::AT_IBOutlet:
5907 handleIBOutlet(S, D, Attr);
5909 case AttributeList::AT_IBOutletCollection:
5910 handleIBOutletCollection(S, D, Attr);
5912 case AttributeList::AT_IFunc:
5913 handleIFuncAttr(S, D, Attr);
5915 case AttributeList::AT_Alias:
5916 handleAliasAttr(S, D, Attr);
5918 case AttributeList::AT_Aligned:
5919 handleAlignedAttr(S, D, Attr);
5921 case AttributeList::AT_AlignValue:
5922 handleAlignValueAttr(S, D, Attr);
5924 case AttributeList::AT_AllocSize:
5925 handleAllocSizeAttr(S, D, Attr);
5927 case AttributeList::AT_AlwaysInline:
5928 handleAlwaysInlineAttr(S, D, Attr);
5930 case AttributeList::AT_AnalyzerNoReturn:
5931 handleAnalyzerNoReturnAttr(S, D, Attr);
5933 case AttributeList::AT_TLSModel:
5934 handleTLSModelAttr(S, D, Attr);
5936 case AttributeList::AT_Annotate:
5937 handleAnnotateAttr(S, D, Attr);
5939 case AttributeList::AT_Availability:
5940 handleAvailabilityAttr(S, D, Attr);
5942 case AttributeList::AT_CarriesDependency:
5943 handleDependencyAttr(S, scope, D, Attr);
5945 case AttributeList::AT_Common:
5946 handleCommonAttr(S, D, Attr);
5948 case AttributeList::AT_CUDAConstant:
5949 handleConstantAttr(S, D, Attr);
5951 case AttributeList::AT_PassObjectSize:
5952 handlePassObjectSizeAttr(S, D, Attr);
5954 case AttributeList::AT_Constructor:
5955 handleConstructorAttr(S, D, Attr);
5957 case AttributeList::AT_CXX11NoReturn:
5958 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5960 case AttributeList::AT_Deprecated:
5961 handleDeprecatedAttr(S, D, Attr);
5963 case AttributeList::AT_Destructor:
5964 handleDestructorAttr(S, D, Attr);
5966 case AttributeList::AT_EnableIf:
5967 handleEnableIfAttr(S, D, Attr);
5969 case AttributeList::AT_DiagnoseIf:
5970 handleDiagnoseIfAttr(S, D, Attr);
5972 case AttributeList::AT_ExtVectorType:
5973 handleExtVectorTypeAttr(S, scope, D, Attr);
5975 case AttributeList::AT_ExternalSourceSymbol:
5976 handleExternalSourceSymbolAttr(S, D, Attr);
5978 case AttributeList::AT_MinSize:
5979 handleMinSizeAttr(S, D, Attr);
5981 case AttributeList::AT_OptimizeNone:
5982 handleOptimizeNoneAttr(S, D, Attr);
5984 case AttributeList::AT_FlagEnum:
5985 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5987 case AttributeList::AT_EnumExtensibility:
5988 handleEnumExtensibilityAttr(S, D, Attr);
5990 case AttributeList::AT_Flatten:
5991 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5993 case AttributeList::AT_Format:
5994 handleFormatAttr(S, D, Attr);
5996 case AttributeList::AT_FormatArg:
5997 handleFormatArgAttr(S, D, Attr);
5999 case AttributeList::AT_CUDAGlobal:
6000 handleGlobalAttr(S, D, Attr);
6002 case AttributeList::AT_CUDADevice:
6003 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6006 case AttributeList::AT_CUDAHost:
6007 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
6010 case AttributeList::AT_GNUInline:
6011 handleGNUInlineAttr(S, D, Attr);
6013 case AttributeList::AT_CUDALaunchBounds:
6014 handleLaunchBoundsAttr(S, D, Attr);
6016 case AttributeList::AT_Restrict:
6017 handleRestrictAttr(S, D, Attr);
6019 case AttributeList::AT_MayAlias:
6020 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
6022 case AttributeList::AT_Mode:
6023 handleModeAttr(S, D, Attr);
6025 case AttributeList::AT_NoAlias:
6026 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
6028 case AttributeList::AT_NoCommon:
6029 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
6031 case AttributeList::AT_NoSplitStack:
6032 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
6034 case AttributeList::AT_NonNull:
6035 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
6036 handleNonNullAttrParameter(S, PVD, Attr);
6038 handleNonNullAttr(S, D, Attr);
6040 case AttributeList::AT_ReturnsNonNull:
6041 handleReturnsNonNullAttr(S, D, Attr);
6043 case AttributeList::AT_AssumeAligned:
6044 handleAssumeAlignedAttr(S, D, Attr);
6046 case AttributeList::AT_AllocAlign:
6047 handleAllocAlignAttr(S, D, Attr);
6049 case AttributeList::AT_Overloadable:
6050 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
6052 case AttributeList::AT_Ownership:
6053 handleOwnershipAttr(S, D, Attr);
6055 case AttributeList::AT_Cold:
6056 handleColdAttr(S, D, Attr);
6058 case AttributeList::AT_Hot:
6059 handleHotAttr(S, D, Attr);
6061 case AttributeList::AT_Naked:
6062 handleNakedAttr(S, D, Attr);
6064 case AttributeList::AT_NoReturn:
6065 handleNoReturnAttr(S, D, Attr);
6067 case AttributeList::AT_NoThrow:
6068 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
6070 case AttributeList::AT_CUDAShared:
6071 handleSharedAttr(S, D, Attr);
6073 case AttributeList::AT_VecReturn:
6074 handleVecReturnAttr(S, D, Attr);
6076 case AttributeList::AT_ObjCOwnership:
6077 handleObjCOwnershipAttr(S, D, Attr);
6079 case AttributeList::AT_ObjCPreciseLifetime:
6080 handleObjCPreciseLifetimeAttr(S, D, Attr);
6082 case AttributeList::AT_ObjCReturnsInnerPointer:
6083 handleObjCReturnsInnerPointerAttr(S, D, Attr);
6085 case AttributeList::AT_ObjCRequiresSuper:
6086 handleObjCRequiresSuperAttr(S, D, Attr);
6088 case AttributeList::AT_ObjCBridge:
6089 handleObjCBridgeAttr(S, scope, D, Attr);
6091 case AttributeList::AT_ObjCBridgeMutable:
6092 handleObjCBridgeMutableAttr(S, scope, D, Attr);
6094 case AttributeList::AT_ObjCBridgeRelated:
6095 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
6097 case AttributeList::AT_ObjCDesignatedInitializer:
6098 handleObjCDesignatedInitializer(S, D, Attr);
6100 case AttributeList::AT_ObjCRuntimeName:
6101 handleObjCRuntimeName(S, D, Attr);
6103 case AttributeList::AT_ObjCRuntimeVisible:
6104 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
6106 case AttributeList::AT_ObjCBoxable:
6107 handleObjCBoxable(S, D, Attr);
6109 case AttributeList::AT_CFAuditedTransfer:
6110 handleCFAuditedTransferAttr(S, D, Attr);
6112 case AttributeList::AT_CFUnknownTransfer:
6113 handleCFUnknownTransferAttr(S, D, Attr);
6115 case AttributeList::AT_CFConsumed:
6116 case AttributeList::AT_NSConsumed:
6117 handleNSConsumedAttr(S, D, Attr);
6119 case AttributeList::AT_NSConsumesSelf:
6120 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
6122 case AttributeList::AT_NSReturnsAutoreleased:
6123 case AttributeList::AT_NSReturnsNotRetained:
6124 case AttributeList::AT_CFReturnsNotRetained:
6125 case AttributeList::AT_NSReturnsRetained:
6126 case AttributeList::AT_CFReturnsRetained:
6127 handleNSReturnsRetainedAttr(S, D, Attr);
6129 case AttributeList::AT_WorkGroupSizeHint:
6130 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
6132 case AttributeList::AT_ReqdWorkGroupSize:
6133 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
6135 case AttributeList::AT_VecTypeHint:
6136 handleVecTypeHint(S, D, Attr);
6138 case AttributeList::AT_RequireConstantInit:
6139 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
6141 case AttributeList::AT_InitPriority:
6142 handleInitPriorityAttr(S, D, Attr);
6144 case AttributeList::AT_Packed:
6145 handlePackedAttr(S, D, Attr);
6147 case AttributeList::AT_Section:
6148 handleSectionAttr(S, D, Attr);
6150 case AttributeList::AT_Target:
6151 handleTargetAttr(S, D, Attr);
6153 case AttributeList::AT_Unavailable:
6154 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
6156 case AttributeList::AT_ArcWeakrefUnavailable:
6157 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
6159 case AttributeList::AT_ObjCRootClass:
6160 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
6162 case AttributeList::AT_ObjCSubclassingRestricted:
6163 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
6165 case AttributeList::AT_ObjCExplicitProtocolImpl:
6166 handleObjCSuppresProtocolAttr(S, D, Attr);
6168 case AttributeList::AT_ObjCRequiresPropertyDefs:
6169 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
6171 case AttributeList::AT_Unused:
6172 handleUnusedAttr(S, D, Attr);
6174 case AttributeList::AT_ReturnsTwice:
6175 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
6177 case AttributeList::AT_NotTailCalled:
6178 handleNotTailCalledAttr(S, D, Attr);
6180 case AttributeList::AT_DisableTailCalls:
6181 handleDisableTailCallsAttr(S, D, Attr);
6183 case AttributeList::AT_Used:
6184 handleUsedAttr(S, D, Attr);
6186 case AttributeList::AT_Visibility:
6187 handleVisibilityAttr(S, D, Attr, false);
6189 case AttributeList::AT_TypeVisibility:
6190 handleVisibilityAttr(S, D, Attr, true);
6192 case AttributeList::AT_WarnUnused:
6193 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
6195 case AttributeList::AT_WarnUnusedResult:
6196 handleWarnUnusedResult(S, D, Attr);
6198 case AttributeList::AT_Weak:
6199 handleSimpleAttribute<WeakAttr>(S, D, Attr);
6201 case AttributeList::AT_WeakRef:
6202 handleWeakRefAttr(S, D, Attr);
6204 case AttributeList::AT_WeakImport:
6205 handleWeakImportAttr(S, D, Attr);
6207 case AttributeList::AT_TransparentUnion:
6208 handleTransparentUnionAttr(S, D, Attr);
6210 case AttributeList::AT_ObjCException:
6211 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6213 case AttributeList::AT_ObjCMethodFamily:
6214 handleObjCMethodFamilyAttr(S, D, Attr);
6216 case AttributeList::AT_ObjCNSObject:
6217 handleObjCNSObject(S, D, Attr);
6219 case AttributeList::AT_ObjCIndependentClass:
6220 handleObjCIndependentClass(S, D, Attr);
6222 case AttributeList::AT_Blocks:
6223 handleBlocksAttr(S, D, Attr);
6225 case AttributeList::AT_Sentinel:
6226 handleSentinelAttr(S, D, Attr);
6228 case AttributeList::AT_Const:
6229 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6231 case AttributeList::AT_Pure:
6232 handleSimpleAttribute<PureAttr>(S, D, Attr);
6234 case AttributeList::AT_Cleanup:
6235 handleCleanupAttr(S, D, Attr);
6237 case AttributeList::AT_NoDebug:
6238 handleNoDebugAttr(S, D, Attr);
6240 case AttributeList::AT_NoDuplicate:
6241 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6243 case AttributeList::AT_Convergent:
6244 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6246 case AttributeList::AT_NoInline:
6247 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6249 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6250 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6252 case AttributeList::AT_StdCall:
6253 case AttributeList::AT_CDecl:
6254 case AttributeList::AT_FastCall:
6255 case AttributeList::AT_ThisCall:
6256 case AttributeList::AT_Pascal:
6257 case AttributeList::AT_RegCall:
6258 case AttributeList::AT_SwiftCall:
6259 case AttributeList::AT_VectorCall:
6260 case AttributeList::AT_MSABI:
6261 case AttributeList::AT_SysVABI:
6262 case AttributeList::AT_Pcs:
6263 case AttributeList::AT_IntelOclBicc:
6264 case AttributeList::AT_PreserveMost:
6265 case AttributeList::AT_PreserveAll:
6266 handleCallConvAttr(S, D, Attr);
6268 case AttributeList::AT_Suppress:
6269 handleSuppressAttr(S, D, Attr);
6271 case AttributeList::AT_OpenCLKernel:
6272 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6274 case AttributeList::AT_OpenCLAccess:
6275 handleOpenCLAccessAttr(S, D, Attr);
6277 case AttributeList::AT_OpenCLNoSVM:
6278 handleOpenCLNoSVMAttr(S, D, Attr);
6280 case AttributeList::AT_SwiftContext:
6281 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6283 case AttributeList::AT_SwiftErrorResult:
6284 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6286 case AttributeList::AT_SwiftIndirectResult:
6287 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6289 case AttributeList::AT_InternalLinkage:
6290 handleInternalLinkageAttr(S, D, Attr);
6292 case AttributeList::AT_LTOVisibilityPublic:
6293 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6296 // Microsoft attributes:
6297 case AttributeList::AT_EmptyBases:
6298 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6300 case AttributeList::AT_LayoutVersion:
6301 handleLayoutVersion(S, D, Attr);
6303 case AttributeList::AT_MSNoVTable:
6304 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
6306 case AttributeList::AT_MSStruct:
6307 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
6309 case AttributeList::AT_Uuid:
6310 handleUuidAttr(S, D, Attr);
6312 case AttributeList::AT_MSInheritance:
6313 handleMSInheritanceAttr(S, D, Attr);
6315 case AttributeList::AT_SelectAny:
6316 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6318 case AttributeList::AT_Thread:
6319 handleDeclspecThreadAttr(S, D, Attr);
6322 case AttributeList::AT_AbiTag:
6323 handleAbiTagAttr(S, D, Attr);
6326 // Thread safety attributes:
6327 case AttributeList::AT_AssertExclusiveLock:
6328 handleAssertExclusiveLockAttr(S, D, Attr);
6330 case AttributeList::AT_AssertSharedLock:
6331 handleAssertSharedLockAttr(S, D, Attr);
6333 case AttributeList::AT_GuardedVar:
6334 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6336 case AttributeList::AT_PtGuardedVar:
6337 handlePtGuardedVarAttr(S, D, Attr);
6339 case AttributeList::AT_ScopedLockable:
6340 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6342 case AttributeList::AT_NoSanitize:
6343 handleNoSanitizeAttr(S, D, Attr);
6345 case AttributeList::AT_NoSanitizeSpecific:
6346 handleNoSanitizeSpecificAttr(S, D, Attr);
6348 case AttributeList::AT_NoThreadSafetyAnalysis:
6349 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
6351 case AttributeList::AT_GuardedBy:
6352 handleGuardedByAttr(S, D, Attr);
6354 case AttributeList::AT_PtGuardedBy:
6355 handlePtGuardedByAttr(S, D, Attr);
6357 case AttributeList::AT_ExclusiveTrylockFunction:
6358 handleExclusiveTrylockFunctionAttr(S, D, Attr);
6360 case AttributeList::AT_LockReturned:
6361 handleLockReturnedAttr(S, D, Attr);
6363 case AttributeList::AT_LocksExcluded:
6364 handleLocksExcludedAttr(S, D, Attr);
6366 case AttributeList::AT_SharedTrylockFunction:
6367 handleSharedTrylockFunctionAttr(S, D, Attr);
6369 case AttributeList::AT_AcquiredBefore:
6370 handleAcquiredBeforeAttr(S, D, Attr);
6372 case AttributeList::AT_AcquiredAfter:
6373 handleAcquiredAfterAttr(S, D, Attr);
6376 // Capability analysis attributes.
6377 case AttributeList::AT_Capability:
6378 case AttributeList::AT_Lockable:
6379 handleCapabilityAttr(S, D, Attr);
6381 case AttributeList::AT_RequiresCapability:
6382 handleRequiresCapabilityAttr(S, D, Attr);
6385 case AttributeList::AT_AssertCapability:
6386 handleAssertCapabilityAttr(S, D, Attr);
6388 case AttributeList::AT_AcquireCapability:
6389 handleAcquireCapabilityAttr(S, D, Attr);
6391 case AttributeList::AT_ReleaseCapability:
6392 handleReleaseCapabilityAttr(S, D, Attr);
6394 case AttributeList::AT_TryAcquireCapability:
6395 handleTryAcquireCapabilityAttr(S, D, Attr);
6398 // Consumed analysis attributes.
6399 case AttributeList::AT_Consumable:
6400 handleConsumableAttr(S, D, Attr);
6402 case AttributeList::AT_ConsumableAutoCast:
6403 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6405 case AttributeList::AT_ConsumableSetOnRead:
6406 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6408 case AttributeList::AT_CallableWhen:
6409 handleCallableWhenAttr(S, D, Attr);
6411 case AttributeList::AT_ParamTypestate:
6412 handleParamTypestateAttr(S, D, Attr);
6414 case AttributeList::AT_ReturnTypestate:
6415 handleReturnTypestateAttr(S, D, Attr);
6417 case AttributeList::AT_SetTypestate:
6418 handleSetTypestateAttr(S, D, Attr);
6420 case AttributeList::AT_TestTypestate:
6421 handleTestTypestateAttr(S, D, Attr);
6424 // Type safety attributes.
6425 case AttributeList::AT_ArgumentWithTypeTag:
6426 handleArgumentWithTypeTagAttr(S, D, Attr);
6428 case AttributeList::AT_TypeTagForDatatype:
6429 handleTypeTagForDatatypeAttr(S, D, Attr);
6431 case AttributeList::AT_RenderScriptKernel:
6432 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
6435 case AttributeList::AT_XRayInstrument:
6436 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6438 case AttributeList::AT_XRayLogArgs:
6439 handleXRayLogArgsAttr(S, D, Attr);
6444 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6445 /// attribute list to the specified decl, ignoring any type attributes.
6446 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
6447 const AttributeList *AttrList,
6448 bool IncludeCXX11Attributes) {
6449 for (const AttributeList* l = AttrList; l; l = l->getNext())
6450 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
6452 // FIXME: We should be able to handle these cases in TableGen.
6454 // static int a9 __attribute__((weakref));
6455 // but that looks really pointless. We reject it.
6456 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
6457 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6458 << cast<NamedDecl>(D);
6459 D->dropAttr<WeakRefAttr>();
6463 // FIXME: We should be able to handle this in TableGen as well. It would be
6464 // good to have a way to specify "these attributes must appear as a group",
6465 // for these. Additionally, it would be good to have a way to specify "these
6466 // attribute must never appear as a group" for attributes like cold and hot.
6467 if (!D->hasAttr<OpenCLKernelAttr>()) {
6468 // These attributes cannot be applied to a non-kernel function.
6469 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
6470 // FIXME: This emits a different error message than
6471 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
6472 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6473 D->setInvalidDecl();
6474 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
6475 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6476 D->setInvalidDecl();
6477 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
6478 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6479 D->setInvalidDecl();
6480 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6481 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6482 << A << ExpectedKernelFunction;
6483 D->setInvalidDecl();
6484 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
6485 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6486 << A << ExpectedKernelFunction;
6487 D->setInvalidDecl();
6488 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6489 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6490 << A << ExpectedKernelFunction;
6491 D->setInvalidDecl();
6492 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6493 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6494 << A << ExpectedKernelFunction;
6495 D->setInvalidDecl();
6500 // Helper for delayed proccessing TransparentUnion attribute.
6501 void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) {
6502 for (const AttributeList *Attr = AttrList; Attr; Attr = Attr->getNext())
6503 if (Attr->getKind() == AttributeList::AT_TransparentUnion) {
6504 handleTransparentUnionAttr(*this, D, *Attr);
6509 // Annotation attributes are the only attributes allowed after an access
6511 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6512 const AttributeList *AttrList) {
6513 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6514 if (l->getKind() == AttributeList::AT_Annotate) {
6515 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
6517 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6525 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
6526 /// contains any decl attributes that we should warn about.
6527 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6528 for ( ; A; A = A->getNext()) {
6529 // Only warn if the attribute is an unignored, non-type attribute.
6530 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
6531 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6533 if (A->getKind() == AttributeList::UnknownAttribute) {
6534 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6535 << A->getName() << A->getRange();
6537 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6538 << A->getName() << A->getRange();
6543 /// checkUnusedDeclAttributes - Given a declarator which is not being
6544 /// used to build a declaration, complain about any decl attributes
6545 /// which might be lying around on it.
6546 void Sema::checkUnusedDeclAttributes(Declarator &D) {
6547 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6548 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6549 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6550 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6553 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
6554 /// \#pragma weak needs a non-definition decl and source may not have one.
6555 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6556 SourceLocation Loc) {
6557 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
6558 NamedDecl *NewD = nullptr;
6559 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6560 FunctionDecl *NewFD;
6561 // FIXME: Missing call to CheckFunctionDeclaration().
6563 // FIXME: Is the qualifier info correct?
6564 // FIXME: Is the DeclContext correct?
6565 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6566 Loc, Loc, DeclarationName(II),
6567 FD->getType(), FD->getTypeSourceInfo(),
6568 SC_None, false/*isInlineSpecified*/,
6570 false/*isConstexprSpecified*/);
6573 if (FD->getQualifier())
6574 NewFD->setQualifierInfo(FD->getQualifierLoc());
6576 // Fake up parameter variables; they are declared as if this were
6578 QualType FDTy = FD->getType();
6579 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6580 SmallVector<ParmVarDecl*, 16> Params;
6581 for (const auto &AI : FT->param_types()) {
6582 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6583 Param->setScopeInfo(0, Params.size());
6584 Params.push_back(Param);
6586 NewFD->setParams(Params);
6588 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6589 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6590 VD->getInnerLocStart(), VD->getLocation(), II,
6591 VD->getType(), VD->getTypeSourceInfo(),
6592 VD->getStorageClass());
6593 if (VD->getQualifier()) {
6594 VarDecl *NewVD = cast<VarDecl>(NewD);
6595 NewVD->setQualifierInfo(VD->getQualifierLoc());
6601 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6602 /// applied to it, possibly with an alias.
6603 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6604 if (W.getUsed()) return; // only do this once
6606 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6607 IdentifierInfo *NDId = ND->getIdentifier();
6608 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6609 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6611 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6612 WeakTopLevelDecl.push_back(NewD);
6613 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6614 // to insert Decl at TU scope, sorry.
6615 DeclContext *SavedContext = CurContext;
6616 CurContext = Context.getTranslationUnitDecl();
6617 NewD->setDeclContext(CurContext);
6618 NewD->setLexicalDeclContext(CurContext);
6619 PushOnScopeChains(NewD, S);
6620 CurContext = SavedContext;
6621 } else { // just add weak to existing
6622 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6626 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6627 // It's valid to "forward-declare" #pragma weak, in which case we
6629 LoadExternalWeakUndeclaredIdentifiers();
6630 if (!WeakUndeclaredIdentifiers.empty()) {
6631 NamedDecl *ND = nullptr;
6632 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6633 if (VD->isExternC())
6635 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6636 if (FD->isExternC())
6639 if (IdentifierInfo *Id = ND->getIdentifier()) {
6640 auto I = WeakUndeclaredIdentifiers.find(Id);
6641 if (I != WeakUndeclaredIdentifiers.end()) {
6642 WeakInfo W = I->second;
6643 DeclApplyPragmaWeak(S, ND, W);
6644 WeakUndeclaredIdentifiers[Id] = W;
6651 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6652 /// it, apply them to D. This is a bit tricky because PD can have attributes
6653 /// specified in many different places, and we need to find and apply them all.
6654 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6655 // Apply decl attributes from the DeclSpec if present.
6656 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6657 ProcessDeclAttributeList(S, D, Attrs);
6659 // Walk the declarator structure, applying decl attributes that were in a type
6660 // position to the decl itself. This handles cases like:
6661 // int *__attr__(x)** D;
6662 // when X is a decl attribute.
6663 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6664 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6665 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6667 // Finally, apply any attributes on the decl itself.
6668 if (const AttributeList *Attrs = PD.getAttributes())
6669 ProcessDeclAttributeList(S, D, Attrs);
6671 // Apply additional attributes specified by '#pragma clang attribute'.
6672 AddPragmaAttributes(S, D);
6675 /// Is the given declaration allowed to use a forbidden type?
6676 /// If so, it'll still be annotated with an attribute that makes it
6677 /// illegal to actually use.
6678 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6679 const DelayedDiagnostic &diag,
6680 UnavailableAttr::ImplicitReason &reason) {
6681 // Private ivars are always okay. Unfortunately, people don't
6682 // always properly make their ivars private, even in system headers.
6683 // Plus we need to make fields okay, too.
6684 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6685 !isa<FunctionDecl>(decl))
6688 // Silently accept unsupported uses of __weak in both user and system
6689 // declarations when it's been disabled, for ease of integration with
6690 // -fno-objc-arc files. We do have to take some care against attempts
6691 // to define such things; for now, we've only done that for ivars
6693 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6694 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6695 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6696 reason = UnavailableAttr::IR_ForbiddenWeak;
6701 // Allow all sorts of things in system headers.
6702 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6703 // Currently, all the failures dealt with this way are due to ARC
6705 reason = UnavailableAttr::IR_ARCForbiddenType;
6712 /// Handle a delayed forbidden-type diagnostic.
6713 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6715 auto reason = UnavailableAttr::IR_None;
6716 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6717 assert(reason && "didn't set reason?");
6718 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6722 if (S.getLangOpts().ObjCAutoRefCount)
6723 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6724 // FIXME: we may want to suppress diagnostics for all
6725 // kind of forbidden type messages on unavailable functions.
6726 if (FD->hasAttr<UnavailableAttr>() &&
6727 diag.getForbiddenTypeDiagnostic() ==
6728 diag::err_arc_array_param_no_ownership) {
6729 diag.Triggered = true;
6734 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6735 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6736 diag.Triggered = true;
6739 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6741 // Check each AvailabilityAttr to find the one for this platform.
6742 for (const auto *A : D->attrs()) {
6743 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6744 // FIXME: this is copied from CheckAvailability. We should try to
6747 // Check if this is an App Extension "platform", and if so chop off
6748 // the suffix for matching with the actual platform.
6749 StringRef ActualPlatform = Avail->getPlatform()->getName();
6750 StringRef RealizedPlatform = ActualPlatform;
6751 if (Context.getLangOpts().AppExt) {
6752 size_t suffix = RealizedPlatform.rfind("_app_extension");
6753 if (suffix != StringRef::npos)
6754 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6757 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6759 // Match the platform name.
6760 if (RealizedPlatform == TargetPlatform)
6767 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6768 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6769 /// in a deprecated context, but not the other way around.
6770 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6771 VersionTuple DeclVersion,
6773 assert(K != AR_Available && "Expected an unavailable declaration here!");
6775 // Checks if we should emit the availability diagnostic in the context of C.
6776 auto CheckContext = [&](const Decl *C) {
6777 if (K == AR_NotYetIntroduced) {
6778 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6779 if (AA->getIntroduced() >= DeclVersion)
6781 } else if (K == AR_Deprecated)
6782 if (C->isDeprecated())
6785 if (C->isUnavailable())
6790 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6791 // on nested declarations in an @interface having the availability of the
6792 // interface when they really shouldn't: they are members of the enclosing
6793 // context, and can referenced from there.
6794 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6795 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6796 if (CheckContext(OrigCtx))
6799 // An implementation implicitly has the availability of the interface.
6800 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6801 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6802 if (CheckContext(Interface))
6805 // A category implicitly has the availability of the interface.
6806 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6807 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6808 if (CheckContext(Interface))
6813 if (CheckContext(Ctx))
6816 // An implementation implicitly has the availability of the interface.
6817 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6818 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6819 if (CheckContext(Interface))
6822 // A category implicitly has the availability of the interface.
6823 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6824 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6825 if (CheckContext(Interface))
6827 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6832 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
6833 Decl *Ctx, const NamedDecl *D,
6834 StringRef Message, SourceLocation Loc,
6835 const ObjCInterfaceDecl *UnknownObjCClass,
6836 const ObjCPropertyDecl *ObjCProperty,
6837 bool ObjCPropertyAccess) {
6838 // Diagnostics for deprecated or unavailable.
6839 unsigned diag, diag_message, diag_fwdclass_message;
6840 unsigned diag_available_here = diag::note_availability_specified_here;
6841 SourceLocation NoteLocation = D->getLocation();
6843 // Matches 'diag::note_property_attribute' options.
6844 unsigned property_note_select;
6846 // Matches diag::note_availability_specified_here.
6847 unsigned available_here_select_kind;
6849 VersionTuple DeclVersion;
6850 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6851 DeclVersion = AA->getIntroduced();
6853 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6858 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6859 : diag::warn_property_method_deprecated;
6860 diag_message = diag::warn_deprecated_message;
6861 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6862 property_note_select = /* deprecated */ 0;
6863 available_here_select_kind = /* deprecated */ 2;
6864 if (const auto *attr = D->getAttr<DeprecatedAttr>())
6865 NoteLocation = attr->getLocation();
6868 case AR_Unavailable:
6869 diag = !ObjCPropertyAccess ? diag::err_unavailable
6870 : diag::err_property_method_unavailable;
6871 diag_message = diag::err_unavailable_message;
6872 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6873 property_note_select = /* unavailable */ 1;
6874 available_here_select_kind = /* unavailable */ 0;
6876 if (auto attr = D->getAttr<UnavailableAttr>()) {
6877 if (attr->isImplicit() && attr->getImplicitReason()) {
6878 // Most of these failures are due to extra restrictions in ARC;
6879 // reflect that in the primary diagnostic when applicable.
6880 auto flagARCError = [&] {
6881 if (S.getLangOpts().ObjCAutoRefCount &&
6882 S.getSourceManager().isInSystemHeader(D->getLocation()))
6883 diag = diag::err_unavailable_in_arc;
6886 switch (attr->getImplicitReason()) {
6887 case UnavailableAttr::IR_None: break;
6889 case UnavailableAttr::IR_ARCForbiddenType:
6891 diag_available_here = diag::note_arc_forbidden_type;
6894 case UnavailableAttr::IR_ForbiddenWeak:
6895 if (S.getLangOpts().ObjCWeakRuntime)
6896 diag_available_here = diag::note_arc_weak_disabled;
6898 diag_available_here = diag::note_arc_weak_no_runtime;
6901 case UnavailableAttr::IR_ARCForbiddenConversion:
6903 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6906 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6908 diag_available_here = diag::note_arc_init_returns_unrelated;
6911 case UnavailableAttr::IR_ARCFieldWithOwnership:
6913 diag_available_here = diag::note_arc_field_with_ownership;
6920 case AR_NotYetIntroduced:
6921 diag = diag::warn_partial_availability;
6922 diag_message = diag::warn_partial_message;
6923 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6924 property_note_select = /* partial */ 2;
6925 available_here_select_kind = /* partial */ 3;
6929 llvm_unreachable("Warning for availability of available declaration?");
6932 CharSourceRange UseRange;
6933 StringRef Replacement;
6934 if (K == AR_Deprecated) {
6935 if (auto attr = D->getAttr<DeprecatedAttr>())
6936 Replacement = attr->getReplacement();
6937 if (auto attr = getAttrForPlatform(S.Context, D))
6938 Replacement = attr->getReplacement();
6940 if (!Replacement.empty())
6942 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6945 if (!Message.empty()) {
6946 S.Diag(Loc, diag_message) << D << Message
6947 << (UseRange.isValid() ?
6948 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6950 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6951 << ObjCProperty->getDeclName() << property_note_select;
6952 } else if (!UnknownObjCClass) {
6953 S.Diag(Loc, diag) << D
6954 << (UseRange.isValid() ?
6955 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6957 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6958 << ObjCProperty->getDeclName() << property_note_select;
6960 S.Diag(Loc, diag_fwdclass_message) << D
6961 << (UseRange.isValid() ?
6962 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6963 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6966 // The declaration can have multiple availability attributes, we are looking
6968 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6969 if (A && A->isInherited()) {
6970 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6971 Redecl = Redecl->getPreviousDecl()) {
6972 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6974 if (AForRedecl && !AForRedecl->isInherited()) {
6975 // If D is a declaration with inherited attributes, the note should
6976 // point to the declaration with actual attributes.
6977 S.Diag(Redecl->getLocation(), diag_available_here) << D
6978 << available_here_select_kind;
6984 S.Diag(NoteLocation, diag_available_here)
6985 << D << available_here_select_kind;
6987 if (K == AR_NotYetIntroduced)
6988 S.Diag(Loc, diag::note_partial_availability_silence) << D;
6991 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6993 assert(DD.Kind == DelayedDiagnostic::Availability &&
6994 "Expected an availability diagnostic here");
6996 DD.Triggered = true;
6997 DoEmitAvailabilityWarning(
6998 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
6999 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
7000 DD.getObjCProperty(), false);
7003 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
7004 assert(DelayedDiagnostics.getCurrentPool());
7005 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
7006 DelayedDiagnostics.popWithoutEmitting(state);
7008 // When delaying diagnostics to run in the context of a parsed
7009 // declaration, we only want to actually emit anything if parsing
7013 // We emit all the active diagnostics in this pool or any of its
7014 // parents. In general, we'll get one pool for the decl spec
7015 // and a child pool for each declarator; in a decl group like:
7016 // deprecated_typedef foo, *bar, baz();
7017 // only the declarator pops will be passed decls. This is correct;
7018 // we really do need to consider delayed diagnostics from the decl spec
7019 // for each of the different declarations.
7020 const DelayedDiagnosticPool *pool = &poppedPool;
7022 for (DelayedDiagnosticPool::pool_iterator
7023 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
7024 // This const_cast is a bit lame. Really, Triggered should be mutable.
7025 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
7029 switch (diag.Kind) {
7030 case DelayedDiagnostic::Availability:
7031 // Don't bother giving deprecation/unavailable diagnostics if
7032 // the decl is invalid.
7033 if (!decl->isInvalidDecl())
7034 handleDelayedAvailabilityCheck(*this, diag, decl);
7037 case DelayedDiagnostic::Access:
7038 HandleDelayedAccessCheck(diag, decl);
7041 case DelayedDiagnostic::ForbiddenType:
7042 handleDelayedForbiddenType(*this, diag, decl);
7046 } while ((pool = pool->getParent()));
7049 /// Given a set of delayed diagnostics, re-emit them as if they had
7050 /// been delayed in the current context instead of in the given pool.
7051 /// Essentially, this just moves them to the current pool.
7052 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
7053 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
7054 assert(curPool && "re-emitting in undelayed context not supported");
7055 curPool->steal(pool);
7058 void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
7059 NamedDecl *D, StringRef Message,
7061 const ObjCInterfaceDecl *UnknownObjCClass,
7062 const ObjCPropertyDecl *ObjCProperty,
7063 bool ObjCPropertyAccess) {
7064 // Delay if we're currently parsing a declaration.
7065 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
7066 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
7067 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
7068 ObjCPropertyAccess));
7072 Decl *Ctx = cast<Decl>(getCurLexicalContext());
7073 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
7074 ObjCProperty, ObjCPropertyAccess);
7079 /// \brief This class implements -Wunguarded-availability.
7081 /// This is done with a traversal of the AST of a function that makes reference
7082 /// to a partially available declaration. Whenever we encounter an \c if of the
7083 /// form: \c if(@available(...)), we use the version from the condition to visit
7084 /// the then statement.
7085 class DiagnoseUnguardedAvailability
7086 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
7087 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
7092 /// Stack of potentially nested 'if (@available(...))'s.
7093 SmallVector<VersionTuple, 8> AvailabilityStack;
7095 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
7098 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
7099 : SemaRef(SemaRef), Ctx(Ctx) {
7100 AvailabilityStack.push_back(
7101 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
7104 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
7106 bool TraverseIfStmt(IfStmt *If);
7108 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
7109 if (ObjCMethodDecl *D = Msg->getMethodDecl())
7110 DiagnoseDeclAvailability(
7111 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
7115 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
7116 DiagnoseDeclAvailability(DRE->getDecl(),
7117 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
7121 bool VisitMemberExpr(MemberExpr *ME) {
7122 DiagnoseDeclAvailability(ME->getMemberDecl(),
7123 SourceRange(ME->getLocStart(), ME->getLocEnd()));
7127 bool VisitTypeLoc(TypeLoc Ty);
7130 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
7131 NamedDecl *D, SourceRange Range) {
7133 VersionTuple ContextVersion = AvailabilityStack.back();
7134 if (AvailabilityResult Result =
7135 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
7136 // All other diagnostic kinds have already been handled in
7137 // DiagnoseAvailabilityOfDecl.
7138 if (Result != AR_NotYetIntroduced)
7141 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
7142 VersionTuple Introduced = AA->getIntroduced();
7144 if (ContextVersion >= Introduced)
7147 // If the context of this function is less available than D, we should not
7148 // emit a diagnostic.
7149 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
7152 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
7154 << AvailabilityAttr::getPrettyPlatformName(
7155 SemaRef.getASTContext().getTargetInfo().getPlatformName())
7156 << Introduced.getAsString();
7158 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
7159 << D << /* partial */ 3;
7161 // FIXME: Replace this with a fixit diagnostic.
7162 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
7167 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
7168 const Type *TyPtr = Ty.getTypePtr();
7169 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
7171 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
7172 TagDecl *TD = TT->getDecl();
7173 DiagnoseDeclAvailability(TD, Range);
7175 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
7176 TypedefNameDecl *D = TD->getDecl();
7177 DiagnoseDeclAvailability(D, Range);
7179 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
7180 if (NamedDecl *D = ObjCO->getInterface())
7181 DiagnoseDeclAvailability(D, Range);
7187 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
7188 VersionTuple CondVersion;
7189 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
7190 CondVersion = E->getVersion();
7192 // If we're using the '*' case here or if this check is redundant, then we
7193 // use the enclosing version to check both branches.
7194 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
7195 return Base::TraverseStmt(If->getThen()) &&
7196 Base::TraverseStmt(If->getElse());
7198 // This isn't an availability checking 'if', we can just continue.
7199 return Base::TraverseIfStmt(If);
7202 AvailabilityStack.push_back(CondVersion);
7203 bool ShouldContinue = TraverseStmt(If->getThen());
7204 AvailabilityStack.pop_back();
7206 return ShouldContinue && TraverseStmt(If->getElse());
7209 } // end anonymous namespace
7211 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
7212 Stmt *Body = nullptr;
7214 if (auto *FD = D->getAsFunction()) {
7215 // FIXME: We only examine the pattern decl for availability violations now,
7216 // but we should also examine instantiated templates.
7217 if (FD->isTemplateInstantiation())
7220 Body = FD->getBody();
7221 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
7222 Body = MD->getBody();
7223 else if (auto *BD = dyn_cast<BlockDecl>(D))
7224 Body = BD->getBody();
7226 assert(Body && "Need a body here!");
7228 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);