1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements decl-related attribute processing.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.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/ASTMutationListener.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 "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/MathExtras.h"
37 using namespace clang;
40 namespace AttributeLangSupport {
46 } // end namespace AttributeLangSupport
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 /// isFunctionOrMethod - Return true if the given decl has function
53 /// type (function or function-typed variable) or an Objective-C
55 static bool isFunctionOrMethod(const Decl *D) {
56 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
59 /// \brief Return true if the given decl has function type (function or
60 /// function-typed variable) or an Objective-C method or a block.
61 static bool isFunctionOrMethodOrBlock(const Decl *D) {
62 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
65 /// Return true if the given decl has a declarator that should have
66 /// been processed by Sema::GetTypeForDeclarator.
67 static bool hasDeclarator(const Decl *D) {
68 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
69 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
70 isa<ObjCPropertyDecl>(D);
73 /// hasFunctionProto - Return true if the given decl has a argument
74 /// information. This decl should have already passed
75 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
76 static bool hasFunctionProto(const Decl *D) {
77 if (const FunctionType *FnTy = D->getFunctionType())
78 return isa<FunctionProtoType>(FnTy);
79 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
82 /// getFunctionOrMethodNumParams - Return number of function or method
83 /// parameters. It is an error to call this on a K&R function (use
84 /// hasFunctionProto first).
85 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
86 if (const FunctionType *FnTy = D->getFunctionType())
87 return cast<FunctionProtoType>(FnTy)->getNumParams();
88 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
89 return BD->getNumParams();
90 return cast<ObjCMethodDecl>(D)->param_size();
93 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
94 if (const FunctionType *FnTy = D->getFunctionType())
95 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
96 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
97 return BD->getParamDecl(Idx)->getType();
99 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
102 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
103 if (const auto *FD = dyn_cast<FunctionDecl>(D))
104 return FD->getParamDecl(Idx)->getSourceRange();
105 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
106 return MD->parameters()[Idx]->getSourceRange();
107 if (const auto *BD = dyn_cast<BlockDecl>(D))
108 return BD->getParamDecl(Idx)->getSourceRange();
109 return SourceRange();
112 static QualType getFunctionOrMethodResultType(const Decl *D) {
113 if (const FunctionType *FnTy = D->getFunctionType())
114 return cast<FunctionType>(FnTy)->getReturnType();
115 return cast<ObjCMethodDecl>(D)->getReturnType();
118 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
119 if (const auto *FD = dyn_cast<FunctionDecl>(D))
120 return FD->getReturnTypeSourceRange();
121 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
122 return MD->getReturnTypeSourceRange();
123 return SourceRange();
126 static bool isFunctionOrMethodVariadic(const Decl *D) {
127 if (const FunctionType *FnTy = D->getFunctionType()) {
128 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
129 return proto->isVariadic();
131 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
132 return BD->isVariadic();
134 return cast<ObjCMethodDecl>(D)->isVariadic();
137 static bool isInstanceMethod(const Decl *D) {
138 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
139 return MethodDecl->isInstance();
143 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
144 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
148 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
152 IdentifierInfo* ClsName = Cls->getIdentifier();
154 // FIXME: Should we walk the chain of classes?
155 return ClsName == &Ctx.Idents.get("NSString") ||
156 ClsName == &Ctx.Idents.get("NSMutableString");
159 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
160 const PointerType *PT = T->getAs<PointerType>();
164 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
168 const RecordDecl *RD = RT->getDecl();
169 if (RD->getTagKind() != TTK_Struct)
172 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
175 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
176 // FIXME: Include the type in the argument list.
177 return Attr.getNumArgs() + Attr.hasParsedType();
180 template <typename Compare>
181 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
182 unsigned Num, unsigned Diag,
184 if (Comp(getNumAttributeArgs(Attr), Num)) {
185 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
192 /// \brief Check if the attribute has exactly as many args as Num. May
194 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
196 return checkAttributeNumArgsImpl(S, Attr, Num,
197 diag::err_attribute_wrong_number_arguments,
198 std::not_equal_to<unsigned>());
201 /// \brief Check if the attribute has at least as many args as Num. May
203 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
205 return checkAttributeNumArgsImpl(S, Attr, Num,
206 diag::err_attribute_too_few_arguments,
207 std::less<unsigned>());
210 /// \brief Check if the attribute has at most as many args as Num. May
212 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
214 return checkAttributeNumArgsImpl(S, Attr, Num,
215 diag::err_attribute_too_many_arguments,
216 std::greater<unsigned>());
219 /// \brief If Expr is a valid integer constant, get the value of the integer
220 /// expression and return success or failure. May output an error.
221 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
222 const Expr *Expr, uint32_t &Val,
223 unsigned Idx = UINT_MAX) {
225 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
226 !Expr->isIntegerConstantExpr(I, S.Context)) {
228 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
229 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
230 << Expr->getSourceRange();
232 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
233 << Attr.getName() << AANT_ArgumentIntegerConstant
234 << Expr->getSourceRange();
239 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
240 << I.toString(10, false) << 32 << /* Unsigned */ 1;
244 Val = (uint32_t)I.getZExtValue();
248 /// \brief Diagnose mutually exclusive attributes when present on a given
249 /// declaration. Returns true if diagnosed.
250 template <typename AttrTy>
251 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
252 IdentifierInfo *Ident) {
253 if (AttrTy *A = D->getAttr<AttrTy>()) {
254 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
256 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
262 /// \brief Check if IdxExpr is a valid parameter index for a function or
263 /// instance method D. May output an error.
265 /// \returns true if IdxExpr is a valid index.
266 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
267 const AttributeList &Attr,
271 assert(isFunctionOrMethodOrBlock(D));
273 // In C++ the implicit 'this' function parameter also counts.
274 // Parameters are counted from one.
275 bool HP = hasFunctionProto(D);
276 bool HasImplicitThisParam = isInstanceMethod(D);
277 bool IV = HP && isFunctionOrMethodVariadic(D);
279 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
282 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
283 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
284 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
285 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
286 << IdxExpr->getSourceRange();
290 Idx = IdxInt.getLimitedValue();
291 if (Idx < 1 || (!IV && Idx > NumParams)) {
292 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
293 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
296 Idx--; // Convert to zero-based.
297 if (HasImplicitThisParam) {
299 S.Diag(Attr.getLoc(),
300 diag::err_attribute_invalid_implicit_this_argument)
301 << Attr.getName() << IdxExpr->getSourceRange();
310 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
311 /// If not emit an error and return false. If the argument is an identifier it
312 /// will emit an error with a fixit hint and treat it as if it was a string
314 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
315 unsigned ArgNum, StringRef &Str,
316 SourceLocation *ArgLocation) {
317 // Look for identifiers. If we have one emit a hint to fix it to a literal.
318 if (Attr.isArgIdent(ArgNum)) {
319 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
320 Diag(Loc->Loc, diag::err_attribute_argument_type)
321 << Attr.getName() << AANT_ArgumentString
322 << FixItHint::CreateInsertion(Loc->Loc, "\"")
323 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
324 Str = Loc->Ident->getName();
326 *ArgLocation = Loc->Loc;
330 // Now check for an actual string literal.
331 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
332 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
334 *ArgLocation = ArgExpr->getLocStart();
336 if (!Literal || !Literal->isAscii()) {
337 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
338 << Attr.getName() << AANT_ArgumentString;
342 Str = Literal->getString();
346 /// \brief Applies the given attribute to the Decl without performing any
347 /// additional semantic checking.
348 template <typename AttrType>
349 static void handleSimpleAttribute(Sema &S, Decl *D,
350 const AttributeList &Attr) {
351 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
352 Attr.getAttributeSpellingListIndex()));
355 template <typename AttrType>
356 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
357 const AttributeList &Attr) {
358 handleSimpleAttribute<AttrType>(S, D, Attr);
361 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't
362 /// already have one of the given incompatible attributes.
363 template <typename AttrType, typename IncompatibleAttrType,
364 typename... IncompatibleAttrTypes>
365 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
366 const AttributeList &Attr) {
367 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
370 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
374 /// \brief Check if the passed-in expression is of type int or bool.
375 static bool isIntOrBool(Expr *Exp) {
376 QualType QT = Exp->getType();
377 return QT->isBooleanType() || QT->isIntegerType();
381 // Check to see if the type is a smart pointer of some kind. We assume
382 // it's a smart pointer if it defines both operator-> and operator*.
383 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
384 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
385 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
389 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
390 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
397 /// \brief Check if passed in Decl is a pointer type.
398 /// Note that this function may produce an error message.
399 /// \return true if the Decl is a pointer type; false otherwise
400 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
401 const AttributeList &Attr) {
402 const ValueDecl *vd = cast<ValueDecl>(D);
403 QualType QT = vd->getType();
404 if (QT->isAnyPointerType())
407 if (const RecordType *RT = QT->getAs<RecordType>()) {
408 // If it's an incomplete type, it could be a smart pointer; skip it.
409 // (We don't want to force template instantiation if we can avoid it,
410 // since that would alter the order in which templates are instantiated.)
411 if (RT->isIncompleteType())
414 if (threadSafetyCheckIsSmartPointer(S, RT))
418 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
419 << Attr.getName() << QT;
423 /// \brief Checks that the passed in QualType either is of RecordType or points
424 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
425 static const RecordType *getRecordType(QualType QT) {
426 if (const RecordType *RT = QT->getAs<RecordType>())
429 // Now check if we point to record type.
430 if (const PointerType *PT = QT->getAs<PointerType>())
431 return PT->getPointeeType()->getAs<RecordType>();
436 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
437 const RecordType *RT = getRecordType(Ty);
442 // Don't check for the capability if the class hasn't been defined yet.
443 if (RT->isIncompleteType())
446 // Allow smart pointers to be used as capability objects.
447 // FIXME -- Check the type that the smart pointer points to.
448 if (threadSafetyCheckIsSmartPointer(S, RT))
451 // Check if the record itself has a capability.
452 RecordDecl *RD = RT->getDecl();
453 if (RD->hasAttr<CapabilityAttr>())
456 // Else check if any base classes have a capability.
457 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
458 CXXBasePaths BPaths(false, false);
459 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
460 const auto *Type = BS->getType()->getAs<RecordType>();
461 return Type->getDecl()->hasAttr<CapabilityAttr>();
468 static bool checkTypedefTypeForCapability(QualType Ty) {
469 const auto *TD = Ty->getAs<TypedefType>();
473 TypedefNameDecl *TN = TD->getDecl();
477 return TN->hasAttr<CapabilityAttr>();
480 static bool typeHasCapability(Sema &S, QualType Ty) {
481 if (checkTypedefTypeForCapability(Ty))
484 if (checkRecordTypeForCapability(S, Ty))
490 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
491 // Capability expressions are simple expressions involving the boolean logic
492 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
493 // a DeclRefExpr is found, its type should be checked to determine whether it
494 // is a capability or not.
496 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
497 return typeHasCapability(S, E->getType());
498 else if (const auto *E = dyn_cast<CastExpr>(Ex))
499 return isCapabilityExpr(S, E->getSubExpr());
500 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
501 return isCapabilityExpr(S, E->getSubExpr());
502 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
503 if (E->getOpcode() == UO_LNot)
504 return isCapabilityExpr(S, E->getSubExpr());
506 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
507 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
508 return isCapabilityExpr(S, E->getLHS()) &&
509 isCapabilityExpr(S, E->getRHS());
516 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
517 /// a capability object.
518 /// \param Sidx The attribute argument index to start checking with.
519 /// \param ParamIdxOk Whether an argument can be indexing into a function
521 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
522 const AttributeList &Attr,
523 SmallVectorImpl<Expr *> &Args,
525 bool ParamIdxOk = false) {
526 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
527 Expr *ArgExp = Attr.getArgAsExpr(Idx);
529 if (ArgExp->isTypeDependent()) {
530 // FIXME -- need to check this again on template instantiation
531 Args.push_back(ArgExp);
535 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
536 if (StrLit->getLength() == 0 ||
537 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
538 // Pass empty strings to the analyzer without warnings.
539 // Treat "*" as the universal lock.
540 Args.push_back(ArgExp);
544 // We allow constant strings to be used as a placeholder for expressions
545 // that are not valid C++ syntax, but warn that they are ignored.
546 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
548 Args.push_back(ArgExp);
552 QualType ArgTy = ArgExp->getType();
554 // A pointer to member expression of the form &MyClass::mu is treated
555 // specially -- we need to look at the type of the member.
556 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
557 if (UOp->getOpcode() == UO_AddrOf)
558 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
559 if (DRE->getDecl()->isCXXInstanceMember())
560 ArgTy = DRE->getDecl()->getType();
562 // First see if we can just cast to record type, or pointer to record type.
563 const RecordType *RT = getRecordType(ArgTy);
565 // Now check if we index into a record type function param.
566 if(!RT && ParamIdxOk) {
567 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
568 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
570 unsigned int NumParams = FD->getNumParams();
571 llvm::APInt ArgValue = IL->getValue();
572 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
573 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
574 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
575 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
576 << Attr.getName() << Idx + 1 << NumParams;
579 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
583 // If the type does not have a capability, see if the components of the
584 // expression have capabilities. This allows for writing C code where the
585 // capability may be on the type, and the expression is a capability
586 // boolean logic expression. Eg) requires_capability(A || B && !C)
587 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
588 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
589 << Attr.getName() << ArgTy;
591 Args.push_back(ArgExp);
595 //===----------------------------------------------------------------------===//
596 // Attribute Implementations
597 //===----------------------------------------------------------------------===//
599 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
600 const AttributeList &Attr) {
601 if (!threadSafetyCheckIsPointer(S, D, Attr))
604 D->addAttr(::new (S.Context)
605 PtGuardedVarAttr(Attr.getRange(), S.Context,
606 Attr.getAttributeSpellingListIndex()));
609 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
610 const AttributeList &Attr,
612 SmallVector<Expr*, 1> Args;
613 // check that all arguments are lockable objects
614 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
615 unsigned Size = Args.size();
624 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
626 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
629 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
630 Attr.getAttributeSpellingListIndex()));
633 static void handlePtGuardedByAttr(Sema &S, Decl *D,
634 const AttributeList &Attr) {
636 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
639 if (!threadSafetyCheckIsPointer(S, D, Attr))
642 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
644 Attr.getAttributeSpellingListIndex()));
647 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
648 const AttributeList &Attr,
649 SmallVectorImpl<Expr *> &Args) {
650 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
653 // Check that this attribute only applies to lockable types.
654 QualType QT = cast<ValueDecl>(D)->getType();
655 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
656 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
661 // Check that all arguments are lockable objects.
662 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
669 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
670 const AttributeList &Attr) {
671 SmallVector<Expr*, 1> Args;
672 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
675 Expr **StartArg = &Args[0];
676 D->addAttr(::new (S.Context)
677 AcquiredAfterAttr(Attr.getRange(), S.Context,
678 StartArg, Args.size(),
679 Attr.getAttributeSpellingListIndex()));
682 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
683 const AttributeList &Attr) {
684 SmallVector<Expr*, 1> Args;
685 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
688 Expr **StartArg = &Args[0];
689 D->addAttr(::new (S.Context)
690 AcquiredBeforeAttr(Attr.getRange(), S.Context,
691 StartArg, Args.size(),
692 Attr.getAttributeSpellingListIndex()));
695 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
696 const AttributeList &Attr,
697 SmallVectorImpl<Expr *> &Args) {
698 // zero or more arguments ok
699 // check that all arguments are lockable objects
700 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
705 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
706 const AttributeList &Attr) {
707 SmallVector<Expr*, 1> Args;
708 if (!checkLockFunAttrCommon(S, D, Attr, Args))
711 unsigned Size = Args.size();
712 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
713 D->addAttr(::new (S.Context)
714 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
715 Attr.getAttributeSpellingListIndex()));
718 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
719 const AttributeList &Attr) {
720 SmallVector<Expr*, 1> Args;
721 if (!checkLockFunAttrCommon(S, D, Attr, Args))
724 unsigned Size = Args.size();
725 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
726 D->addAttr(::new (S.Context)
727 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
729 Attr.getAttributeSpellingListIndex()));
733 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
734 const AttributeList &Attr,
735 SmallVectorImpl<Expr *> &Args) {
736 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
739 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
740 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
741 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
745 // check that all arguments are lockable objects
746 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
751 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
752 const AttributeList &Attr) {
753 SmallVector<Expr*, 2> Args;
754 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
757 D->addAttr(::new (S.Context)
758 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
759 Attr.getArgAsExpr(0),
760 Args.data(), Args.size(),
761 Attr.getAttributeSpellingListIndex()));
764 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
765 const AttributeList &Attr) {
766 SmallVector<Expr*, 2> Args;
767 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
770 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
771 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
772 Args.size(), Attr.getAttributeSpellingListIndex()));
775 static void handleLockReturnedAttr(Sema &S, Decl *D,
776 const AttributeList &Attr) {
777 // check that the argument is lockable object
778 SmallVector<Expr*, 1> Args;
779 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
780 unsigned Size = Args.size();
784 D->addAttr(::new (S.Context)
785 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
786 Attr.getAttributeSpellingListIndex()));
789 static void handleLocksExcludedAttr(Sema &S, Decl *D,
790 const AttributeList &Attr) {
791 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
794 // check that all arguments are lockable objects
795 SmallVector<Expr*, 1> Args;
796 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
797 unsigned Size = Args.size();
800 Expr **StartArg = &Args[0];
802 D->addAttr(::new (S.Context)
803 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
804 Attr.getAttributeSpellingListIndex()));
807 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
808 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
810 Expr *Cond = Attr.getArgAsExpr(0);
811 if (!Cond->isTypeDependent()) {
812 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
813 if (Converted.isInvalid())
815 Cond = Converted.get();
819 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
822 SmallVector<PartialDiagnosticAt, 8> Diags;
823 if (!Cond->isValueDependent() &&
824 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
826 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
827 for (int I = 0, N = Diags.size(); I != N; ++I)
828 S.Diag(Diags[I].first, Diags[I].second);
832 D->addAttr(::new (S.Context)
833 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
834 Attr.getAttributeSpellingListIndex()));
837 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
838 const AttributeList &Attr) {
839 if (D->hasAttr<PassObjectSizeAttr>()) {
840 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
845 Expr *E = Attr.getArgAsExpr(0);
847 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
850 // pass_object_size's argument is passed in as the second argument of
851 // __builtin_object_size. So, it has the same constraints as that second
852 // argument; namely, it must be in the range [0, 3].
854 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
855 << Attr.getName() << 0 << 3 << E->getSourceRange();
859 // pass_object_size is only supported on constant pointer parameters; as a
860 // kindness to users, we allow the parameter to be non-const for declarations.
861 // At this point, we have no clue if `D` belongs to a function declaration or
862 // definition, so we defer the constness check until later.
863 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
864 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
865 << Attr.getName() << 1;
869 D->addAttr(::new (S.Context)
870 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
871 Attr.getAttributeSpellingListIndex()));
874 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
875 ConsumableAttr::ConsumedState DefaultState;
877 if (Attr.isArgIdent(0)) {
878 IdentifierLoc *IL = Attr.getArgAsIdent(0);
879 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
881 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
882 << Attr.getName() << IL->Ident;
886 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
887 << Attr.getName() << AANT_ArgumentIdentifier;
891 D->addAttr(::new (S.Context)
892 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
893 Attr.getAttributeSpellingListIndex()));
896 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
897 const AttributeList &Attr) {
898 ASTContext &CurrContext = S.getASTContext();
899 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
901 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
902 if (!RD->hasAttr<ConsumableAttr>()) {
903 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
904 RD->getNameAsString();
913 static void handleCallableWhenAttr(Sema &S, Decl *D,
914 const AttributeList &Attr) {
915 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
918 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
921 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
922 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
923 CallableWhenAttr::ConsumedState CallableState;
925 StringRef StateString;
927 if (Attr.isArgIdent(ArgIndex)) {
928 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
929 StateString = Ident->Ident->getName();
932 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
936 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
938 S.Diag(Loc, diag::warn_attribute_type_not_supported)
939 << Attr.getName() << StateString;
943 States.push_back(CallableState);
946 D->addAttr(::new (S.Context)
947 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
948 States.size(), Attr.getAttributeSpellingListIndex()));
951 static void handleParamTypestateAttr(Sema &S, Decl *D,
952 const AttributeList &Attr) {
953 ParamTypestateAttr::ConsumedState ParamState;
955 if (Attr.isArgIdent(0)) {
956 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
957 StringRef StateString = Ident->Ident->getName();
959 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
961 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
962 << Attr.getName() << StateString;
966 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
967 Attr.getName() << AANT_ArgumentIdentifier;
971 // FIXME: This check is currently being done in the analysis. It can be
972 // enabled here only after the parser propagates attributes at
973 // template specialization definition, not declaration.
974 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
975 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
977 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
978 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
979 // ReturnType.getAsString();
983 D->addAttr(::new (S.Context)
984 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
985 Attr.getAttributeSpellingListIndex()));
988 static void handleReturnTypestateAttr(Sema &S, Decl *D,
989 const AttributeList &Attr) {
990 ReturnTypestateAttr::ConsumedState ReturnState;
992 if (Attr.isArgIdent(0)) {
993 IdentifierLoc *IL = Attr.getArgAsIdent(0);
994 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
996 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
997 << Attr.getName() << IL->Ident;
1001 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1002 Attr.getName() << AANT_ArgumentIdentifier;
1006 // FIXME: This check is currently being done in the analysis. It can be
1007 // enabled here only after the parser propagates attributes at
1008 // template specialization definition, not declaration.
1009 //QualType ReturnType;
1011 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1012 // ReturnType = Param->getType();
1014 //} else if (const CXXConstructorDecl *Constructor =
1015 // dyn_cast<CXXConstructorDecl>(D)) {
1016 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1020 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1023 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1025 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1026 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1027 // ReturnType.getAsString();
1031 D->addAttr(::new (S.Context)
1032 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1033 Attr.getAttributeSpellingListIndex()));
1036 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1037 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1040 SetTypestateAttr::ConsumedState NewState;
1041 if (Attr.isArgIdent(0)) {
1042 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1043 StringRef Param = Ident->Ident->getName();
1044 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1045 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1046 << Attr.getName() << Param;
1050 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1051 Attr.getName() << AANT_ArgumentIdentifier;
1055 D->addAttr(::new (S.Context)
1056 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1057 Attr.getAttributeSpellingListIndex()));
1060 static void handleTestTypestateAttr(Sema &S, Decl *D,
1061 const AttributeList &Attr) {
1062 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1065 TestTypestateAttr::ConsumedState TestState;
1066 if (Attr.isArgIdent(0)) {
1067 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1068 StringRef Param = Ident->Ident->getName();
1069 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1070 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1071 << Attr.getName() << Param;
1075 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1076 Attr.getName() << AANT_ArgumentIdentifier;
1080 D->addAttr(::new (S.Context)
1081 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1082 Attr.getAttributeSpellingListIndex()));
1085 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1086 const AttributeList &Attr) {
1087 // Remember this typedef decl, we will need it later for diagnostics.
1088 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1091 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1092 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1093 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1094 Attr.getAttributeSpellingListIndex()));
1095 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1096 // Report warning about changed offset in the newer compiler versions.
1097 if (!FD->getType()->isDependentType() &&
1098 !FD->getType()->isIncompleteType() && FD->isBitField() &&
1099 S.Context.getTypeAlign(FD->getType()) <= 8)
1100 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1102 FD->addAttr(::new (S.Context) PackedAttr(
1103 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1105 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1108 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1109 // The IBOutlet/IBOutletCollection attributes only apply to instance
1110 // variables or properties of Objective-C classes. The outlet must also
1111 // have an object reference type.
1112 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1113 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1114 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1115 << Attr.getName() << VD->getType() << 0;
1119 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1120 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1121 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1122 << Attr.getName() << PD->getType() << 1;
1127 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1134 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1135 if (!checkIBOutletCommon(S, D, Attr))
1138 D->addAttr(::new (S.Context)
1139 IBOutletAttr(Attr.getRange(), S.Context,
1140 Attr.getAttributeSpellingListIndex()));
1143 static void handleIBOutletCollection(Sema &S, Decl *D,
1144 const AttributeList &Attr) {
1146 // The iboutletcollection attribute can have zero or one arguments.
1147 if (Attr.getNumArgs() > 1) {
1148 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1149 << Attr.getName() << 1;
1153 if (!checkIBOutletCommon(S, D, Attr))
1158 if (Attr.hasParsedType())
1159 PT = Attr.getTypeArg();
1161 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1162 S.getScopeForContext(D->getDeclContext()->getParent()));
1164 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1169 TypeSourceInfo *QTLoc = nullptr;
1170 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1172 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1174 // Diagnose use of non-object type in iboutletcollection attribute.
1175 // FIXME. Gnu attribute extension ignores use of builtin types in
1176 // attributes. So, __attribute__((iboutletcollection(char))) will be
1177 // treated as __attribute__((iboutletcollection())).
1178 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1179 S.Diag(Attr.getLoc(),
1180 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1181 : diag::err_iboutletcollection_type) << QT;
1185 D->addAttr(::new (S.Context)
1186 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1187 Attr.getAttributeSpellingListIndex()));
1190 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1192 if (T->isReferenceType())
1195 T = T.getNonReferenceType();
1198 // The nonnull attribute, and other similar attributes, can be applied to a
1199 // transparent union that contains a pointer type.
1200 if (const RecordType *UT = T->getAsUnionType()) {
1201 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1202 RecordDecl *UD = UT->getDecl();
1203 for (const auto *I : UD->fields()) {
1204 QualType QT = I->getType();
1205 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1211 return T->isAnyPointerType() || T->isBlockPointerType();
1214 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1215 SourceRange AttrParmRange,
1216 SourceRange TypeRange,
1217 bool isReturnValue = false) {
1218 if (!S.isValidPointerAttrType(T)) {
1220 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1221 << Attr.getName() << AttrParmRange << TypeRange;
1223 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1224 << Attr.getName() << AttrParmRange << TypeRange << 0;
1230 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1231 SmallVector<unsigned, 8> NonNullArgs;
1232 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1233 Expr *Ex = Attr.getArgAsExpr(I);
1235 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1238 // Is the function argument a pointer type?
1239 if (Idx < getFunctionOrMethodNumParams(D) &&
1240 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1241 Ex->getSourceRange(),
1242 getFunctionOrMethodParamRange(D, Idx)))
1245 NonNullArgs.push_back(Idx);
1248 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1249 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1250 // check if the attribute came from a macro expansion or a template
1252 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1253 S.ActiveTemplateInstantiations.empty()) {
1254 bool AnyPointers = isFunctionOrMethodVariadic(D);
1255 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1256 I != E && !AnyPointers; ++I) {
1257 QualType T = getFunctionOrMethodParamType(D, I);
1258 if (T->isDependentType() || S.isValidPointerAttrType(T))
1263 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1266 unsigned *Start = NonNullArgs.data();
1267 unsigned Size = NonNullArgs.size();
1268 llvm::array_pod_sort(Start, Start + Size);
1269 D->addAttr(::new (S.Context)
1270 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1271 Attr.getAttributeSpellingListIndex()));
1274 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1275 const AttributeList &Attr) {
1276 if (Attr.getNumArgs() > 0) {
1277 if (D->getFunctionType()) {
1278 handleNonNullAttr(S, D, Attr);
1280 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1281 << D->getSourceRange();
1286 // Is the argument a pointer type?
1287 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1288 D->getSourceRange()))
1291 D->addAttr(::new (S.Context)
1292 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1293 Attr.getAttributeSpellingListIndex()));
1296 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1297 const AttributeList &Attr) {
1298 QualType ResultType = getFunctionOrMethodResultType(D);
1299 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1300 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1301 /* isReturnValue */ true))
1304 D->addAttr(::new (S.Context)
1305 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1306 Attr.getAttributeSpellingListIndex()));
1309 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1310 const AttributeList &Attr) {
1311 Expr *E = Attr.getArgAsExpr(0),
1312 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1313 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1314 Attr.getAttributeSpellingListIndex());
1317 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1318 Expr *OE, unsigned SpellingListIndex) {
1319 QualType ResultType = getFunctionOrMethodResultType(D);
1320 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1322 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1323 SourceLocation AttrLoc = AttrRange.getBegin();
1325 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1326 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1327 << &TmpAttr << AttrRange << SR;
1331 if (!E->isValueDependent()) {
1333 if (!E->isIntegerConstantExpr(I, Context)) {
1335 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1336 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1337 << E->getSourceRange();
1339 Diag(AttrLoc, diag::err_attribute_argument_type)
1340 << &TmpAttr << AANT_ArgumentIntegerConstant
1341 << E->getSourceRange();
1345 if (!I.isPowerOf2()) {
1346 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1347 << E->getSourceRange();
1353 if (!OE->isValueDependent()) {
1355 if (!OE->isIntegerConstantExpr(I, Context)) {
1356 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1357 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1358 << OE->getSourceRange();
1364 D->addAttr(::new (Context)
1365 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1368 /// Normalize the attribute, __foo__ becomes foo.
1369 /// Returns true if normalization was applied.
1370 static bool normalizeName(StringRef &AttrName) {
1371 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1372 AttrName.endswith("__")) {
1373 AttrName = AttrName.drop_front(2).drop_back(2);
1379 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1380 // This attribute must be applied to a function declaration. The first
1381 // argument to the attribute must be an identifier, the name of the resource,
1382 // for example: malloc. The following arguments must be argument indexes, the
1383 // arguments must be of integer type for Returns, otherwise of pointer type.
1384 // The difference between Holds and Takes is that a pointer may still be used
1385 // after being held. free() should be __attribute((ownership_takes)), whereas
1386 // a list append function may well be __attribute((ownership_holds)).
1388 if (!AL.isArgIdent(0)) {
1389 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1390 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1394 // Figure out our Kind.
1395 OwnershipAttr::OwnershipKind K =
1396 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1397 AL.getAttributeSpellingListIndex()).getOwnKind();
1401 case OwnershipAttr::Takes:
1402 case OwnershipAttr::Holds:
1403 if (AL.getNumArgs() < 2) {
1404 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1405 << AL.getName() << 2;
1409 case OwnershipAttr::Returns:
1410 if (AL.getNumArgs() > 2) {
1411 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1412 << AL.getName() << 1;
1418 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1420 StringRef ModuleName = Module->getName();
1421 if (normalizeName(ModuleName)) {
1422 Module = &S.PP.getIdentifierTable().get(ModuleName);
1425 SmallVector<unsigned, 8> OwnershipArgs;
1426 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1427 Expr *Ex = AL.getArgAsExpr(i);
1429 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1432 // Is the function argument a pointer type?
1433 QualType T = getFunctionOrMethodParamType(D, Idx);
1434 int Err = -1; // No error
1436 case OwnershipAttr::Takes:
1437 case OwnershipAttr::Holds:
1438 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1441 case OwnershipAttr::Returns:
1442 if (!T->isIntegerType())
1447 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1448 << Ex->getSourceRange();
1452 // Check we don't have a conflict with another ownership attribute.
1453 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1454 // Cannot have two ownership attributes of different kinds for the same
1456 if (I->getOwnKind() != K && I->args_end() !=
1457 std::find(I->args_begin(), I->args_end(), Idx)) {
1458 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1459 << AL.getName() << I;
1461 } else if (K == OwnershipAttr::Returns &&
1462 I->getOwnKind() == OwnershipAttr::Returns) {
1463 // A returns attribute conflicts with any other returns attribute using
1464 // a different index. Note, diagnostic reporting is 1-based, but stored
1465 // argument indexes are 0-based.
1466 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1467 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1468 << *(I->args_begin()) + 1;
1470 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1471 << (unsigned)Idx + 1 << Ex->getSourceRange();
1476 OwnershipArgs.push_back(Idx);
1479 unsigned* start = OwnershipArgs.data();
1480 unsigned size = OwnershipArgs.size();
1481 llvm::array_pod_sort(start, start + size);
1483 D->addAttr(::new (S.Context)
1484 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1485 AL.getAttributeSpellingListIndex()));
1488 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1489 // Check the attribute arguments.
1490 if (Attr.getNumArgs() > 1) {
1491 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1492 << Attr.getName() << 1;
1496 NamedDecl *nd = cast<NamedDecl>(D);
1500 // static int a __attribute__((weakref ("v2")));
1501 // static int b() __attribute__((weakref ("f3")));
1503 // and ignores the attributes of
1505 // static int a __attribute__((weakref ("v2")));
1508 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1509 if (!Ctx->isFileContext()) {
1510 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1515 // The GCC manual says
1517 // At present, a declaration to which `weakref' is attached can only
1522 // Without a TARGET,
1523 // given as an argument to `weakref' or to `alias', `weakref' is
1524 // equivalent to `weak'.
1526 // gcc 4.4.1 will accept
1527 // int a7 __attribute__((weakref));
1529 // int a7 __attribute__((weak));
1530 // This looks like a bug in gcc. We reject that for now. We should revisit
1531 // it if this behaviour is actually used.
1534 // static ((alias ("y"), weakref)).
1535 // Should we? How to check that weakref is before or after alias?
1537 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1538 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1539 // StringRef parameter it was given anyway.
1541 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1542 // GCC will accept anything as the argument of weakref. Should we
1543 // check for an existing decl?
1544 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1545 Attr.getAttributeSpellingListIndex()));
1547 D->addAttr(::new (S.Context)
1548 WeakRefAttr(Attr.getRange(), S.Context,
1549 Attr.getAttributeSpellingListIndex()));
1552 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1554 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1557 // Aliases should be on declarations, not definitions.
1558 const auto *FD = cast<FunctionDecl>(D);
1559 if (FD->isThisDeclarationADefinition()) {
1560 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1563 // FIXME: it should be handled as a target specific attribute.
1564 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1565 llvm::Triple::ELF) {
1566 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1570 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1571 Attr.getAttributeSpellingListIndex()));
1574 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1576 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1579 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1580 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1583 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1584 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1587 // Aliases should be on declarations, not definitions.
1588 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1589 if (FD->isThisDeclarationADefinition()) {
1590 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
1594 const auto *VD = cast<VarDecl>(D);
1595 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1596 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
1601 // FIXME: check if target symbol exists in current file
1603 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1604 Attr.getAttributeSpellingListIndex()));
1607 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1608 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1611 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1612 Attr.getAttributeSpellingListIndex()));
1615 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1616 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1619 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1620 Attr.getAttributeSpellingListIndex()));
1623 static void handleTLSModelAttr(Sema &S, Decl *D,
1624 const AttributeList &Attr) {
1626 SourceLocation LiteralLoc;
1627 // Check that it is a string.
1628 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1631 // Check that the value.
1632 if (Model != "global-dynamic" && Model != "local-dynamic"
1633 && Model != "initial-exec" && Model != "local-exec") {
1634 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1638 D->addAttr(::new (S.Context)
1639 TLSModelAttr(Attr.getRange(), S.Context, Model,
1640 Attr.getAttributeSpellingListIndex()));
1643 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1644 QualType ResultType = getFunctionOrMethodResultType(D);
1645 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1646 D->addAttr(::new (S.Context) RestrictAttr(
1647 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1651 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1652 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1655 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1656 if (S.LangOpts.CPlusPlus) {
1657 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1658 << Attr.getName() << AttributeLangSupport::Cpp;
1662 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1663 Attr.getAttributeSpellingListIndex()))
1667 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1668 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1672 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1673 Attr.getAttributeSpellingListIndex()));
1676 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1677 if (hasDeclarator(D)) return;
1679 if (S.CheckNoReturnAttr(attr)) return;
1681 if (!isa<ObjCMethodDecl>(D)) {
1682 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1683 << attr.getName() << ExpectedFunctionOrMethod;
1687 D->addAttr(::new (S.Context)
1688 NoReturnAttr(attr.getRange(), S.Context,
1689 attr.getAttributeSpellingListIndex()));
1692 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1693 if (!checkAttributeNumArgs(*this, attr, 0)) {
1701 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1702 const AttributeList &Attr) {
1704 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1705 // because 'analyzer_noreturn' does not impact the type.
1706 if (!isFunctionOrMethodOrBlock(D)) {
1707 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1708 if (!VD || (!VD->getType()->isBlockPointerType() &&
1709 !VD->getType()->isFunctionPointerType())) {
1710 S.Diag(Attr.getLoc(),
1711 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1712 : diag::warn_attribute_wrong_decl_type)
1713 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1718 D->addAttr(::new (S.Context)
1719 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1720 Attr.getAttributeSpellingListIndex()));
1723 // PS3 PPU-specific.
1724 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1726 Returning a Vector Class in Registers
1728 According to the PPU ABI specifications, a class with a single member of
1729 vector type is returned in memory when used as the return value of a function.
1730 This results in inefficient code when implementing vector classes. To return
1731 the value in a single vector register, add the vecreturn attribute to the
1732 class definition. This attribute is also applicable to struct types.
1738 __vector float xyzw;
1739 } __attribute__((vecreturn));
1741 Vector Add(Vector lhs, Vector rhs)
1744 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1745 return result; // This will be returned in a register
1748 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1749 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1753 RecordDecl *record = cast<RecordDecl>(D);
1756 if (!isa<CXXRecordDecl>(record)) {
1757 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1761 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1762 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1766 for (const auto *I : record->fields()) {
1767 if ((count == 1) || !I->getType()->isVectorType()) {
1768 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1774 D->addAttr(::new (S.Context)
1775 VecReturnAttr(Attr.getRange(), S.Context,
1776 Attr.getAttributeSpellingListIndex()));
1779 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1780 const AttributeList &Attr) {
1781 if (isa<ParmVarDecl>(D)) {
1782 // [[carries_dependency]] can only be applied to a parameter if it is a
1783 // parameter of a function declaration or lambda.
1784 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1785 S.Diag(Attr.getLoc(),
1786 diag::err_carries_dependency_param_not_function_decl);
1791 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1792 Attr.getRange(), S.Context,
1793 Attr.getAttributeSpellingListIndex()));
1796 static void handleNotTailCalledAttr(Sema &S, Decl *D,
1797 const AttributeList &Attr) {
1798 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1802 D->addAttr(::new (S.Context) NotTailCalledAttr(
1803 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1806 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1807 const AttributeList &Attr) {
1808 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1812 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1813 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1816 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1817 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1818 if (VD->hasLocalStorage()) {
1819 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1822 } else if (!isFunctionOrMethod(D)) {
1823 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1824 << Attr.getName() << ExpectedVariableOrFunction;
1828 D->addAttr(::new (S.Context)
1829 UsedAttr(Attr.getRange(), S.Context,
1830 Attr.getAttributeSpellingListIndex()));
1833 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1834 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
1836 if (IsCXX1zAttr && isa<VarDecl>(D)) {
1837 // The C++1z spelling of this attribute cannot be applied to a static data
1838 // member per [dcl.attr.unused]p2.
1839 if (cast<VarDecl>(D)->isStaticDataMember()) {
1840 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1841 << Attr.getName() << ExpectedForMaybeUnused;
1846 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
1847 // about using it as an extension.
1848 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
1849 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
1851 D->addAttr(::new (S.Context) UnusedAttr(
1852 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1855 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1856 uint32_t priority = ConstructorAttr::DefaultPriority;
1857 if (Attr.getNumArgs() &&
1858 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1861 D->addAttr(::new (S.Context)
1862 ConstructorAttr(Attr.getRange(), S.Context, priority,
1863 Attr.getAttributeSpellingListIndex()));
1866 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1867 uint32_t priority = DestructorAttr::DefaultPriority;
1868 if (Attr.getNumArgs() &&
1869 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
1872 D->addAttr(::new (S.Context)
1873 DestructorAttr(Attr.getRange(), S.Context, priority,
1874 Attr.getAttributeSpellingListIndex()));
1877 template <typename AttrTy>
1878 static void handleAttrWithMessage(Sema &S, Decl *D,
1879 const AttributeList &Attr) {
1880 // Handle the case where the attribute has a text message.
1882 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1885 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
1886 Attr.getAttributeSpellingListIndex()));
1889 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
1890 const AttributeList &Attr) {
1891 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
1892 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
1893 << Attr.getName() << Attr.getRange();
1897 D->addAttr(::new (S.Context)
1898 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
1899 Attr.getAttributeSpellingListIndex()));
1902 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
1903 IdentifierInfo *Platform,
1904 VersionTuple Introduced,
1905 VersionTuple Deprecated,
1906 VersionTuple Obsoleted) {
1907 StringRef PlatformName
1908 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1909 if (PlatformName.empty())
1910 PlatformName = Platform->getName();
1912 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
1913 // of these steps are needed).
1914 if (!Introduced.empty() && !Deprecated.empty() &&
1915 !(Introduced <= Deprecated)) {
1916 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1917 << 1 << PlatformName << Deprecated.getAsString()
1918 << 0 << Introduced.getAsString();
1922 if (!Introduced.empty() && !Obsoleted.empty() &&
1923 !(Introduced <= Obsoleted)) {
1924 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1925 << 2 << PlatformName << Obsoleted.getAsString()
1926 << 0 << Introduced.getAsString();
1930 if (!Deprecated.empty() && !Obsoleted.empty() &&
1931 !(Deprecated <= Obsoleted)) {
1932 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
1933 << 2 << PlatformName << Obsoleted.getAsString()
1934 << 1 << Deprecated.getAsString();
1941 /// \brief Check whether the two versions match.
1943 /// If either version tuple is empty, then they are assumed to match. If
1944 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
1945 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
1946 bool BeforeIsOkay) {
1947 if (X.empty() || Y.empty())
1953 if (BeforeIsOkay && X < Y)
1959 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
1960 IdentifierInfo *Platform,
1962 VersionTuple Introduced,
1963 VersionTuple Deprecated,
1964 VersionTuple Obsoleted,
1968 StringRef Replacement,
1969 AvailabilityMergeKind AMK,
1970 unsigned AttrSpellingListIndex) {
1971 VersionTuple MergedIntroduced = Introduced;
1972 VersionTuple MergedDeprecated = Deprecated;
1973 VersionTuple MergedObsoleted = Obsoleted;
1974 bool FoundAny = false;
1975 bool OverrideOrImpl = false;
1978 case AMK_Redeclaration:
1979 OverrideOrImpl = false;
1983 case AMK_ProtocolImplementation:
1984 OverrideOrImpl = true;
1988 if (D->hasAttrs()) {
1989 AttrVec &Attrs = D->getAttrs();
1990 for (unsigned i = 0, e = Attrs.size(); i != e;) {
1991 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
1997 IdentifierInfo *OldPlatform = OldAA->getPlatform();
1998 if (OldPlatform != Platform) {
2003 // If there is an existing availability attribute for this platform that
2004 // is explicit and the new one is implicit use the explicit one and
2005 // discard the new implicit attribute.
2006 if (!OldAA->isImplicit() && Implicit) {
2010 // If there is an existing attribute for this platform that is implicit
2011 // and the new attribute is explicit then erase the old one and
2012 // continue processing the attributes.
2013 if (!Implicit && OldAA->isImplicit()) {
2014 Attrs.erase(Attrs.begin() + i);
2020 VersionTuple OldIntroduced = OldAA->getIntroduced();
2021 VersionTuple OldDeprecated = OldAA->getDeprecated();
2022 VersionTuple OldObsoleted = OldAA->getObsoleted();
2023 bool OldIsUnavailable = OldAA->getUnavailable();
2025 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2026 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2027 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2028 !(OldIsUnavailable == IsUnavailable ||
2029 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2030 if (OverrideOrImpl) {
2032 VersionTuple FirstVersion;
2033 VersionTuple SecondVersion;
2034 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2036 FirstVersion = OldIntroduced;
2037 SecondVersion = Introduced;
2038 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2040 FirstVersion = Deprecated;
2041 SecondVersion = OldDeprecated;
2042 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2044 FirstVersion = Obsoleted;
2045 SecondVersion = OldObsoleted;
2049 Diag(OldAA->getLocation(),
2050 diag::warn_mismatched_availability_override_unavail)
2051 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2052 << (AMK == AMK_Override);
2054 Diag(OldAA->getLocation(),
2055 diag::warn_mismatched_availability_override)
2057 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2058 << FirstVersion.getAsString() << SecondVersion.getAsString()
2059 << (AMK == AMK_Override);
2061 if (AMK == AMK_Override)
2062 Diag(Range.getBegin(), diag::note_overridden_method);
2064 Diag(Range.getBegin(), diag::note_protocol_method);
2066 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2067 Diag(Range.getBegin(), diag::note_previous_attribute);
2070 Attrs.erase(Attrs.begin() + i);
2075 VersionTuple MergedIntroduced2 = MergedIntroduced;
2076 VersionTuple MergedDeprecated2 = MergedDeprecated;
2077 VersionTuple MergedObsoleted2 = MergedObsoleted;
2079 if (MergedIntroduced2.empty())
2080 MergedIntroduced2 = OldIntroduced;
2081 if (MergedDeprecated2.empty())
2082 MergedDeprecated2 = OldDeprecated;
2083 if (MergedObsoleted2.empty())
2084 MergedObsoleted2 = OldObsoleted;
2086 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2087 MergedIntroduced2, MergedDeprecated2,
2088 MergedObsoleted2)) {
2089 Attrs.erase(Attrs.begin() + i);
2094 MergedIntroduced = MergedIntroduced2;
2095 MergedDeprecated = MergedDeprecated2;
2096 MergedObsoleted = MergedObsoleted2;
2102 MergedIntroduced == Introduced &&
2103 MergedDeprecated == Deprecated &&
2104 MergedObsoleted == Obsoleted)
2107 // Only create a new attribute if !OverrideOrImpl, but we want to do
2109 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2110 MergedDeprecated, MergedObsoleted) &&
2112 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2113 Introduced, Deprecated,
2114 Obsoleted, IsUnavailable, Message,
2115 IsStrict, Replacement,
2116 AttrSpellingListIndex);
2117 Avail->setImplicit(Implicit);
2123 static void handleAvailabilityAttr(Sema &S, Decl *D,
2124 const AttributeList &Attr) {
2125 if (!checkAttributeNumArgs(S, Attr, 1))
2127 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2128 unsigned Index = Attr.getAttributeSpellingListIndex();
2130 IdentifierInfo *II = Platform->Ident;
2131 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2132 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2135 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2137 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2141 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2142 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2143 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2144 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2145 bool IsStrict = Attr.getStrictLoc().isValid();
2147 if (const StringLiteral *SE =
2148 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2149 Str = SE->getString();
2150 StringRef Replacement;
2151 if (const StringLiteral *SE =
2152 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2153 Replacement = SE->getString();
2155 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2161 IsStrict, Replacement,
2165 D->addAttr(NewAttr);
2167 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2168 // matches before the start of the watchOS platform.
2169 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2170 IdentifierInfo *NewII = nullptr;
2171 if (II->getName() == "ios")
2172 NewII = &S.Context.Idents.get("watchos");
2173 else if (II->getName() == "ios_app_extension")
2174 NewII = &S.Context.Idents.get("watchos_app_extension");
2177 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2178 if (Version.empty())
2180 auto Major = Version.getMajor();
2181 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2182 if (NewMajor >= 2) {
2183 if (Version.getMinor().hasValue()) {
2184 if (Version.getSubminor().hasValue())
2185 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2186 Version.getSubminor().getValue());
2188 return VersionTuple(NewMajor, Version.getMinor().getValue());
2192 return VersionTuple(2, 0);
2195 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2196 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2197 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2199 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2212 D->addAttr(NewAttr);
2214 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2215 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2216 // matches before the start of the tvOS platform.
2217 IdentifierInfo *NewII = nullptr;
2218 if (II->getName() == "ios")
2219 NewII = &S.Context.Idents.get("tvos");
2220 else if (II->getName() == "ios_app_extension")
2221 NewII = &S.Context.Idents.get("tvos_app_extension");
2224 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2237 D->addAttr(NewAttr);
2243 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2244 typename T::VisibilityType value,
2245 unsigned attrSpellingListIndex) {
2246 T *existingAttr = D->getAttr<T>();
2248 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2249 if (existingValue == value)
2251 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2252 S.Diag(range.getBegin(), diag::note_previous_attribute);
2255 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2258 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2259 VisibilityAttr::VisibilityType Vis,
2260 unsigned AttrSpellingListIndex) {
2261 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2262 AttrSpellingListIndex);
2265 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2266 TypeVisibilityAttr::VisibilityType Vis,
2267 unsigned AttrSpellingListIndex) {
2268 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2269 AttrSpellingListIndex);
2272 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2273 bool isTypeVisibility) {
2274 // Visibility attributes don't mean anything on a typedef.
2275 if (isa<TypedefNameDecl>(D)) {
2276 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2281 // 'type_visibility' can only go on a type or namespace.
2282 if (isTypeVisibility &&
2283 !(isa<TagDecl>(D) ||
2284 isa<ObjCInterfaceDecl>(D) ||
2285 isa<NamespaceDecl>(D))) {
2286 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2287 << Attr.getName() << ExpectedTypeOrNamespace;
2291 // Check that the argument is a string literal.
2293 SourceLocation LiteralLoc;
2294 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2297 VisibilityAttr::VisibilityType type;
2298 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2299 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2300 << Attr.getName() << TypeStr;
2304 // Complain about attempts to use protected visibility on targets
2305 // (like Darwin) that don't support it.
2306 if (type == VisibilityAttr::Protected &&
2307 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2308 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2309 type = VisibilityAttr::Default;
2312 unsigned Index = Attr.getAttributeSpellingListIndex();
2313 clang::Attr *newAttr;
2314 if (isTypeVisibility) {
2315 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2316 (TypeVisibilityAttr::VisibilityType) type,
2319 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2322 D->addAttr(newAttr);
2325 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2326 const AttributeList &Attr) {
2327 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2328 if (!Attr.isArgIdent(0)) {
2329 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2330 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2334 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2335 ObjCMethodFamilyAttr::FamilyKind F;
2336 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2337 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2342 if (F == ObjCMethodFamilyAttr::OMF_init &&
2343 !method->getReturnType()->isObjCObjectPointerType()) {
2344 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2345 << method->getReturnType();
2346 // Ignore the attribute.
2350 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2352 Attr.getAttributeSpellingListIndex()));
2355 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2356 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2357 QualType T = TD->getUnderlyingType();
2358 if (!T->isCARCBridgableType()) {
2359 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2363 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2364 QualType T = PD->getType();
2365 if (!T->isCARCBridgableType()) {
2366 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2371 // It is okay to include this attribute on properties, e.g.:
2373 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2375 // In this case it follows tradition and suppresses an error in the above
2377 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2379 D->addAttr(::new (S.Context)
2380 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2381 Attr.getAttributeSpellingListIndex()));
2384 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2385 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2386 QualType T = TD->getUnderlyingType();
2387 if (!T->isObjCObjectPointerType()) {
2388 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2392 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2395 D->addAttr(::new (S.Context)
2396 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2397 Attr.getAttributeSpellingListIndex()));
2400 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2401 if (!Attr.isArgIdent(0)) {
2402 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2403 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2407 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2408 BlocksAttr::BlockType type;
2409 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2410 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2411 << Attr.getName() << II;
2415 D->addAttr(::new (S.Context)
2416 BlocksAttr(Attr.getRange(), S.Context, type,
2417 Attr.getAttributeSpellingListIndex()));
2420 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2421 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2422 if (Attr.getNumArgs() > 0) {
2423 Expr *E = Attr.getArgAsExpr(0);
2424 llvm::APSInt Idx(32);
2425 if (E->isTypeDependent() || E->isValueDependent() ||
2426 !E->isIntegerConstantExpr(Idx, S.Context)) {
2427 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2428 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2429 << E->getSourceRange();
2433 if (Idx.isSigned() && Idx.isNegative()) {
2434 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2435 << E->getSourceRange();
2439 sentinel = Idx.getZExtValue();
2442 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2443 if (Attr.getNumArgs() > 1) {
2444 Expr *E = Attr.getArgAsExpr(1);
2445 llvm::APSInt Idx(32);
2446 if (E->isTypeDependent() || E->isValueDependent() ||
2447 !E->isIntegerConstantExpr(Idx, S.Context)) {
2448 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2449 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2450 << E->getSourceRange();
2453 nullPos = Idx.getZExtValue();
2455 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2456 // FIXME: This error message could be improved, it would be nice
2457 // to say what the bounds actually are.
2458 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2459 << E->getSourceRange();
2464 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2465 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2466 if (isa<FunctionNoProtoType>(FT)) {
2467 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2471 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2472 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2475 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2476 if (!MD->isVariadic()) {
2477 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2480 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2481 if (!BD->isVariadic()) {
2482 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2485 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2486 QualType Ty = V->getType();
2487 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2488 const FunctionType *FT = Ty->isFunctionPointerType()
2489 ? D->getFunctionType()
2490 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2491 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2492 int m = Ty->isFunctionPointerType() ? 0 : 1;
2493 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2497 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2498 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2502 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2503 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2506 D->addAttr(::new (S.Context)
2507 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2508 Attr.getAttributeSpellingListIndex()));
2511 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2512 if (D->getFunctionType() &&
2513 D->getFunctionType()->getReturnType()->isVoidType()) {
2514 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2515 << Attr.getName() << 0;
2518 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2519 if (MD->getReturnType()->isVoidType()) {
2520 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2521 << Attr.getName() << 1;
2525 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2526 // about using it as an extension.
2527 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2528 !Attr.getScopeName())
2529 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2531 D->addAttr(::new (S.Context)
2532 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2533 Attr.getAttributeSpellingListIndex()));
2536 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2537 // weak_import only applies to variable & function declarations.
2539 if (!D->canBeWeakImported(isDef)) {
2541 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2543 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2544 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2545 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2546 // Nothing to warn about here.
2548 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2549 << Attr.getName() << ExpectedVariableOrFunction;
2554 D->addAttr(::new (S.Context)
2555 WeakImportAttr(Attr.getRange(), S.Context,
2556 Attr.getAttributeSpellingListIndex()));
2559 // Handles reqd_work_group_size and work_group_size_hint.
2560 template <typename WorkGroupAttr>
2561 static void handleWorkGroupSize(Sema &S, Decl *D,
2562 const AttributeList &Attr) {
2564 for (unsigned i = 0; i < 3; ++i) {
2565 const Expr *E = Attr.getArgAsExpr(i);
2566 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2568 if (WGSize[i] == 0) {
2569 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2570 << Attr.getName() << E->getSourceRange();
2575 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2576 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2577 Existing->getYDim() == WGSize[1] &&
2578 Existing->getZDim() == WGSize[2]))
2579 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2581 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2582 WGSize[0], WGSize[1], WGSize[2],
2583 Attr.getAttributeSpellingListIndex()));
2586 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2587 if (!Attr.hasParsedType()) {
2588 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2589 << Attr.getName() << 1;
2593 TypeSourceInfo *ParmTSI = nullptr;
2594 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2595 assert(ParmTSI && "no type source info for attribute argument");
2597 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2598 (ParmType->isBooleanType() ||
2599 !ParmType->isIntegralType(S.getASTContext()))) {
2600 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2605 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2606 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2607 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2612 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2614 Attr.getAttributeSpellingListIndex()));
2617 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2619 unsigned AttrSpellingListIndex) {
2620 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2621 if (ExistingAttr->getName() == Name)
2623 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2624 Diag(Range.getBegin(), diag::note_previous_attribute);
2627 return ::new (Context) SectionAttr(Range, Context, Name,
2628 AttrSpellingListIndex);
2631 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2632 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2633 if (!Error.empty()) {
2634 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2640 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2641 // Make sure that there is a string literal as the sections's single
2644 SourceLocation LiteralLoc;
2645 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2648 if (!S.checkSectionName(LiteralLoc, Str))
2651 // If the target wants to validate the section specifier, make it happen.
2652 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2653 if (!Error.empty()) {
2654 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2659 unsigned Index = Attr.getAttributeSpellingListIndex();
2660 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2662 D->addAttr(NewAttr);
2665 // Check for things we'd like to warn about, no errors or validation for now.
2666 // TODO: Validation should use a backend target library that specifies
2667 // the allowable subtarget features and cpus. We could use something like a
2668 // TargetCodeGenInfo hook here to do validation.
2669 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2670 for (auto Str : {"tune=", "fpmath="})
2671 if (AttrStr.find(Str) != StringRef::npos)
2672 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2675 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2677 SourceLocation LiteralLoc;
2678 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2680 S.checkTargetAttr(LiteralLoc, Str);
2681 unsigned Index = Attr.getAttributeSpellingListIndex();
2682 TargetAttr *NewAttr =
2683 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2684 D->addAttr(NewAttr);
2687 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2688 VarDecl *VD = cast<VarDecl>(D);
2689 if (!VD->hasLocalStorage()) {
2690 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2694 Expr *E = Attr.getArgAsExpr(0);
2695 SourceLocation Loc = E->getExprLoc();
2696 FunctionDecl *FD = nullptr;
2697 DeclarationNameInfo NI;
2699 // gcc only allows for simple identifiers. Since we support more than gcc, we
2700 // will warn the user.
2701 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2702 if (DRE->hasQualifier())
2703 S.Diag(Loc, diag::warn_cleanup_ext);
2704 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2705 NI = DRE->getNameInfo();
2707 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2711 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2712 if (ULE->hasExplicitTemplateArgs())
2713 S.Diag(Loc, diag::warn_cleanup_ext);
2714 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2715 NI = ULE->getNameInfo();
2717 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2719 if (ULE->getType() == S.Context.OverloadTy)
2720 S.NoteAllOverloadCandidates(ULE);
2724 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2728 if (FD->getNumParams() != 1) {
2729 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2734 // We're currently more strict than GCC about what function types we accept.
2735 // If this ever proves to be a problem it should be easy to fix.
2736 QualType Ty = S.Context.getPointerType(VD->getType());
2737 QualType ParamTy = FD->getParamDecl(0)->getType();
2738 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2739 ParamTy, Ty) != Sema::Compatible) {
2740 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2741 << NI.getName() << ParamTy << Ty;
2745 D->addAttr(::new (S.Context)
2746 CleanupAttr(Attr.getRange(), S.Context, FD,
2747 Attr.getAttributeSpellingListIndex()));
2750 /// Handle __attribute__((format_arg((idx)))) attribute based on
2751 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2752 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2753 Expr *IdxExpr = Attr.getArgAsExpr(0);
2755 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2758 // Make sure the format string is really a string.
2759 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2761 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2762 if (NotNSStringTy &&
2763 !isCFStringType(Ty, S.Context) &&
2764 (!Ty->isPointerType() ||
2765 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2766 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2767 << "a string type" << IdxExpr->getSourceRange()
2768 << getFunctionOrMethodParamRange(D, 0);
2771 Ty = getFunctionOrMethodResultType(D);
2772 if (!isNSStringType(Ty, S.Context) &&
2773 !isCFStringType(Ty, S.Context) &&
2774 (!Ty->isPointerType() ||
2775 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2776 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2777 << (NotNSStringTy ? "string type" : "NSString")
2778 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2782 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2783 // because that has corrected for the implicit this parameter, and is zero-
2784 // based. The attribute expects what the user wrote explicitly.
2786 IdxExpr->EvaluateAsInt(Val, S.Context);
2788 D->addAttr(::new (S.Context)
2789 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2790 Attr.getAttributeSpellingListIndex()));
2793 enum FormatAttrKind {
2802 /// getFormatAttrKind - Map from format attribute names to supported format
2804 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2805 return llvm::StringSwitch<FormatAttrKind>(Format)
2806 // Check for formats that get handled specially.
2807 .Case("NSString", NSStringFormat)
2808 .Case("CFString", CFStringFormat)
2809 .Case("strftime", StrftimeFormat)
2811 // Otherwise, check for supported formats.
2812 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2813 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2814 .Case("kprintf", SupportedFormat) // OpenBSD.
2815 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2816 .Case("os_trace", SupportedFormat)
2818 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2819 .Default(InvalidFormat);
2822 /// Handle __attribute__((init_priority(priority))) attributes based on
2823 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2824 static void handleInitPriorityAttr(Sema &S, Decl *D,
2825 const AttributeList &Attr) {
2826 if (!S.getLangOpts().CPlusPlus) {
2827 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2831 if (S.getCurFunctionOrMethodDecl()) {
2832 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2836 QualType T = cast<VarDecl>(D)->getType();
2837 if (S.Context.getAsArrayType(T))
2838 T = S.Context.getBaseElementType(T);
2839 if (!T->getAs<RecordType>()) {
2840 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2845 Expr *E = Attr.getArgAsExpr(0);
2846 uint32_t prioritynum;
2847 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
2852 if (prioritynum < 101 || prioritynum > 65535) {
2853 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2854 << E->getSourceRange() << Attr.getName() << 101 << 65535;
2858 D->addAttr(::new (S.Context)
2859 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2860 Attr.getAttributeSpellingListIndex()));
2863 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2864 IdentifierInfo *Format, int FormatIdx,
2866 unsigned AttrSpellingListIndex) {
2867 // Check whether we already have an equivalent format attribute.
2868 for (auto *F : D->specific_attrs<FormatAttr>()) {
2869 if (F->getType() == Format &&
2870 F->getFormatIdx() == FormatIdx &&
2871 F->getFirstArg() == FirstArg) {
2872 // If we don't have a valid location for this attribute, adopt the
2874 if (F->getLocation().isInvalid())
2880 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
2881 FirstArg, AttrSpellingListIndex);
2884 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
2885 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2886 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2887 if (!Attr.isArgIdent(0)) {
2888 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2889 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2893 // In C++ the implicit 'this' function parameter also counts, and they are
2894 // counted from one.
2895 bool HasImplicitThisParam = isInstanceMethod(D);
2896 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
2898 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2899 StringRef Format = II->getName();
2901 if (normalizeName(Format)) {
2902 // If we've modified the string name, we need a new identifier for it.
2903 II = &S.Context.Idents.get(Format);
2906 // Check for supported formats.
2907 FormatAttrKind Kind = getFormatAttrKind(Format);
2909 if (Kind == IgnoredFormat)
2912 if (Kind == InvalidFormat) {
2913 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2914 << Attr.getName() << II->getName();
2918 // checks for the 2nd argument
2919 Expr *IdxExpr = Attr.getArgAsExpr(1);
2921 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
2924 if (Idx < 1 || Idx > NumArgs) {
2925 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2926 << Attr.getName() << 2 << IdxExpr->getSourceRange();
2930 // FIXME: Do we need to bounds check?
2931 unsigned ArgIdx = Idx - 1;
2933 if (HasImplicitThisParam) {
2935 S.Diag(Attr.getLoc(),
2936 diag::err_format_attribute_implicit_this_format_string)
2937 << IdxExpr->getSourceRange();
2943 // make sure the format string is really a string
2944 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
2946 if (Kind == CFStringFormat) {
2947 if (!isCFStringType(Ty, S.Context)) {
2948 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2949 << "a CFString" << IdxExpr->getSourceRange()
2950 << getFunctionOrMethodParamRange(D, ArgIdx);
2953 } else if (Kind == NSStringFormat) {
2954 // FIXME: do we need to check if the type is NSString*? What are the
2956 if (!isNSStringType(Ty, S.Context)) {
2957 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2958 << "an NSString" << IdxExpr->getSourceRange()
2959 << getFunctionOrMethodParamRange(D, ArgIdx);
2962 } else if (!Ty->isPointerType() ||
2963 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
2964 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2965 << "a string type" << IdxExpr->getSourceRange()
2966 << getFunctionOrMethodParamRange(D, ArgIdx);
2970 // check the 3rd argument
2971 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
2973 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
2976 // check if the function is variadic if the 3rd argument non-zero
2977 if (FirstArg != 0) {
2978 if (isFunctionOrMethodVariadic(D)) {
2979 ++NumArgs; // +1 for ...
2981 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
2986 // strftime requires FirstArg to be 0 because it doesn't read from any
2987 // variable the input is just the current time + the format string.
2988 if (Kind == StrftimeFormat) {
2989 if (FirstArg != 0) {
2990 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
2991 << FirstArgExpr->getSourceRange();
2994 // if 0 it disables parameter checking (to use with e.g. va_list)
2995 } else if (FirstArg != 0 && FirstArg != NumArgs) {
2996 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
2997 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3001 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3003 Attr.getAttributeSpellingListIndex());
3005 D->addAttr(NewAttr);
3008 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3009 const AttributeList &Attr) {
3010 // Try to find the underlying union declaration.
3011 RecordDecl *RD = nullptr;
3012 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3013 if (TD && TD->getUnderlyingType()->isUnionType())
3014 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3016 RD = dyn_cast<RecordDecl>(D);
3018 if (!RD || !RD->isUnion()) {
3019 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3020 << Attr.getName() << ExpectedUnion;
3024 if (!RD->isCompleteDefinition()) {
3025 S.Diag(Attr.getLoc(),
3026 diag::warn_transparent_union_attribute_not_definition);
3030 RecordDecl::field_iterator Field = RD->field_begin(),
3031 FieldEnd = RD->field_end();
3032 if (Field == FieldEnd) {
3033 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3037 FieldDecl *FirstField = *Field;
3038 QualType FirstType = FirstField->getType();
3039 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3040 S.Diag(FirstField->getLocation(),
3041 diag::warn_transparent_union_attribute_floating)
3042 << FirstType->isVectorType() << FirstType;
3046 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3047 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3048 for (; Field != FieldEnd; ++Field) {
3049 QualType FieldType = Field->getType();
3050 // FIXME: this isn't fully correct; we also need to test whether the
3051 // members of the union would all have the same calling convention as the
3052 // first member of the union. Checking just the size and alignment isn't
3053 // sufficient (consider structs passed on the stack instead of in registers
3055 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3056 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3057 // Warn if we drop the attribute.
3058 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3059 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3060 : S.Context.getTypeAlign(FieldType);
3061 S.Diag(Field->getLocation(),
3062 diag::warn_transparent_union_attribute_field_size_align)
3063 << isSize << Field->getDeclName() << FieldBits;
3064 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3065 S.Diag(FirstField->getLocation(),
3066 diag::note_transparent_union_first_field_size_align)
3067 << isSize << FirstBits;
3072 RD->addAttr(::new (S.Context)
3073 TransparentUnionAttr(Attr.getRange(), S.Context,
3074 Attr.getAttributeSpellingListIndex()));
3077 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3078 // Make sure that there is a string literal as the annotation's single
3081 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3084 // Don't duplicate annotations that are already set.
3085 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3086 if (I->getAnnotation() == Str)
3090 D->addAttr(::new (S.Context)
3091 AnnotateAttr(Attr.getRange(), S.Context, Str,
3092 Attr.getAttributeSpellingListIndex()));
3095 static void handleAlignValueAttr(Sema &S, Decl *D,
3096 const AttributeList &Attr) {
3097 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3098 Attr.getAttributeSpellingListIndex());
3101 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3102 unsigned SpellingListIndex) {
3103 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3104 SourceLocation AttrLoc = AttrRange.getBegin();
3107 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3108 T = TD->getUnderlyingType();
3109 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3112 llvm_unreachable("Unknown decl type for align_value");
3114 if (!T->isDependentType() && !T->isAnyPointerType() &&
3115 !T->isReferenceType() && !T->isMemberPointerType()) {
3116 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3117 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3121 if (!E->isValueDependent()) {
3122 llvm::APSInt Alignment;
3124 = VerifyIntegerConstantExpression(E, &Alignment,
3125 diag::err_align_value_attribute_argument_not_int,
3126 /*AllowFold*/ false);
3127 if (ICE.isInvalid())
3130 if (!Alignment.isPowerOf2()) {
3131 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3132 << E->getSourceRange();
3136 D->addAttr(::new (Context)
3137 AlignValueAttr(AttrRange, Context, ICE.get(),
3138 SpellingListIndex));
3142 // Save dependent expressions in the AST to be instantiated.
3143 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3146 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3147 // check the attribute arguments.
3148 if (Attr.getNumArgs() > 1) {
3149 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3150 << Attr.getName() << 1;
3154 if (Attr.getNumArgs() == 0) {
3155 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3156 true, nullptr, Attr.getAttributeSpellingListIndex()));
3160 Expr *E = Attr.getArgAsExpr(0);
3161 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3162 S.Diag(Attr.getEllipsisLoc(),
3163 diag::err_pack_expansion_without_parameter_packs);
3167 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3170 if (E->isValueDependent()) {
3171 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3172 if (!TND->getUnderlyingType()->isDependentType()) {
3173 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3174 << E->getSourceRange();
3180 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3181 Attr.isPackExpansion());
3184 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3185 unsigned SpellingListIndex, bool IsPackExpansion) {
3186 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3187 SourceLocation AttrLoc = AttrRange.getBegin();
3189 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3190 if (TmpAttr.isAlignas()) {
3191 // C++11 [dcl.align]p1:
3192 // An alignment-specifier may be applied to a variable or to a class
3193 // data member, but it shall not be applied to a bit-field, a function
3194 // parameter, the formal parameter of a catch clause, or a variable
3195 // declared with the register storage class specifier. An
3196 // alignment-specifier may also be applied to the declaration of a class
3197 // or enumeration type.
3199 // An alignment attribute shall not be specified in a declaration of
3200 // a typedef, or a bit-field, or a function, or a parameter, or an
3201 // object declared with the register storage-class specifier.
3203 if (isa<ParmVarDecl>(D)) {
3205 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3206 if (VD->getStorageClass() == SC_Register)
3208 if (VD->isExceptionVariable())
3210 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3211 if (FD->isBitField())
3213 } else if (!isa<TagDecl>(D)) {
3214 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3215 << (TmpAttr.isC11() ? ExpectedVariableOrField
3216 : ExpectedVariableFieldOrTag);
3219 if (DiagKind != -1) {
3220 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3221 << &TmpAttr << DiagKind;
3226 if (E->isTypeDependent() || E->isValueDependent()) {
3227 // Save dependent expressions in the AST to be instantiated.
3228 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3229 AA->setPackExpansion(IsPackExpansion);
3234 // FIXME: Cache the number on the Attr object?
3235 llvm::APSInt Alignment;
3237 = VerifyIntegerConstantExpression(E, &Alignment,
3238 diag::err_aligned_attribute_argument_not_int,
3239 /*AllowFold*/ false);
3240 if (ICE.isInvalid())
3243 uint64_t AlignVal = Alignment.getZExtValue();
3245 // C++11 [dcl.align]p2:
3246 // -- if the constant expression evaluates to zero, the alignment
3247 // specifier shall have no effect
3249 // An alignment specification of zero has no effect.
3250 if (!(TmpAttr.isAlignas() && !Alignment)) {
3251 if (!llvm::isPowerOf2_64(AlignVal)) {
3252 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3253 << E->getSourceRange();
3258 // Alignment calculations can wrap around if it's greater than 2**28.
3259 unsigned MaxValidAlignment =
3260 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3262 if (AlignVal > MaxValidAlignment) {
3263 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3264 << E->getSourceRange();
3268 if (Context.getTargetInfo().isTLSSupported()) {
3269 unsigned MaxTLSAlign =
3270 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3272 auto *VD = dyn_cast<VarDecl>(D);
3273 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3274 VD->getTLSKind() != VarDecl::TLS_None) {
3275 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3276 << (unsigned)AlignVal << VD << MaxTLSAlign;
3281 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3282 ICE.get(), SpellingListIndex);
3283 AA->setPackExpansion(IsPackExpansion);
3287 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3288 unsigned SpellingListIndex, bool IsPackExpansion) {
3289 // FIXME: Cache the number on the Attr object if non-dependent?
3290 // FIXME: Perform checking of type validity
3291 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3293 AA->setPackExpansion(IsPackExpansion);
3297 void Sema::CheckAlignasUnderalignment(Decl *D) {
3298 assert(D->hasAttrs() && "no attributes on decl");
3300 QualType UnderlyingTy, DiagTy;
3301 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3302 UnderlyingTy = DiagTy = VD->getType();
3304 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3305 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3306 UnderlyingTy = ED->getIntegerType();
3308 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3311 // C++11 [dcl.align]p5, C11 6.7.5/4:
3312 // The combined effect of all alignment attributes in a declaration shall
3313 // not specify an alignment that is less strict than the alignment that
3314 // would otherwise be required for the entity being declared.
3315 AlignedAttr *AlignasAttr = nullptr;
3317 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3318 if (I->isAlignmentDependent())
3322 Align = std::max(Align, I->getAlignment(Context));
3325 if (AlignasAttr && Align) {
3326 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3327 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3328 if (NaturalAlign > RequestedAlign)
3329 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3330 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3334 bool Sema::checkMSInheritanceAttrOnDefinition(
3335 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3336 MSInheritanceAttr::Spelling SemanticSpelling) {
3337 assert(RD->hasDefinition() && "RD has no definition!");
3339 // We may not have seen base specifiers or any virtual methods yet. We will
3340 // have to wait until the record is defined to catch any mismatches.
3341 if (!RD->getDefinition()->isCompleteDefinition())
3344 // The unspecified model never matches what a definition could need.
3345 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3349 if (RD->calculateInheritanceModel() == SemanticSpelling)
3352 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3356 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3357 << 0 /*definition*/;
3358 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3359 << RD->getNameAsString();
3363 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3365 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3366 bool &IntegerMode, bool &ComplexMode) {
3368 ComplexMode = false;
3369 switch (Str.size()) {
3391 if (Str[1] == 'F') {
3392 IntegerMode = false;
3393 } else if (Str[1] == 'C') {
3394 IntegerMode = false;
3396 } else if (Str[1] != 'I') {
3401 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3402 // pointer on PIC16 and other embedded platforms.
3404 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3405 else if (Str == "byte")
3406 DestWidth = S.Context.getTargetInfo().getCharWidth();
3409 if (Str == "pointer")
3410 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3413 if (Str == "unwind_word")
3414 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3419 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3422 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3423 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3424 /// HImode, not an intermediate pointer.
3425 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3426 // This attribute isn't documented, but glibc uses it. It changes
3427 // the width of an int or unsigned int to the specified size.
3428 if (!Attr.isArgIdent(0)) {
3429 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3430 << AANT_ArgumentIdentifier;
3434 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3436 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3439 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3440 unsigned SpellingListIndex, bool InInstantiation) {
3441 StringRef Str = Name->getName();
3443 SourceLocation AttrLoc = AttrRange.getBegin();
3445 unsigned DestWidth = 0;
3446 bool IntegerMode = true;
3447 bool ComplexMode = false;
3448 llvm::APInt VectorSize(64, 0);
3449 if (Str.size() >= 4 && Str[0] == 'V') {
3450 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3451 size_t StrSize = Str.size();
3452 size_t VectorStringLength = 0;
3453 while ((VectorStringLength + 1) < StrSize &&
3454 isdigit(Str[VectorStringLength + 1]))
3455 ++VectorStringLength;
3456 if (VectorStringLength &&
3457 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3458 VectorSize.isPowerOf2()) {
3459 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3460 IntegerMode, ComplexMode);
3461 // Avoid duplicate warning from template instantiation.
3462 if (!InInstantiation)
3463 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3470 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3472 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3473 // and friends, at least with glibc.
3474 // FIXME: Make sure floating-point mappings are accurate
3475 // FIXME: Support XF and TF types
3477 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3482 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3483 OldTy = TD->getUnderlyingType();
3484 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3485 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3486 // Try to get type from enum declaration, default to int.
3487 OldTy = ED->getIntegerType();
3489 OldTy = Context.IntTy;
3491 OldTy = cast<ValueDecl>(D)->getType();
3493 if (OldTy->isDependentType()) {
3494 D->addAttr(::new (Context)
3495 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3499 // Base type can also be a vector type (see PR17453).
3500 // Distinguish between base type and base element type.
3501 QualType OldElemTy = OldTy;
3502 if (const VectorType *VT = OldTy->getAs<VectorType>())
3503 OldElemTy = VT->getElementType();
3505 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3506 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3507 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3508 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3509 VectorSize.getBoolValue()) {
3510 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3513 bool IntegralOrAnyEnumType =
3514 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3516 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3517 !IntegralOrAnyEnumType)
3518 Diag(AttrLoc, diag::err_mode_not_primitive);
3519 else if (IntegerMode) {
3520 if (!IntegralOrAnyEnumType)
3521 Diag(AttrLoc, diag::err_mode_wrong_type);
3522 } else if (ComplexMode) {
3523 if (!OldElemTy->isComplexType())
3524 Diag(AttrLoc, diag::err_mode_wrong_type);
3526 if (!OldElemTy->isFloatingType())
3527 Diag(AttrLoc, diag::err_mode_wrong_type);
3533 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3534 OldElemTy->isSignedIntegerType());
3536 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3538 if (NewElemTy.isNull()) {
3539 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3544 NewElemTy = Context.getComplexType(NewElemTy);
3547 QualType NewTy = NewElemTy;
3548 if (VectorSize.getBoolValue()) {
3549 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3550 VectorType::GenericVector);
3551 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3552 // Complex machine mode does not support base vector types.
3554 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3557 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3558 OldVT->getNumElements() /
3559 Context.getTypeSize(NewElemTy);
3561 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3564 if (NewTy.isNull()) {
3565 Diag(AttrLoc, diag::err_mode_wrong_type);
3569 // Install the new type.
3570 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3571 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3572 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3573 ED->setIntegerType(NewTy);
3575 cast<ValueDecl>(D)->setType(NewTy);
3577 D->addAttr(::new (Context)
3578 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3581 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3582 D->addAttr(::new (S.Context)
3583 NoDebugAttr(Attr.getRange(), S.Context,
3584 Attr.getAttributeSpellingListIndex()));
3587 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3588 IdentifierInfo *Ident,
3589 unsigned AttrSpellingListIndex) {
3590 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3591 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3592 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3596 if (D->hasAttr<AlwaysInlineAttr>())
3599 return ::new (Context) AlwaysInlineAttr(Range, Context,
3600 AttrSpellingListIndex);
3603 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3604 IdentifierInfo *Ident,
3605 unsigned AttrSpellingListIndex) {
3606 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3609 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3612 InternalLinkageAttr *
3613 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3614 IdentifierInfo *Ident,
3615 unsigned AttrSpellingListIndex) {
3616 if (auto VD = dyn_cast<VarDecl>(D)) {
3617 // Attribute applies to Var but not any subclass of it (like ParmVar,
3618 // ImplicitParm or VarTemplateSpecialization).
3619 if (VD->getKind() != Decl::Var) {
3620 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3621 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3622 : ExpectedVariableOrFunction);
3625 // Attribute does not apply to non-static local variables.
3626 if (VD->hasLocalStorage()) {
3627 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3632 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3635 return ::new (Context)
3636 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3639 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3640 unsigned AttrSpellingListIndex) {
3641 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3642 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3643 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3647 if (D->hasAttr<MinSizeAttr>())
3650 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3653 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3654 unsigned AttrSpellingListIndex) {
3655 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3656 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3657 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3658 D->dropAttr<AlwaysInlineAttr>();
3660 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3661 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3662 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3663 D->dropAttr<MinSizeAttr>();
3666 if (D->hasAttr<OptimizeNoneAttr>())
3669 return ::new (Context) OptimizeNoneAttr(Range, Context,
3670 AttrSpellingListIndex);
3673 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3674 const AttributeList &Attr) {
3675 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3679 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3680 D, Attr.getRange(), Attr.getName(),
3681 Attr.getAttributeSpellingListIndex()))
3685 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3686 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3687 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3688 D->addAttr(MinSize);
3691 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3692 const AttributeList &Attr) {
3693 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3694 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3695 D->addAttr(Optnone);
3698 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3699 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
3701 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
3705 FunctionDecl *FD = cast<FunctionDecl>(D);
3706 if (!FD->getReturnType()->isVoidType()) {
3707 SourceRange RTRange = FD->getReturnTypeSourceRange();
3708 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3710 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3714 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
3715 if (Method->isInstance()) {
3716 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
3720 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
3722 // Only warn for "inline" when compiling for host, to cut down on noise.
3723 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
3724 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
3726 D->addAttr(::new (S.Context)
3727 CUDAGlobalAttr(Attr.getRange(), S.Context,
3728 Attr.getAttributeSpellingListIndex()));
3731 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3732 FunctionDecl *Fn = cast<FunctionDecl>(D);
3733 if (!Fn->isInlineSpecified()) {
3734 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3738 D->addAttr(::new (S.Context)
3739 GNUInlineAttr(Attr.getRange(), S.Context,
3740 Attr.getAttributeSpellingListIndex()));
3743 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3744 if (hasDeclarator(D)) return;
3746 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3747 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3749 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
3752 if (!isa<ObjCMethodDecl>(D)) {
3753 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3754 << Attr.getName() << ExpectedFunctionOrMethod;
3758 switch (Attr.getKind()) {
3759 case AttributeList::AT_FastCall:
3760 D->addAttr(::new (S.Context)
3761 FastCallAttr(Attr.getRange(), S.Context,
3762 Attr.getAttributeSpellingListIndex()));
3764 case AttributeList::AT_StdCall:
3765 D->addAttr(::new (S.Context)
3766 StdCallAttr(Attr.getRange(), S.Context,
3767 Attr.getAttributeSpellingListIndex()));
3769 case AttributeList::AT_ThisCall:
3770 D->addAttr(::new (S.Context)
3771 ThisCallAttr(Attr.getRange(), S.Context,
3772 Attr.getAttributeSpellingListIndex()));
3774 case AttributeList::AT_CDecl:
3775 D->addAttr(::new (S.Context)
3776 CDeclAttr(Attr.getRange(), S.Context,
3777 Attr.getAttributeSpellingListIndex()));
3779 case AttributeList::AT_Pascal:
3780 D->addAttr(::new (S.Context)
3781 PascalAttr(Attr.getRange(), S.Context,
3782 Attr.getAttributeSpellingListIndex()));
3784 case AttributeList::AT_SwiftCall:
3785 D->addAttr(::new (S.Context)
3786 SwiftCallAttr(Attr.getRange(), S.Context,
3787 Attr.getAttributeSpellingListIndex()));
3789 case AttributeList::AT_VectorCall:
3790 D->addAttr(::new (S.Context)
3791 VectorCallAttr(Attr.getRange(), S.Context,
3792 Attr.getAttributeSpellingListIndex()));
3794 case AttributeList::AT_MSABI:
3795 D->addAttr(::new (S.Context)
3796 MSABIAttr(Attr.getRange(), S.Context,
3797 Attr.getAttributeSpellingListIndex()));
3799 case AttributeList::AT_SysVABI:
3800 D->addAttr(::new (S.Context)
3801 SysVABIAttr(Attr.getRange(), S.Context,
3802 Attr.getAttributeSpellingListIndex()));
3804 case AttributeList::AT_Pcs: {
3805 PcsAttr::PCSType PCS;
3808 PCS = PcsAttr::AAPCS;
3811 PCS = PcsAttr::AAPCS_VFP;
3814 llvm_unreachable("unexpected calling convention in pcs attribute");
3817 D->addAttr(::new (S.Context)
3818 PcsAttr(Attr.getRange(), S.Context, PCS,
3819 Attr.getAttributeSpellingListIndex()));
3822 case AttributeList::AT_IntelOclBicc:
3823 D->addAttr(::new (S.Context)
3824 IntelOclBiccAttr(Attr.getRange(), S.Context,
3825 Attr.getAttributeSpellingListIndex()));
3827 case AttributeList::AT_PreserveMost:
3828 D->addAttr(::new (S.Context) PreserveMostAttr(
3829 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3831 case AttributeList::AT_PreserveAll:
3832 D->addAttr(::new (S.Context) PreserveAllAttr(
3833 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3836 llvm_unreachable("unexpected attribute kind");
3840 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3841 const FunctionDecl *FD) {
3842 if (attr.isInvalid())
3845 if (attr.hasProcessingCache()) {
3846 CC = (CallingConv) attr.getProcessingCache();
3850 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3851 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3856 // TODO: diagnose uses of these conventions on the wrong target.
3857 switch (attr.getKind()) {
3858 case AttributeList::AT_CDecl: CC = CC_C; break;
3859 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3860 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3861 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3862 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3863 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
3864 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
3865 case AttributeList::AT_MSABI:
3866 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3869 case AttributeList::AT_SysVABI:
3870 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3873 case AttributeList::AT_Pcs: {
3875 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3879 if (StrRef == "aapcs") {
3882 } else if (StrRef == "aapcs-vfp") {
3888 Diag(attr.getLoc(), diag::err_invalid_pcs);
3891 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3892 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
3893 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
3894 default: llvm_unreachable("unexpected attribute kind");
3897 const TargetInfo &TI = Context.getTargetInfo();
3898 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3899 if (A != TargetInfo::CCCR_OK) {
3900 if (A == TargetInfo::CCCR_Warning)
3901 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3903 // This convention is not valid for the target. Use the default function or
3904 // method calling convention.
3905 bool IsCXXMethod = false, IsVariadic = false;
3907 IsCXXMethod = FD->isCXXInstanceMember();
3908 IsVariadic = FD->isVariadic();
3910 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
3913 attr.setProcessingCache((unsigned) CC);
3917 /// Pointer-like types in the default address space.
3918 static bool isValidSwiftContextType(QualType type) {
3919 if (!type->hasPointerRepresentation())
3920 return type->isDependentType();
3921 return type->getPointeeType().getAddressSpace() == 0;
3924 /// Pointers and references in the default address space.
3925 static bool isValidSwiftIndirectResultType(QualType type) {
3926 if (auto ptrType = type->getAs<PointerType>()) {
3927 type = ptrType->getPointeeType();
3928 } else if (auto refType = type->getAs<ReferenceType>()) {
3929 type = refType->getPointeeType();
3931 return type->isDependentType();
3933 return type.getAddressSpace() == 0;
3936 /// Pointers and references to pointers in the default address space.
3937 static bool isValidSwiftErrorResultType(QualType type) {
3938 if (auto ptrType = type->getAs<PointerType>()) {
3939 type = ptrType->getPointeeType();
3940 } else if (auto refType = type->getAs<ReferenceType>()) {
3941 type = refType->getPointeeType();
3943 return type->isDependentType();
3945 if (!type.getQualifiers().empty())
3947 return isValidSwiftContextType(type);
3950 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
3952 S.AddParameterABIAttr(attr.getRange(), D, abi,
3953 attr.getAttributeSpellingListIndex());
3956 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
3957 unsigned spellingIndex) {
3959 QualType type = cast<ParmVarDecl>(D)->getType();
3961 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
3962 if (existingAttr->getABI() != abi) {
3963 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
3964 << getParameterABISpelling(abi) << existingAttr;
3965 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
3971 case ParameterABI::Ordinary:
3972 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
3974 case ParameterABI::SwiftContext:
3975 if (!isValidSwiftContextType(type)) {
3976 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
3977 << getParameterABISpelling(abi)
3978 << /*pointer to pointer */ 0 << type;
3980 D->addAttr(::new (Context)
3981 SwiftContextAttr(range, Context, spellingIndex));
3984 case ParameterABI::SwiftErrorResult:
3985 if (!isValidSwiftErrorResultType(type)) {
3986 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
3987 << getParameterABISpelling(abi)
3988 << /*pointer to pointer */ 1 << type;
3990 D->addAttr(::new (Context)
3991 SwiftErrorResultAttr(range, Context, spellingIndex));
3994 case ParameterABI::SwiftIndirectResult:
3995 if (!isValidSwiftIndirectResultType(type)) {
3996 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
3997 << getParameterABISpelling(abi)
3998 << /*pointer*/ 0 << type;
4000 D->addAttr(::new (Context)
4001 SwiftIndirectResultAttr(range, Context, spellingIndex));
4004 llvm_unreachable("bad parameter ABI attribute");
4007 /// Checks a regparm attribute, returning true if it is ill-formed and
4008 /// otherwise setting numParams to the appropriate value.
4009 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4010 if (Attr.isInvalid())
4013 if (!checkAttributeNumArgs(*this, Attr, 1)) {
4019 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4020 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4025 if (Context.getTargetInfo().getRegParmMax() == 0) {
4026 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4027 << NumParamsExpr->getSourceRange();
4033 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4034 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4035 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4043 // Checks whether an argument of launch_bounds attribute is
4044 // acceptable, performs implicit conversion to Rvalue, and returns
4045 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4046 // and may output an error.
4047 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4048 const CUDALaunchBoundsAttr &Attr,
4049 const unsigned Idx) {
4050 if (S.DiagnoseUnexpandedParameterPack(E))
4053 // Accept template arguments for now as they depend on something else.
4054 // We'll get to check them when they eventually get instantiated.
4055 if (E->isValueDependent())
4059 if (!E->isIntegerConstantExpr(I, S.Context)) {
4060 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4061 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4064 // Make sure we can fit it in 32 bits.
4065 if (!I.isIntN(32)) {
4066 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4067 << 32 << /* Unsigned */ 1;
4071 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4072 << &Attr << Idx << E->getSourceRange();
4074 // We may need to perform implicit conversion of the argument.
4075 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4076 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4077 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4078 assert(!ValArg.isInvalid() &&
4079 "Unexpected PerformCopyInitialization() failure.");
4081 return ValArg.getAs<Expr>();
4084 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4085 Expr *MinBlocks, unsigned SpellingListIndex) {
4086 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4088 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4089 if (MaxThreads == nullptr)
4093 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4094 if (MinBlocks == nullptr)
4098 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4099 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4102 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4103 const AttributeList &Attr) {
4104 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4105 !checkAttributeAtMostNumArgs(S, Attr, 2))
4108 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4109 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4110 Attr.getAttributeSpellingListIndex());
4113 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4114 const AttributeList &Attr) {
4115 if (!Attr.isArgIdent(0)) {
4116 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4117 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4121 if (!checkAttributeNumArgs(S, Attr, 3))
4124 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4126 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4127 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4128 << Attr.getName() << ExpectedFunctionOrMethod;
4132 uint64_t ArgumentIdx;
4133 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4137 uint64_t TypeTagIdx;
4138 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4142 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4144 // Ensure that buffer has a pointer type.
4145 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4146 if (!BufferTy->isPointerType()) {
4147 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4148 << Attr.getName() << 0;
4152 D->addAttr(::new (S.Context)
4153 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4154 ArgumentIdx, TypeTagIdx, IsPointer,
4155 Attr.getAttributeSpellingListIndex()));
4158 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4159 const AttributeList &Attr) {
4160 if (!Attr.isArgIdent(0)) {
4161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4162 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4166 if (!checkAttributeNumArgs(S, Attr, 1))
4169 if (!isa<VarDecl>(D)) {
4170 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4171 << Attr.getName() << ExpectedVariable;
4175 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4176 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4177 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4178 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4180 D->addAttr(::new (S.Context)
4181 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4183 Attr.getLayoutCompatible(),
4184 Attr.getMustBeNull(),
4185 Attr.getAttributeSpellingListIndex()));
4188 //===----------------------------------------------------------------------===//
4189 // Checker-specific attribute handlers.
4190 //===----------------------------------------------------------------------===//
4192 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4193 return type->isDependentType() ||
4194 type->isObjCRetainableType();
4197 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4198 return type->isDependentType() ||
4199 type->isObjCObjectPointerType() ||
4200 S.Context.isObjCNSObjectType(type);
4203 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4204 return type->isDependentType() ||
4205 type->isPointerType() ||
4206 isValidSubjectOfNSAttribute(S, type);
4209 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4210 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4211 Attr.getKind() == AttributeList::AT_NSConsumed,
4212 /*template instantiation*/ false);
4215 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4216 unsigned spellingIndex, bool isNSConsumed,
4217 bool isTemplateInstantiation) {
4218 ParmVarDecl *param = cast<ParmVarDecl>(D);
4222 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4224 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4228 // These attributes are normally just advisory, but in ARC, ns_consumed
4229 // is significant. Allow non-dependent code to contain inappropriate
4230 // attributes even in ARC, but require template instantiations to be
4231 // set up correctly.
4232 Diag(D->getLocStart(),
4233 (isTemplateInstantiation && isNSConsumed &&
4234 getLangOpts().ObjCAutoRefCount
4235 ? diag::err_ns_attribute_wrong_parameter_type
4236 : diag::warn_ns_attribute_wrong_parameter_type))
4238 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4239 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4244 param->addAttr(::new (Context)
4245 NSConsumedAttr(attrRange, Context, spellingIndex));
4247 param->addAttr(::new (Context)
4248 CFConsumedAttr(attrRange, Context, spellingIndex));
4251 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4252 const AttributeList &Attr) {
4253 QualType returnType;
4255 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4256 returnType = MD->getReturnType();
4257 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4258 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4259 return; // ignore: was handled as a type attribute
4260 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4261 returnType = PD->getType();
4262 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4263 returnType = FD->getReturnType();
4264 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4265 returnType = Param->getType()->getPointeeType();
4266 if (returnType.isNull()) {
4267 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4268 << Attr.getName() << /*pointer-to-CF*/2
4273 AttributeDeclKind ExpectedDeclKind;
4274 switch (Attr.getKind()) {
4275 default: llvm_unreachable("invalid ownership attribute");
4276 case AttributeList::AT_NSReturnsRetained:
4277 case AttributeList::AT_NSReturnsAutoreleased:
4278 case AttributeList::AT_NSReturnsNotRetained:
4279 ExpectedDeclKind = ExpectedFunctionOrMethod;
4282 case AttributeList::AT_CFReturnsRetained:
4283 case AttributeList::AT_CFReturnsNotRetained:
4284 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4287 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4288 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4294 switch (Attr.getKind()) {
4295 default: llvm_unreachable("invalid ownership attribute");
4296 case AttributeList::AT_NSReturnsRetained:
4297 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4301 case AttributeList::AT_NSReturnsAutoreleased:
4302 case AttributeList::AT_NSReturnsNotRetained:
4303 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4307 case AttributeList::AT_CFReturnsRetained:
4308 case AttributeList::AT_CFReturnsNotRetained:
4309 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4315 if (isa<ParmVarDecl>(D)) {
4316 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4317 << Attr.getName() << /*pointer-to-CF*/2
4320 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4325 } SubjectKind = Function;
4326 if (isa<ObjCMethodDecl>(D))
4327 SubjectKind = Method;
4328 else if (isa<ObjCPropertyDecl>(D))
4329 SubjectKind = Property;
4330 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4331 << Attr.getName() << SubjectKind << cf
4337 switch (Attr.getKind()) {
4339 llvm_unreachable("invalid ownership attribute");
4340 case AttributeList::AT_NSReturnsAutoreleased:
4341 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4342 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4344 case AttributeList::AT_CFReturnsNotRetained:
4345 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4346 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4348 case AttributeList::AT_NSReturnsNotRetained:
4349 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4350 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4352 case AttributeList::AT_CFReturnsRetained:
4353 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4354 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4356 case AttributeList::AT_NSReturnsRetained:
4357 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4358 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4363 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4364 const AttributeList &attr) {
4365 const int EP_ObjCMethod = 1;
4366 const int EP_ObjCProperty = 2;
4368 SourceLocation loc = attr.getLoc();
4369 QualType resultType;
4370 if (isa<ObjCMethodDecl>(D))
4371 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4373 resultType = cast<ObjCPropertyDecl>(D)->getType();
4375 if (!resultType->isReferenceType() &&
4376 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4377 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4380 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4381 << /*non-retainable pointer*/ 2;
4383 // Drop the attribute.
4387 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4388 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4391 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4392 const AttributeList &attr) {
4393 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4395 DeclContext *DC = method->getDeclContext();
4396 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4397 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4398 << attr.getName() << 0;
4399 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4402 if (method->getMethodFamily() == OMF_dealloc) {
4403 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4404 << attr.getName() << 1;
4408 method->addAttr(::new (S.Context)
4409 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4410 attr.getAttributeSpellingListIndex()));
4413 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4414 const AttributeList &Attr) {
4415 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4419 D->addAttr(::new (S.Context)
4420 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4421 Attr.getAttributeSpellingListIndex()));
4424 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4425 const AttributeList &Attr) {
4426 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4430 D->addAttr(::new (S.Context)
4431 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4432 Attr.getAttributeSpellingListIndex()));
4435 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4436 const AttributeList &Attr) {
4437 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4440 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4444 // Typedefs only allow objc_bridge(id) and have some additional checking.
4445 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4446 if (!Parm->Ident->isStr("id")) {
4447 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4452 // Only allow 'cv void *'.
4453 QualType T = TD->getUnderlyingType();
4454 if (!T->isVoidPointerType()) {
4455 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4460 D->addAttr(::new (S.Context)
4461 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4462 Attr.getAttributeSpellingListIndex()));
4465 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4466 const AttributeList &Attr) {
4467 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4470 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4474 D->addAttr(::new (S.Context)
4475 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4476 Attr.getAttributeSpellingListIndex()));
4479 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4480 const AttributeList &Attr) {
4481 IdentifierInfo *RelatedClass =
4482 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4483 if (!RelatedClass) {
4484 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4487 IdentifierInfo *ClassMethod =
4488 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4489 IdentifierInfo *InstanceMethod =
4490 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4491 D->addAttr(::new (S.Context)
4492 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4493 ClassMethod, InstanceMethod,
4494 Attr.getAttributeSpellingListIndex()));
4497 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4498 const AttributeList &Attr) {
4499 ObjCInterfaceDecl *IFace;
4500 if (ObjCCategoryDecl *CatDecl =
4501 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4502 IFace = CatDecl->getClassInterface();
4504 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4509 IFace->setHasDesignatedInitializers();
4510 D->addAttr(::new (S.Context)
4511 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4512 Attr.getAttributeSpellingListIndex()));
4515 static void handleObjCRuntimeName(Sema &S, Decl *D,
4516 const AttributeList &Attr) {
4517 StringRef MetaDataName;
4518 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4520 D->addAttr(::new (S.Context)
4521 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4523 Attr.getAttributeSpellingListIndex()));
4526 // When a user wants to use objc_boxable with a union or struct
4527 // but they don't have access to the declaration (legacy/third-party code)
4528 // then they can 'enable' this feature with a typedef:
4529 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4530 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4531 bool notify = false;
4533 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4534 if (RD && RD->getDefinition()) {
4535 RD = RD->getDefinition();
4540 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4541 ObjCBoxableAttr(Attr.getRange(), S.Context,
4542 Attr.getAttributeSpellingListIndex());
4543 RD->addAttr(BoxableAttr);
4545 // we need to notify ASTReader/ASTWriter about
4546 // modification of existing declaration
4547 if (ASTMutationListener *L = S.getASTMutationListener())
4548 L->AddedAttributeToRecord(BoxableAttr, RD);
4553 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4554 const AttributeList &Attr) {
4555 if (hasDeclarator(D)) return;
4557 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4558 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4561 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4562 const AttributeList &Attr) {
4563 ValueDecl *vd = cast<ValueDecl>(D);
4564 QualType type = vd->getType();
4566 if (!type->isDependentType() &&
4567 !type->isObjCLifetimeType()) {
4568 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4573 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4575 // If we have no lifetime yet, check the lifetime we're presumably
4577 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4578 lifetime = type->getObjCARCImplicitLifetime();
4581 case Qualifiers::OCL_None:
4582 assert(type->isDependentType() &&
4583 "didn't infer lifetime for non-dependent type?");
4586 case Qualifiers::OCL_Weak: // meaningful
4587 case Qualifiers::OCL_Strong: // meaningful
4590 case Qualifiers::OCL_ExplicitNone:
4591 case Qualifiers::OCL_Autoreleasing:
4592 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4593 << (lifetime == Qualifiers::OCL_Autoreleasing);
4597 D->addAttr(::new (S.Context)
4598 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4599 Attr.getAttributeSpellingListIndex()));
4602 //===----------------------------------------------------------------------===//
4603 // Microsoft specific attribute handlers.
4604 //===----------------------------------------------------------------------===//
4606 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4607 if (!S.LangOpts.CPlusPlus) {
4608 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4609 << Attr.getName() << AttributeLangSupport::C;
4613 if (!isa<CXXRecordDecl>(D)) {
4614 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4615 << Attr.getName() << ExpectedClass;
4620 SourceLocation LiteralLoc;
4621 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4624 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4625 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4626 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4627 StrRef = StrRef.drop_front().drop_back();
4629 // Validate GUID length.
4630 if (StrRef.size() != 36) {
4631 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4635 for (unsigned i = 0; i < 36; ++i) {
4636 if (i == 8 || i == 13 || i == 18 || i == 23) {
4637 if (StrRef[i] != '-') {
4638 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4641 } else if (!isHexDigit(StrRef[i])) {
4642 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4647 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4648 Attr.getAttributeSpellingListIndex()));
4651 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4652 if (!S.LangOpts.CPlusPlus) {
4653 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4654 << Attr.getName() << AttributeLangSupport::C;
4657 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
4658 D, Attr.getRange(), /*BestCase=*/true,
4659 Attr.getAttributeSpellingListIndex(),
4660 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
4663 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
4667 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4668 const AttributeList &Attr) {
4669 VarDecl *VD = cast<VarDecl>(D);
4670 if (!S.Context.getTargetInfo().isTLSSupported()) {
4671 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4674 if (VD->getTSCSpec() != TSCS_unspecified) {
4675 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4678 if (VD->hasLocalStorage()) {
4679 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4682 VD->addAttr(::new (S.Context) ThreadAttr(
4683 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4686 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4687 SmallVector<StringRef, 4> Tags;
4688 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4690 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
4692 Tags.push_back(Tag);
4695 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
4696 if (!NS->isInline()) {
4697 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
4700 if (NS->isAnonymousNamespace()) {
4701 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
4704 if (Attr.getNumArgs() == 0)
4705 Tags.push_back(NS->getName());
4706 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4709 // Store tags sorted and without duplicates.
4710 std::sort(Tags.begin(), Tags.end());
4711 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
4713 D->addAttr(::new (S.Context)
4714 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
4715 Attr.getAttributeSpellingListIndex()));
4718 static void handleARMInterruptAttr(Sema &S, Decl *D,
4719 const AttributeList &Attr) {
4720 // Check the attribute arguments.
4721 if (Attr.getNumArgs() > 1) {
4722 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4723 << Attr.getName() << 1;
4728 SourceLocation ArgLoc;
4730 if (Attr.getNumArgs() == 0)
4732 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4735 ARMInterruptAttr::InterruptType Kind;
4736 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4737 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4738 << Attr.getName() << Str << ArgLoc;
4742 unsigned Index = Attr.getAttributeSpellingListIndex();
4743 D->addAttr(::new (S.Context)
4744 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4747 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4748 const AttributeList &Attr) {
4749 if (!checkAttributeNumArgs(S, Attr, 1))
4752 if (!Attr.isArgExpr(0)) {
4753 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4754 << AANT_ArgumentIntegerConstant;
4758 // FIXME: Check for decl - it should be void ()(void).
4760 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4761 llvm::APSInt NumParams(32);
4762 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4763 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4764 << Attr.getName() << AANT_ArgumentIntegerConstant
4765 << NumParamsExpr->getSourceRange();
4769 unsigned Num = NumParams.getLimitedValue(255);
4770 if ((Num & 1) || Num > 30) {
4771 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4772 << Attr.getName() << (int)NumParams.getSExtValue()
4773 << NumParamsExpr->getSourceRange();
4777 D->addAttr(::new (S.Context)
4778 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
4779 Attr.getAttributeSpellingListIndex()));
4780 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4783 static void handleMipsInterruptAttr(Sema &S, Decl *D,
4784 const AttributeList &Attr) {
4785 // Only one optional argument permitted.
4786 if (Attr.getNumArgs() > 1) {
4787 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4788 << Attr.getName() << 1;
4793 SourceLocation ArgLoc;
4795 if (Attr.getNumArgs() == 0)
4797 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4800 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
4801 // a) Must be a function.
4802 // b) Must have no parameters.
4803 // c) Must have the 'void' return type.
4804 // d) Cannot have the 'mips16' attribute, as that instruction set
4805 // lacks the 'eret' instruction.
4806 // e) The attribute itself must either have no argument or one of the
4807 // valid interrupt types, see [MipsInterruptDocs].
4809 if (!isFunctionOrMethod(D)) {
4810 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
4811 << "'interrupt'" << ExpectedFunctionOrMethod;
4815 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
4816 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4821 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4822 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
4827 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
4831 MipsInterruptAttr::InterruptType Kind;
4832 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4833 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4834 << Attr.getName() << "'" + std::string(Str) + "'";
4838 D->addAttr(::new (S.Context) MipsInterruptAttr(
4839 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
4842 static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
4843 const AttributeList &Attr) {
4844 // Semantic checks for a function with the 'interrupt' attribute.
4845 // a) Must be a function.
4846 // b) Must have the 'void' return type.
4847 // c) Must take 1 or 2 arguments.
4848 // d) The 1st argument must be a pointer.
4849 // e) The 2nd argument (if any) must be an unsigned integer.
4850 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
4851 CXXMethodDecl::isStaticOverloadedOperator(
4852 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
4853 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4854 << Attr.getName() << ExpectedFunctionWithProtoType;
4857 // Interrupt handler must have void return type.
4858 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
4859 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
4860 diag::err_anyx86_interrupt_attribute)
4861 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4867 // Interrupt handler must have 1 or 2 parameters.
4868 unsigned NumParams = getFunctionOrMethodNumParams(D);
4869 if (NumParams < 1 || NumParams > 2) {
4870 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
4871 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4877 // The first argument must be a pointer.
4878 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
4879 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
4880 diag::err_anyx86_interrupt_attribute)
4881 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4887 // The second argument, if present, must be an unsigned integer.
4889 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
4892 if (NumParams == 2 &&
4893 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
4894 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
4895 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
4896 diag::err_anyx86_interrupt_attribute)
4897 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
4900 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
4903 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
4904 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
4905 D->addAttr(UsedAttr::CreateImplicit(S.Context));
4908 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4909 // Dispatch the interrupt attribute based on the current target.
4910 switch (S.Context.getTargetInfo().getTriple().getArch()) {
4911 case llvm::Triple::msp430:
4912 handleMSP430InterruptAttr(S, D, Attr);
4914 case llvm::Triple::mipsel:
4915 case llvm::Triple::mips:
4916 handleMipsInterruptAttr(S, D, Attr);
4918 case llvm::Triple::x86:
4919 case llvm::Triple::x86_64:
4920 handleAnyX86InterruptAttr(S, D, Attr);
4923 handleARMInterruptAttr(S, D, Attr);
4928 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
4929 const AttributeList &Attr) {
4931 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4932 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4935 D->addAttr(::new (S.Context)
4936 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context,
4938 Attr.getAttributeSpellingListIndex()));
4941 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
4942 const AttributeList &Attr) {
4944 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4945 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs))
4948 D->addAttr(::new (S.Context)
4949 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context,
4951 Attr.getAttributeSpellingListIndex()));
4954 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
4955 const AttributeList& Attr) {
4956 // If we try to apply it to a function pointer, don't warn, but don't
4957 // do anything, either. It doesn't matter anyway, because there's nothing
4958 // special about calling a force_align_arg_pointer function.
4959 ValueDecl *VD = dyn_cast<ValueDecl>(D);
4960 if (VD && VD->getType()->isFunctionPointerType())
4962 // Also don't warn on function pointer typedefs.
4963 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
4964 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
4965 TD->getUnderlyingType()->isFunctionType()))
4967 // Attribute can only be applied to function types.
4968 if (!isa<FunctionDecl>(D)) {
4969 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4970 << Attr.getName() << /* function */0;
4974 D->addAttr(::new (S.Context)
4975 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
4976 Attr.getAttributeSpellingListIndex()));
4979 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
4981 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4982 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
4985 // TODO: Investigate what happens with the next major version of MSVC.
4986 if (Version != LangOptions::MSVC2015) {
4987 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4988 << Attr.getName() << Version << VersionExpr->getSourceRange();
4992 D->addAttr(::new (S.Context)
4993 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
4994 Attr.getAttributeSpellingListIndex()));
4997 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
4998 unsigned AttrSpellingListIndex) {
4999 if (D->hasAttr<DLLExportAttr>()) {
5000 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5004 if (D->hasAttr<DLLImportAttr>())
5007 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5010 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5011 unsigned AttrSpellingListIndex) {
5012 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5013 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5014 D->dropAttr<DLLImportAttr>();
5017 if (D->hasAttr<DLLExportAttr>())
5020 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5023 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5024 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5025 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5026 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5032 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5033 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5034 // MinGW doesn't allow dllimport on inline functions.
5035 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5041 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5042 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5043 MD->getParent()->isLambda()) {
5044 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5049 unsigned Index = A.getAttributeSpellingListIndex();
5050 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5051 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5052 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5054 D->addAttr(NewAttr);
5058 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5059 unsigned AttrSpellingListIndex,
5060 MSInheritanceAttr::Spelling SemanticSpelling) {
5061 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5062 if (IA->getSemanticSpelling() == SemanticSpelling)
5064 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5065 << 1 /*previous declaration*/;
5066 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5067 D->dropAttr<MSInheritanceAttr>();
5070 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5071 if (RD->hasDefinition()) {
5072 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5073 SemanticSpelling)) {
5077 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5078 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5079 << 1 /*partial specialization*/;
5082 if (RD->getDescribedClassTemplate()) {
5083 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5084 << 0 /*primary template*/;
5089 return ::new (Context)
5090 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5093 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5094 // The capability attributes take a single string parameter for the name of
5095 // the capability they represent. The lockable attribute does not take any
5096 // parameters. However, semantically, both attributes represent the same
5097 // concept, and so they use the same semantic attribute. Eventually, the
5098 // lockable attribute will be removed.
5100 // For backward compatibility, any capability which has no specified string
5101 // literal will be considered a "mutex."
5102 StringRef N("mutex");
5103 SourceLocation LiteralLoc;
5104 if (Attr.getKind() == AttributeList::AT_Capability &&
5105 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5108 // Currently, there are only two names allowed for a capability: role and
5109 // mutex (case insensitive). Diagnose other capability names.
5110 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5111 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5113 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5114 Attr.getAttributeSpellingListIndex()));
5117 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5118 const AttributeList &Attr) {
5119 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5120 Attr.getArgAsExpr(0),
5121 Attr.getAttributeSpellingListIndex()));
5124 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5125 const AttributeList &Attr) {
5126 SmallVector<Expr*, 1> Args;
5127 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5130 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5132 Args.data(), Args.size(),
5133 Attr.getAttributeSpellingListIndex()));
5136 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5137 const AttributeList &Attr) {
5138 SmallVector<Expr*, 2> Args;
5139 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5142 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5144 Attr.getArgAsExpr(0),
5147 Attr.getAttributeSpellingListIndex()));
5150 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5151 const AttributeList &Attr) {
5152 // Check that all arguments are lockable objects.
5153 SmallVector<Expr *, 1> Args;
5154 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5156 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5157 Attr.getRange(), S.Context, Args.data(), Args.size(),
5158 Attr.getAttributeSpellingListIndex()));
5161 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5162 const AttributeList &Attr) {
5163 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5166 // check that all arguments are lockable objects
5167 SmallVector<Expr*, 1> Args;
5168 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5172 RequiresCapabilityAttr *RCA = ::new (S.Context)
5173 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5174 Args.size(), Attr.getAttributeSpellingListIndex());
5179 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5180 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5181 if (NSD->isAnonymousNamespace()) {
5182 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5183 // Do not want to attach the attribute to the namespace because that will
5184 // cause confusing diagnostic reports for uses of declarations within the
5190 // Handle the cases where the attribute has a text message.
5191 StringRef Str, Replacement;
5192 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5193 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5196 // Only support a single optional message for Declspec and CXX11.
5197 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5198 checkAttributeAtMostNumArgs(S, Attr, 1);
5199 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5200 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5203 if (!S.getLangOpts().CPlusPlus14)
5204 if (Attr.isCXX11Attribute() &&
5205 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5206 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5208 D->addAttr(::new (S.Context) DeprecatedAttr(Attr.getRange(), S.Context, Str,
5210 Attr.getAttributeSpellingListIndex()));
5213 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5214 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5217 std::vector<StringRef> Sanitizers;
5219 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5220 StringRef SanitizerName;
5221 SourceLocation LiteralLoc;
5223 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5226 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5227 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5229 Sanitizers.push_back(SanitizerName);
5232 D->addAttr(::new (S.Context) NoSanitizeAttr(
5233 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5234 Attr.getAttributeSpellingListIndex()));
5237 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5238 const AttributeList &Attr) {
5239 StringRef AttrName = Attr.getName()->getName();
5240 normalizeName(AttrName);
5241 StringRef SanitizerName =
5242 llvm::StringSwitch<StringRef>(AttrName)
5243 .Case("no_address_safety_analysis", "address")
5244 .Case("no_sanitize_address", "address")
5245 .Case("no_sanitize_thread", "thread")
5246 .Case("no_sanitize_memory", "memory");
5247 D->addAttr(::new (S.Context)
5248 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5249 Attr.getAttributeSpellingListIndex()));
5252 static void handleInternalLinkageAttr(Sema &S, Decl *D,
5253 const AttributeList &Attr) {
5254 if (InternalLinkageAttr *Internal =
5255 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5256 Attr.getAttributeSpellingListIndex()))
5257 D->addAttr(Internal);
5260 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5261 if (S.LangOpts.OpenCLVersion != 200)
5262 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5263 << Attr.getName() << "2.0" << 0;
5265 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5266 << Attr.getName() << "2.0";
5269 /// Handles semantic checking for features that are common to all attributes,
5270 /// such as checking whether a parameter was properly specified, or the correct
5271 /// number of arguments were passed, etc.
5272 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5273 const AttributeList &Attr) {
5274 // Several attributes carry different semantics than the parsing requires, so
5275 // those are opted out of the common handling.
5277 // We also bail on unknown and ignored attributes because those are handled
5278 // as part of the target-specific handling logic.
5279 if (Attr.hasCustomParsing() ||
5280 Attr.getKind() == AttributeList::UnknownAttribute)
5283 // Check whether the attribute requires specific language extensions to be
5285 if (!Attr.diagnoseLangOpts(S))
5288 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5289 // If there are no optional arguments, then checking for the argument count
5291 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5294 // There are optional arguments, so checking is slightly more involved.
5295 if (Attr.getMinArgs() &&
5296 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5298 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5299 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5303 // Check whether the attribute appertains to the given subject.
5304 if (!Attr.diagnoseAppertainsTo(S, D))
5310 static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5311 const AttributeList &Attr) {
5312 if (D->isInvalidDecl())
5315 // Check if there is only one access qualifier.
5316 if (D->hasAttr<OpenCLAccessAttr>()) {
5317 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5318 << D->getSourceRange();
5319 D->setInvalidDecl(true);
5323 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5324 // image object can be read and written.
5325 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5326 // object. Using the read_write (or __read_write) qualifier with the pipe
5327 // qualifier is a compilation error.
5328 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5329 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5330 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5331 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5332 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5333 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5334 D->setInvalidDecl(true);
5340 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5341 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5344 //===----------------------------------------------------------------------===//
5345 // Top Level Sema Entry Points
5346 //===----------------------------------------------------------------------===//
5348 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5349 /// the attribute applies to decls. If the attribute is a type attribute, just
5350 /// silently ignore it if a GNU attribute.
5351 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5352 const AttributeList &Attr,
5353 bool IncludeCXX11Attributes) {
5354 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5357 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5359 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5362 // Unknown attributes are automatically warned on. Target-specific attributes
5363 // which do not apply to the current target architecture are treated as
5364 // though they were unknown attributes.
5365 if (Attr.getKind() == AttributeList::UnknownAttribute ||
5366 !Attr.existsInTarget(S.Context.getTargetInfo())) {
5367 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5368 ? diag::warn_unhandled_ms_attribute_ignored
5369 : diag::warn_unknown_attribute_ignored)
5374 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5377 switch (Attr.getKind()) {
5379 if (!Attr.isStmtAttr()) {
5380 // Type attributes are handled elsewhere; silently move on.
5381 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5384 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5385 << Attr.getName() << D->getLocation();
5387 case AttributeList::AT_Interrupt:
5388 handleInterruptAttr(S, D, Attr);
5390 case AttributeList::AT_X86ForceAlignArgPointer:
5391 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5393 case AttributeList::AT_DLLExport:
5394 case AttributeList::AT_DLLImport:
5395 handleDLLAttr(S, D, Attr);
5397 case AttributeList::AT_Mips16:
5398 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5401 case AttributeList::AT_NoMips16:
5402 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5404 case AttributeList::AT_AMDGPUNumVGPR:
5405 handleAMDGPUNumVGPRAttr(S, D, Attr);
5407 case AttributeList::AT_AMDGPUNumSGPR:
5408 handleAMDGPUNumSGPRAttr(S, D, Attr);
5410 case AttributeList::AT_IBAction:
5411 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5413 case AttributeList::AT_IBOutlet:
5414 handleIBOutlet(S, D, Attr);
5416 case AttributeList::AT_IBOutletCollection:
5417 handleIBOutletCollection(S, D, Attr);
5419 case AttributeList::AT_IFunc:
5420 handleIFuncAttr(S, D, Attr);
5422 case AttributeList::AT_Alias:
5423 handleAliasAttr(S, D, Attr);
5425 case AttributeList::AT_Aligned:
5426 handleAlignedAttr(S, D, Attr);
5428 case AttributeList::AT_AlignValue:
5429 handleAlignValueAttr(S, D, Attr);
5431 case AttributeList::AT_AlwaysInline:
5432 handleAlwaysInlineAttr(S, D, Attr);
5434 case AttributeList::AT_AnalyzerNoReturn:
5435 handleAnalyzerNoReturnAttr(S, D, Attr);
5437 case AttributeList::AT_TLSModel:
5438 handleTLSModelAttr(S, D, Attr);
5440 case AttributeList::AT_Annotate:
5441 handleAnnotateAttr(S, D, Attr);
5443 case AttributeList::AT_Availability:
5444 handleAvailabilityAttr(S, D, Attr);
5446 case AttributeList::AT_CarriesDependency:
5447 handleDependencyAttr(S, scope, D, Attr);
5449 case AttributeList::AT_Common:
5450 handleCommonAttr(S, D, Attr);
5452 case AttributeList::AT_CUDAConstant:
5453 handleSimpleAttributeWithExclusions<CUDAConstantAttr, CUDASharedAttr>(S, D,
5456 case AttributeList::AT_PassObjectSize:
5457 handlePassObjectSizeAttr(S, D, Attr);
5459 case AttributeList::AT_Constructor:
5460 handleConstructorAttr(S, D, Attr);
5462 case AttributeList::AT_CXX11NoReturn:
5463 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5465 case AttributeList::AT_Deprecated:
5466 handleDeprecatedAttr(S, D, Attr);
5468 case AttributeList::AT_Destructor:
5469 handleDestructorAttr(S, D, Attr);
5471 case AttributeList::AT_EnableIf:
5472 handleEnableIfAttr(S, D, Attr);
5474 case AttributeList::AT_ExtVectorType:
5475 handleExtVectorTypeAttr(S, scope, D, Attr);
5477 case AttributeList::AT_MinSize:
5478 handleMinSizeAttr(S, D, Attr);
5480 case AttributeList::AT_OptimizeNone:
5481 handleOptimizeNoneAttr(S, D, Attr);
5483 case AttributeList::AT_FlagEnum:
5484 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5486 case AttributeList::AT_Flatten:
5487 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5489 case AttributeList::AT_Format:
5490 handleFormatAttr(S, D, Attr);
5492 case AttributeList::AT_FormatArg:
5493 handleFormatArgAttr(S, D, Attr);
5495 case AttributeList::AT_CUDAGlobal:
5496 handleGlobalAttr(S, D, Attr);
5498 case AttributeList::AT_CUDADevice:
5499 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
5502 case AttributeList::AT_CUDAHost:
5503 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
5506 case AttributeList::AT_GNUInline:
5507 handleGNUInlineAttr(S, D, Attr);
5509 case AttributeList::AT_CUDALaunchBounds:
5510 handleLaunchBoundsAttr(S, D, Attr);
5512 case AttributeList::AT_Restrict:
5513 handleRestrictAttr(S, D, Attr);
5515 case AttributeList::AT_MayAlias:
5516 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5518 case AttributeList::AT_Mode:
5519 handleModeAttr(S, D, Attr);
5521 case AttributeList::AT_NoAlias:
5522 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5524 case AttributeList::AT_NoCommon:
5525 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5527 case AttributeList::AT_NoSplitStack:
5528 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5530 case AttributeList::AT_NonNull:
5531 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5532 handleNonNullAttrParameter(S, PVD, Attr);
5534 handleNonNullAttr(S, D, Attr);
5536 case AttributeList::AT_ReturnsNonNull:
5537 handleReturnsNonNullAttr(S, D, Attr);
5539 case AttributeList::AT_AssumeAligned:
5540 handleAssumeAlignedAttr(S, D, Attr);
5542 case AttributeList::AT_Overloadable:
5543 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5545 case AttributeList::AT_Ownership:
5546 handleOwnershipAttr(S, D, Attr);
5548 case AttributeList::AT_Cold:
5549 handleColdAttr(S, D, Attr);
5551 case AttributeList::AT_Hot:
5552 handleHotAttr(S, D, Attr);
5554 case AttributeList::AT_Naked:
5555 handleNakedAttr(S, D, Attr);
5557 case AttributeList::AT_NoReturn:
5558 handleNoReturnAttr(S, D, Attr);
5560 case AttributeList::AT_NoThrow:
5561 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5563 case AttributeList::AT_CUDAShared:
5564 handleSimpleAttributeWithExclusions<CUDASharedAttr, CUDAConstantAttr>(S, D,
5567 case AttributeList::AT_VecReturn:
5568 handleVecReturnAttr(S, D, Attr);
5570 case AttributeList::AT_ObjCOwnership:
5571 handleObjCOwnershipAttr(S, D, Attr);
5573 case AttributeList::AT_ObjCPreciseLifetime:
5574 handleObjCPreciseLifetimeAttr(S, D, Attr);
5576 case AttributeList::AT_ObjCReturnsInnerPointer:
5577 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5579 case AttributeList::AT_ObjCRequiresSuper:
5580 handleObjCRequiresSuperAttr(S, D, Attr);
5582 case AttributeList::AT_ObjCBridge:
5583 handleObjCBridgeAttr(S, scope, D, Attr);
5585 case AttributeList::AT_ObjCBridgeMutable:
5586 handleObjCBridgeMutableAttr(S, scope, D, Attr);
5588 case AttributeList::AT_ObjCBridgeRelated:
5589 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
5591 case AttributeList::AT_ObjCDesignatedInitializer:
5592 handleObjCDesignatedInitializer(S, D, Attr);
5594 case AttributeList::AT_ObjCRuntimeName:
5595 handleObjCRuntimeName(S, D, Attr);
5597 case AttributeList::AT_ObjCRuntimeVisible:
5598 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
5600 case AttributeList::AT_ObjCBoxable:
5601 handleObjCBoxable(S, D, Attr);
5603 case AttributeList::AT_CFAuditedTransfer:
5604 handleCFAuditedTransferAttr(S, D, Attr);
5606 case AttributeList::AT_CFUnknownTransfer:
5607 handleCFUnknownTransferAttr(S, D, Attr);
5609 case AttributeList::AT_CFConsumed:
5610 case AttributeList::AT_NSConsumed:
5611 handleNSConsumedAttr(S, D, Attr);
5613 case AttributeList::AT_NSConsumesSelf:
5614 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
5616 case AttributeList::AT_NSReturnsAutoreleased:
5617 case AttributeList::AT_NSReturnsNotRetained:
5618 case AttributeList::AT_CFReturnsNotRetained:
5619 case AttributeList::AT_NSReturnsRetained:
5620 case AttributeList::AT_CFReturnsRetained:
5621 handleNSReturnsRetainedAttr(S, D, Attr);
5623 case AttributeList::AT_WorkGroupSizeHint:
5624 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
5626 case AttributeList::AT_ReqdWorkGroupSize:
5627 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
5629 case AttributeList::AT_VecTypeHint:
5630 handleVecTypeHint(S, D, Attr);
5632 case AttributeList::AT_InitPriority:
5633 handleInitPriorityAttr(S, D, Attr);
5635 case AttributeList::AT_Packed:
5636 handlePackedAttr(S, D, Attr);
5638 case AttributeList::AT_Section:
5639 handleSectionAttr(S, D, Attr);
5641 case AttributeList::AT_Target:
5642 handleTargetAttr(S, D, Attr);
5644 case AttributeList::AT_Unavailable:
5645 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
5647 case AttributeList::AT_ArcWeakrefUnavailable:
5648 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
5650 case AttributeList::AT_ObjCRootClass:
5651 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
5653 case AttributeList::AT_ObjCExplicitProtocolImpl:
5654 handleObjCSuppresProtocolAttr(S, D, Attr);
5656 case AttributeList::AT_ObjCRequiresPropertyDefs:
5657 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
5659 case AttributeList::AT_Unused:
5660 handleUnusedAttr(S, D, Attr);
5662 case AttributeList::AT_ReturnsTwice:
5663 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
5665 case AttributeList::AT_NotTailCalled:
5666 handleNotTailCalledAttr(S, D, Attr);
5668 case AttributeList::AT_DisableTailCalls:
5669 handleDisableTailCallsAttr(S, D, Attr);
5671 case AttributeList::AT_Used:
5672 handleUsedAttr(S, D, Attr);
5674 case AttributeList::AT_Visibility:
5675 handleVisibilityAttr(S, D, Attr, false);
5677 case AttributeList::AT_TypeVisibility:
5678 handleVisibilityAttr(S, D, Attr, true);
5680 case AttributeList::AT_WarnUnused:
5681 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
5683 case AttributeList::AT_WarnUnusedResult:
5684 handleWarnUnusedResult(S, D, Attr);
5686 case AttributeList::AT_Weak:
5687 handleSimpleAttribute<WeakAttr>(S, D, Attr);
5689 case AttributeList::AT_WeakRef:
5690 handleWeakRefAttr(S, D, Attr);
5692 case AttributeList::AT_WeakImport:
5693 handleWeakImportAttr(S, D, Attr);
5695 case AttributeList::AT_TransparentUnion:
5696 handleTransparentUnionAttr(S, D, Attr);
5698 case AttributeList::AT_ObjCException:
5699 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
5701 case AttributeList::AT_ObjCMethodFamily:
5702 handleObjCMethodFamilyAttr(S, D, Attr);
5704 case AttributeList::AT_ObjCNSObject:
5705 handleObjCNSObject(S, D, Attr);
5707 case AttributeList::AT_ObjCIndependentClass:
5708 handleObjCIndependentClass(S, D, Attr);
5710 case AttributeList::AT_Blocks:
5711 handleBlocksAttr(S, D, Attr);
5713 case AttributeList::AT_Sentinel:
5714 handleSentinelAttr(S, D, Attr);
5716 case AttributeList::AT_Const:
5717 handleSimpleAttribute<ConstAttr>(S, D, Attr);
5719 case AttributeList::AT_Pure:
5720 handleSimpleAttribute<PureAttr>(S, D, Attr);
5722 case AttributeList::AT_Cleanup:
5723 handleCleanupAttr(S, D, Attr);
5725 case AttributeList::AT_NoDebug:
5726 handleNoDebugAttr(S, D, Attr);
5728 case AttributeList::AT_NoDuplicate:
5729 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
5731 case AttributeList::AT_NoInline:
5732 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
5734 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
5735 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
5737 case AttributeList::AT_StdCall:
5738 case AttributeList::AT_CDecl:
5739 case AttributeList::AT_FastCall:
5740 case AttributeList::AT_ThisCall:
5741 case AttributeList::AT_Pascal:
5742 case AttributeList::AT_SwiftCall:
5743 case AttributeList::AT_VectorCall:
5744 case AttributeList::AT_MSABI:
5745 case AttributeList::AT_SysVABI:
5746 case AttributeList::AT_Pcs:
5747 case AttributeList::AT_IntelOclBicc:
5748 case AttributeList::AT_PreserveMost:
5749 case AttributeList::AT_PreserveAll:
5750 handleCallConvAttr(S, D, Attr);
5752 case AttributeList::AT_OpenCLKernel:
5753 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
5755 case AttributeList::AT_OpenCLAccess:
5756 handleOpenCLAccessAttr(S, D, Attr);
5758 case AttributeList::AT_OpenCLNoSVM:
5759 handleOpenCLNoSVMAttr(S, D, Attr);
5761 case AttributeList::AT_SwiftContext:
5762 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
5764 case AttributeList::AT_SwiftErrorResult:
5765 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
5767 case AttributeList::AT_SwiftIndirectResult:
5768 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
5770 case AttributeList::AT_InternalLinkage:
5771 handleInternalLinkageAttr(S, D, Attr);
5773 case AttributeList::AT_LTOVisibilityPublic:
5774 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
5777 // Microsoft attributes:
5778 case AttributeList::AT_EmptyBases:
5779 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
5781 case AttributeList::AT_LayoutVersion:
5782 handleLayoutVersion(S, D, Attr);
5784 case AttributeList::AT_MSNoVTable:
5785 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
5787 case AttributeList::AT_MSStruct:
5788 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
5790 case AttributeList::AT_Uuid:
5791 handleUuidAttr(S, D, Attr);
5793 case AttributeList::AT_MSInheritance:
5794 handleMSInheritanceAttr(S, D, Attr);
5796 case AttributeList::AT_SelectAny:
5797 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
5799 case AttributeList::AT_Thread:
5800 handleDeclspecThreadAttr(S, D, Attr);
5803 case AttributeList::AT_AbiTag:
5804 handleAbiTagAttr(S, D, Attr);
5807 // Thread safety attributes:
5808 case AttributeList::AT_AssertExclusiveLock:
5809 handleAssertExclusiveLockAttr(S, D, Attr);
5811 case AttributeList::AT_AssertSharedLock:
5812 handleAssertSharedLockAttr(S, D, Attr);
5814 case AttributeList::AT_GuardedVar:
5815 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
5817 case AttributeList::AT_PtGuardedVar:
5818 handlePtGuardedVarAttr(S, D, Attr);
5820 case AttributeList::AT_ScopedLockable:
5821 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
5823 case AttributeList::AT_NoSanitize:
5824 handleNoSanitizeAttr(S, D, Attr);
5826 case AttributeList::AT_NoSanitizeSpecific:
5827 handleNoSanitizeSpecificAttr(S, D, Attr);
5829 case AttributeList::AT_NoThreadSafetyAnalysis:
5830 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
5832 case AttributeList::AT_GuardedBy:
5833 handleGuardedByAttr(S, D, Attr);
5835 case AttributeList::AT_PtGuardedBy:
5836 handlePtGuardedByAttr(S, D, Attr);
5838 case AttributeList::AT_ExclusiveTrylockFunction:
5839 handleExclusiveTrylockFunctionAttr(S, D, Attr);
5841 case AttributeList::AT_LockReturned:
5842 handleLockReturnedAttr(S, D, Attr);
5844 case AttributeList::AT_LocksExcluded:
5845 handleLocksExcludedAttr(S, D, Attr);
5847 case AttributeList::AT_SharedTrylockFunction:
5848 handleSharedTrylockFunctionAttr(S, D, Attr);
5850 case AttributeList::AT_AcquiredBefore:
5851 handleAcquiredBeforeAttr(S, D, Attr);
5853 case AttributeList::AT_AcquiredAfter:
5854 handleAcquiredAfterAttr(S, D, Attr);
5857 // Capability analysis attributes.
5858 case AttributeList::AT_Capability:
5859 case AttributeList::AT_Lockable:
5860 handleCapabilityAttr(S, D, Attr);
5862 case AttributeList::AT_RequiresCapability:
5863 handleRequiresCapabilityAttr(S, D, Attr);
5866 case AttributeList::AT_AssertCapability:
5867 handleAssertCapabilityAttr(S, D, Attr);
5869 case AttributeList::AT_AcquireCapability:
5870 handleAcquireCapabilityAttr(S, D, Attr);
5872 case AttributeList::AT_ReleaseCapability:
5873 handleReleaseCapabilityAttr(S, D, Attr);
5875 case AttributeList::AT_TryAcquireCapability:
5876 handleTryAcquireCapabilityAttr(S, D, Attr);
5879 // Consumed analysis attributes.
5880 case AttributeList::AT_Consumable:
5881 handleConsumableAttr(S, D, Attr);
5883 case AttributeList::AT_ConsumableAutoCast:
5884 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
5886 case AttributeList::AT_ConsumableSetOnRead:
5887 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
5889 case AttributeList::AT_CallableWhen:
5890 handleCallableWhenAttr(S, D, Attr);
5892 case AttributeList::AT_ParamTypestate:
5893 handleParamTypestateAttr(S, D, Attr);
5895 case AttributeList::AT_ReturnTypestate:
5896 handleReturnTypestateAttr(S, D, Attr);
5898 case AttributeList::AT_SetTypestate:
5899 handleSetTypestateAttr(S, D, Attr);
5901 case AttributeList::AT_TestTypestate:
5902 handleTestTypestateAttr(S, D, Attr);
5905 // Type safety attributes.
5906 case AttributeList::AT_ArgumentWithTypeTag:
5907 handleArgumentWithTypeTagAttr(S, D, Attr);
5909 case AttributeList::AT_TypeTagForDatatype:
5910 handleTypeTagForDatatypeAttr(S, D, Attr);
5912 case AttributeList::AT_RenderScriptKernel:
5913 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
5916 case AttributeList::AT_XRayInstrument:
5917 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
5922 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
5923 /// attribute list to the specified decl, ignoring any type attributes.
5924 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
5925 const AttributeList *AttrList,
5926 bool IncludeCXX11Attributes) {
5927 for (const AttributeList* l = AttrList; l; l = l->getNext())
5928 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
5930 // FIXME: We should be able to handle these cases in TableGen.
5932 // static int a9 __attribute__((weakref));
5933 // but that looks really pointless. We reject it.
5934 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
5935 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
5936 << cast<NamedDecl>(D);
5937 D->dropAttr<WeakRefAttr>();
5941 // FIXME: We should be able to handle this in TableGen as well. It would be
5942 // good to have a way to specify "these attributes must appear as a group",
5943 // for these. Additionally, it would be good to have a way to specify "these
5944 // attribute must never appear as a group" for attributes like cold and hot.
5945 if (!D->hasAttr<OpenCLKernelAttr>()) {
5946 // These attributes cannot be applied to a non-kernel function.
5947 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
5948 // FIXME: This emits a different error message than
5949 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
5950 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5951 D->setInvalidDecl();
5952 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
5953 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5954 D->setInvalidDecl();
5955 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
5956 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
5957 D->setInvalidDecl();
5958 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
5959 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5960 << A << ExpectedKernelFunction;
5961 D->setInvalidDecl();
5962 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
5963 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5964 << A << ExpectedKernelFunction;
5965 D->setInvalidDecl();
5970 // Annotation attributes are the only attributes allowed after an access
5972 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
5973 const AttributeList *AttrList) {
5974 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5975 if (l->getKind() == AttributeList::AT_Annotate) {
5976 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
5978 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
5986 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
5987 /// contains any decl attributes that we should warn about.
5988 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
5989 for ( ; A; A = A->getNext()) {
5990 // Only warn if the attribute is an unignored, non-type attribute.
5991 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
5992 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
5994 if (A->getKind() == AttributeList::UnknownAttribute) {
5995 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
5996 << A->getName() << A->getRange();
5998 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
5999 << A->getName() << A->getRange();
6004 /// checkUnusedDeclAttributes - Given a declarator which is not being
6005 /// used to build a declaration, complain about any decl attributes
6006 /// which might be lying around on it.
6007 void Sema::checkUnusedDeclAttributes(Declarator &D) {
6008 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6009 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6010 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6011 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6014 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
6015 /// \#pragma weak needs a non-definition decl and source may not have one.
6016 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6017 SourceLocation Loc) {
6018 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
6019 NamedDecl *NewD = nullptr;
6020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6021 FunctionDecl *NewFD;
6022 // FIXME: Missing call to CheckFunctionDeclaration().
6024 // FIXME: Is the qualifier info correct?
6025 // FIXME: Is the DeclContext correct?
6026 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6027 Loc, Loc, DeclarationName(II),
6028 FD->getType(), FD->getTypeSourceInfo(),
6029 SC_None, false/*isInlineSpecified*/,
6031 false/*isConstexprSpecified*/);
6034 if (FD->getQualifier())
6035 NewFD->setQualifierInfo(FD->getQualifierLoc());
6037 // Fake up parameter variables; they are declared as if this were
6039 QualType FDTy = FD->getType();
6040 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6041 SmallVector<ParmVarDecl*, 16> Params;
6042 for (const auto &AI : FT->param_types()) {
6043 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6044 Param->setScopeInfo(0, Params.size());
6045 Params.push_back(Param);
6047 NewFD->setParams(Params);
6049 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6050 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6051 VD->getInnerLocStart(), VD->getLocation(), II,
6052 VD->getType(), VD->getTypeSourceInfo(),
6053 VD->getStorageClass());
6054 if (VD->getQualifier()) {
6055 VarDecl *NewVD = cast<VarDecl>(NewD);
6056 NewVD->setQualifierInfo(VD->getQualifierLoc());
6062 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6063 /// applied to it, possibly with an alias.
6064 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6065 if (W.getUsed()) return; // only do this once
6067 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6068 IdentifierInfo *NDId = ND->getIdentifier();
6069 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6070 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6072 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6073 WeakTopLevelDecl.push_back(NewD);
6074 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6075 // to insert Decl at TU scope, sorry.
6076 DeclContext *SavedContext = CurContext;
6077 CurContext = Context.getTranslationUnitDecl();
6078 NewD->setDeclContext(CurContext);
6079 NewD->setLexicalDeclContext(CurContext);
6080 PushOnScopeChains(NewD, S);
6081 CurContext = SavedContext;
6082 } else { // just add weak to existing
6083 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6087 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6088 // It's valid to "forward-declare" #pragma weak, in which case we
6090 LoadExternalWeakUndeclaredIdentifiers();
6091 if (!WeakUndeclaredIdentifiers.empty()) {
6092 NamedDecl *ND = nullptr;
6093 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6094 if (VD->isExternC())
6096 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6097 if (FD->isExternC())
6100 if (IdentifierInfo *Id = ND->getIdentifier()) {
6101 auto I = WeakUndeclaredIdentifiers.find(Id);
6102 if (I != WeakUndeclaredIdentifiers.end()) {
6103 WeakInfo W = I->second;
6104 DeclApplyPragmaWeak(S, ND, W);
6105 WeakUndeclaredIdentifiers[Id] = W;
6112 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6113 /// it, apply them to D. This is a bit tricky because PD can have attributes
6114 /// specified in many different places, and we need to find and apply them all.
6115 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6116 // Apply decl attributes from the DeclSpec if present.
6117 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6118 ProcessDeclAttributeList(S, D, Attrs);
6120 // Walk the declarator structure, applying decl attributes that were in a type
6121 // position to the decl itself. This handles cases like:
6122 // int *__attr__(x)** D;
6123 // when X is a decl attribute.
6124 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6125 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6126 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6128 // Finally, apply any attributes on the decl itself.
6129 if (const AttributeList *Attrs = PD.getAttributes())
6130 ProcessDeclAttributeList(S, D, Attrs);
6133 /// Is the given declaration allowed to use a forbidden type?
6134 /// If so, it'll still be annotated with an attribute that makes it
6135 /// illegal to actually use.
6136 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6137 const DelayedDiagnostic &diag,
6138 UnavailableAttr::ImplicitReason &reason) {
6139 // Private ivars are always okay. Unfortunately, people don't
6140 // always properly make their ivars private, even in system headers.
6141 // Plus we need to make fields okay, too.
6142 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6143 !isa<FunctionDecl>(decl))
6146 // Silently accept unsupported uses of __weak in both user and system
6147 // declarations when it's been disabled, for ease of integration with
6148 // -fno-objc-arc files. We do have to take some care against attempts
6149 // to define such things; for now, we've only done that for ivars
6151 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6152 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6153 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6154 reason = UnavailableAttr::IR_ForbiddenWeak;
6159 // Allow all sorts of things in system headers.
6160 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6161 // Currently, all the failures dealt with this way are due to ARC
6163 reason = UnavailableAttr::IR_ARCForbiddenType;
6170 /// Handle a delayed forbidden-type diagnostic.
6171 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6173 auto reason = UnavailableAttr::IR_None;
6174 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6175 assert(reason && "didn't set reason?");
6176 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6180 if (S.getLangOpts().ObjCAutoRefCount)
6181 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6182 // FIXME: we may want to suppress diagnostics for all
6183 // kind of forbidden type messages on unavailable functions.
6184 if (FD->hasAttr<UnavailableAttr>() &&
6185 diag.getForbiddenTypeDiagnostic() ==
6186 diag::err_arc_array_param_no_ownership) {
6187 diag.Triggered = true;
6192 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6193 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6194 diag.Triggered = true;
6197 static bool isDeclDeprecated(Decl *D) {
6199 if (D->isDeprecated())
6201 // A category implicitly has the availability of the interface.
6202 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
6203 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6204 return Interface->isDeprecated();
6205 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
6209 static bool isDeclUnavailable(Decl *D) {
6211 if (D->isUnavailable())
6213 // A category implicitly has the availability of the interface.
6214 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
6215 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6216 return Interface->isUnavailable();
6217 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
6221 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6223 // Check each AvailabilityAttr to find the one for this platform.
6224 for (const auto *A : D->attrs()) {
6225 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6226 // FIXME: this is copied from CheckAvailability. We should try to
6229 // Check if this is an App Extension "platform", and if so chop off
6230 // the suffix for matching with the actual platform.
6231 StringRef ActualPlatform = Avail->getPlatform()->getName();
6232 StringRef RealizedPlatform = ActualPlatform;
6233 if (Context.getLangOpts().AppExt) {
6234 size_t suffix = RealizedPlatform.rfind("_app_extension");
6235 if (suffix != StringRef::npos)
6236 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6239 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6241 // Match the platform name.
6242 if (RealizedPlatform == TargetPlatform)
6249 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K,
6250 Decl *Ctx, const NamedDecl *D,
6251 StringRef Message, SourceLocation Loc,
6252 const ObjCInterfaceDecl *UnknownObjCClass,
6253 const ObjCPropertyDecl *ObjCProperty,
6254 bool ObjCPropertyAccess) {
6255 // Diagnostics for deprecated or unavailable.
6256 unsigned diag, diag_message, diag_fwdclass_message;
6257 unsigned diag_available_here = diag::note_availability_specified_here;
6259 // Matches 'diag::note_property_attribute' options.
6260 unsigned property_note_select;
6262 // Matches diag::note_availability_specified_here.
6263 unsigned available_here_select_kind;
6265 // Don't warn if our current context is deprecated or unavailable.
6267 case Sema::AD_Deprecation:
6268 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx))
6270 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6271 : diag::warn_property_method_deprecated;
6272 diag_message = diag::warn_deprecated_message;
6273 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6274 property_note_select = /* deprecated */ 0;
6275 available_here_select_kind = /* deprecated */ 2;
6278 case Sema::AD_Unavailable:
6279 if (isDeclUnavailable(Ctx))
6281 diag = !ObjCPropertyAccess ? diag::err_unavailable
6282 : diag::err_property_method_unavailable;
6283 diag_message = diag::err_unavailable_message;
6284 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6285 property_note_select = /* unavailable */ 1;
6286 available_here_select_kind = /* unavailable */ 0;
6288 if (auto attr = D->getAttr<UnavailableAttr>()) {
6289 if (attr->isImplicit() && attr->getImplicitReason()) {
6290 // Most of these failures are due to extra restrictions in ARC;
6291 // reflect that in the primary diagnostic when applicable.
6292 auto flagARCError = [&] {
6293 if (S.getLangOpts().ObjCAutoRefCount &&
6294 S.getSourceManager().isInSystemHeader(D->getLocation()))
6295 diag = diag::err_unavailable_in_arc;
6298 switch (attr->getImplicitReason()) {
6299 case UnavailableAttr::IR_None: break;
6301 case UnavailableAttr::IR_ARCForbiddenType:
6303 diag_available_here = diag::note_arc_forbidden_type;
6306 case UnavailableAttr::IR_ForbiddenWeak:
6307 if (S.getLangOpts().ObjCWeakRuntime)
6308 diag_available_here = diag::note_arc_weak_disabled;
6310 diag_available_here = diag::note_arc_weak_no_runtime;
6313 case UnavailableAttr::IR_ARCForbiddenConversion:
6315 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6318 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6320 diag_available_here = diag::note_arc_init_returns_unrelated;
6323 case UnavailableAttr::IR_ARCFieldWithOwnership:
6325 diag_available_here = diag::note_arc_field_with_ownership;
6332 case Sema::AD_Partial:
6333 diag = diag::warn_partial_availability;
6334 diag_message = diag::warn_partial_message;
6335 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6336 property_note_select = /* partial */ 2;
6337 available_here_select_kind = /* partial */ 3;
6341 CharSourceRange UseRange;
6342 StringRef Replacement;
6343 if (K == Sema::AD_Deprecation) {
6344 if (auto attr = D->getAttr<DeprecatedAttr>())
6345 Replacement = attr->getReplacement();
6346 if (auto attr = getAttrForPlatform(S.Context, D))
6347 Replacement = attr->getReplacement();
6349 if (!Replacement.empty())
6351 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6354 if (!Message.empty()) {
6355 S.Diag(Loc, diag_message) << D << Message
6356 << (UseRange.isValid() ?
6357 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6359 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6360 << ObjCProperty->getDeclName() << property_note_select;
6361 } else if (!UnknownObjCClass) {
6362 S.Diag(Loc, diag) << D
6363 << (UseRange.isValid() ?
6364 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6366 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6367 << ObjCProperty->getDeclName() << property_note_select;
6369 S.Diag(Loc, diag_fwdclass_message) << D
6370 << (UseRange.isValid() ?
6371 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6372 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6375 // The declaration can have multiple availability attributes, we are looking
6377 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6378 if (A && A->isInherited()) {
6379 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6380 Redecl = Redecl->getPreviousDecl()) {
6381 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6383 if (AForRedecl && !AForRedecl->isInherited()) {
6384 // If D is a declaration with inherited attributes, the note should
6385 // point to the declaration with actual attributes.
6386 S.Diag(Redecl->getLocation(), diag_available_here) << D
6387 << available_here_select_kind;
6393 S.Diag(D->getLocation(), diag_available_here)
6394 << D << available_here_select_kind;
6396 if (K == Sema::AD_Partial)
6397 S.Diag(Loc, diag::note_partial_availability_silence) << D;
6400 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6402 assert(DD.Kind == DelayedDiagnostic::Deprecation ||
6403 DD.Kind == DelayedDiagnostic::Unavailable);
6404 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation
6405 ? Sema::AD_Deprecation
6406 : Sema::AD_Unavailable;
6407 DD.Triggered = true;
6408 DoEmitAvailabilityWarning(
6409 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc,
6410 DD.getUnknownObjCClass(), DD.getObjCProperty(), false);
6413 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
6414 assert(DelayedDiagnostics.getCurrentPool());
6415 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
6416 DelayedDiagnostics.popWithoutEmitting(state);
6418 // When delaying diagnostics to run in the context of a parsed
6419 // declaration, we only want to actually emit anything if parsing
6423 // We emit all the active diagnostics in this pool or any of its
6424 // parents. In general, we'll get one pool for the decl spec
6425 // and a child pool for each declarator; in a decl group like:
6426 // deprecated_typedef foo, *bar, baz();
6427 // only the declarator pops will be passed decls. This is correct;
6428 // we really do need to consider delayed diagnostics from the decl spec
6429 // for each of the different declarations.
6430 const DelayedDiagnosticPool *pool = &poppedPool;
6432 for (DelayedDiagnosticPool::pool_iterator
6433 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
6434 // This const_cast is a bit lame. Really, Triggered should be mutable.
6435 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
6439 switch (diag.Kind) {
6440 case DelayedDiagnostic::Deprecation:
6441 case DelayedDiagnostic::Unavailable:
6442 // Don't bother giving deprecation/unavailable diagnostics if
6443 // the decl is invalid.
6444 if (!decl->isInvalidDecl())
6445 handleDelayedAvailabilityCheck(*this, diag, decl);
6448 case DelayedDiagnostic::Access:
6449 HandleDelayedAccessCheck(diag, decl);
6452 case DelayedDiagnostic::ForbiddenType:
6453 handleDelayedForbiddenType(*this, diag, decl);
6457 } while ((pool = pool->getParent()));
6460 /// Given a set of delayed diagnostics, re-emit them as if they had
6461 /// been delayed in the current context instead of in the given pool.
6462 /// Essentially, this just moves them to the current pool.
6463 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
6464 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
6465 assert(curPool && "re-emitting in undelayed context not supported");
6466 curPool->steal(pool);
6469 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD,
6470 NamedDecl *D, StringRef Message,
6472 const ObjCInterfaceDecl *UnknownObjCClass,
6473 const ObjCPropertyDecl *ObjCProperty,
6474 bool ObjCPropertyAccess) {
6475 // Delay if we're currently parsing a declaration.
6476 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) {
6477 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
6478 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message,
6479 ObjCPropertyAccess));
6483 Decl *Ctx = cast<Decl>(getCurLexicalContext());
6484 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass,
6485 ObjCProperty, ObjCPropertyAccess);