1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements decl-related attribute processing.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/Mangle.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/MathExtras.h"
39 using namespace clang;
42 namespace AttributeLangSupport {
48 } // end namespace AttributeLangSupport
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 /// isFunctionOrMethod - Return true if the given decl has function
55 /// type (function or function-typed variable) or an Objective-C
57 static bool isFunctionOrMethod(const Decl *D) {
58 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
61 /// \brief Return true if the given decl has function type (function or
62 /// function-typed variable) or an Objective-C method or a block.
63 static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
67 /// Return true if the given decl has a declarator that should have
68 /// been processed by Sema::GetTypeForDeclarator.
69 static bool hasDeclarator(const Decl *D) {
70 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
71 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
75 /// hasFunctionProto - Return true if the given decl has a argument
76 /// information. This decl should have already passed
77 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
78 static bool hasFunctionProto(const Decl *D) {
79 if (const FunctionType *FnTy = D->getFunctionType())
80 return isa<FunctionProtoType>(FnTy);
81 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
84 /// getFunctionOrMethodNumParams - Return number of function or method
85 /// parameters. It is an error to call this on a K&R function (use
86 /// hasFunctionProto first).
87 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
88 if (const FunctionType *FnTy = D->getFunctionType())
89 return cast<FunctionProtoType>(FnTy)->getNumParams();
90 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
91 return BD->getNumParams();
92 return cast<ObjCMethodDecl>(D)->param_size();
95 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
96 if (const FunctionType *FnTy = D->getFunctionType())
97 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
98 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
99 return BD->getParamDecl(Idx)->getType();
101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
104 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
105 if (const auto *FD = dyn_cast<FunctionDecl>(D))
106 return FD->getParamDecl(Idx)->getSourceRange();
107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
108 return MD->parameters()[Idx]->getSourceRange();
109 if (const auto *BD = dyn_cast<BlockDecl>(D))
110 return BD->getParamDecl(Idx)->getSourceRange();
111 return SourceRange();
114 static QualType getFunctionOrMethodResultType(const Decl *D) {
115 if (const FunctionType *FnTy = D->getFunctionType())
116 return cast<FunctionType>(FnTy)->getReturnType();
117 return cast<ObjCMethodDecl>(D)->getReturnType();
120 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
121 if (const auto *FD = dyn_cast<FunctionDecl>(D))
122 return FD->getReturnTypeSourceRange();
123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
124 return MD->getReturnTypeSourceRange();
125 return SourceRange();
128 static bool isFunctionOrMethodVariadic(const Decl *D) {
129 if (const FunctionType *FnTy = D->getFunctionType()) {
130 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
131 return proto->isVariadic();
133 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
134 return BD->isVariadic();
136 return cast<ObjCMethodDecl>(D)->isVariadic();
139 static bool isInstanceMethod(const Decl *D) {
140 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
141 return MethodDecl->isInstance();
145 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
146 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
150 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
154 IdentifierInfo* ClsName = Cls->getIdentifier();
156 // FIXME: Should we walk the chain of classes?
157 return ClsName == &Ctx.Idents.get("NSString") ||
158 ClsName == &Ctx.Idents.get("NSMutableString");
161 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
162 const PointerType *PT = T->getAs<PointerType>();
166 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
170 const RecordDecl *RD = RT->getDecl();
171 if (RD->getTagKind() != TTK_Struct)
174 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
177 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
178 // FIXME: Include the type in the argument list.
179 return Attr.getNumArgs() + Attr.hasParsedType();
182 template <typename Compare>
183 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
184 unsigned Num, unsigned Diag,
186 if (Comp(getNumAttributeArgs(Attr), Num)) {
187 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
194 /// \brief Check if the attribute has exactly as many args as Num. May
196 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
198 return checkAttributeNumArgsImpl(S, Attr, Num,
199 diag::err_attribute_wrong_number_arguments,
200 std::not_equal_to<unsigned>());
203 /// \brief Check if the attribute has at least as many args as Num. May
205 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
207 return checkAttributeNumArgsImpl(S, Attr, Num,
208 diag::err_attribute_too_few_arguments,
209 std::less<unsigned>());
212 /// \brief Check if the attribute has at most as many args as Num. May
214 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
216 return checkAttributeNumArgsImpl(S, Attr, Num,
217 diag::err_attribute_too_many_arguments,
218 std::greater<unsigned>());
221 /// \brief If Expr is a valid integer constant, get the value of the integer
222 /// expression and return success or failure. May output an error.
223 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
224 const Expr *Expr, uint32_t &Val,
225 unsigned Idx = UINT_MAX) {
227 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
228 !Expr->isIntegerConstantExpr(I, S.Context)) {
230 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
231 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
232 << Expr->getSourceRange();
234 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
235 << Attr.getName() << AANT_ArgumentIntegerConstant
236 << Expr->getSourceRange();
241 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
242 << I.toString(10, false) << 32 << /* Unsigned */ 1;
246 Val = (uint32_t)I.getZExtValue();
250 /// \brief Wrapper around checkUInt32Argument, with an extra check to be sure
251 /// that the result will fit into a regular (signed) int. All args have the same
252 /// purpose as they do in checkUInt32Argument.
253 static bool checkPositiveIntArgument(Sema &S, const AttributeList &Attr,
254 const Expr *Expr, int &Val,
255 unsigned Idx = UINT_MAX) {
257 if (!checkUInt32Argument(S, Attr, Expr, UVal, Idx))
260 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
261 llvm::APSInt I(32); // for toString
263 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
264 << I.toString(10, false) << 32 << /* Unsigned */ 0;
272 /// \brief Diagnose mutually exclusive attributes when present on a given
273 /// declaration. Returns true if diagnosed.
274 template <typename AttrTy>
275 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
276 IdentifierInfo *Ident) {
277 if (AttrTy *A = D->getAttr<AttrTy>()) {
278 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
280 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
286 /// \brief Check if IdxExpr is a valid parameter index for a function or
287 /// instance method D. May output an error.
289 /// \returns true if IdxExpr is a valid index.
290 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
291 const AttributeList &Attr,
295 assert(isFunctionOrMethodOrBlock(D));
297 // In C++ the implicit 'this' function parameter also counts.
298 // Parameters are counted from one.
299 bool HP = hasFunctionProto(D);
300 bool HasImplicitThisParam = isInstanceMethod(D);
301 bool IV = HP && isFunctionOrMethodVariadic(D);
303 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
306 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
307 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
308 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
309 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
310 << IdxExpr->getSourceRange();
314 Idx = IdxInt.getLimitedValue();
315 if (Idx < 1 || (!IV && Idx > NumParams)) {
316 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
317 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
320 Idx--; // Convert to zero-based.
321 if (HasImplicitThisParam) {
323 S.Diag(Attr.getLoc(),
324 diag::err_attribute_invalid_implicit_this_argument)
325 << Attr.getName() << IdxExpr->getSourceRange();
334 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
335 /// If not emit an error and return false. If the argument is an identifier it
336 /// will emit an error with a fixit hint and treat it as if it was a string
338 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
339 unsigned ArgNum, StringRef &Str,
340 SourceLocation *ArgLocation) {
341 // Look for identifiers. If we have one emit a hint to fix it to a literal.
342 if (Attr.isArgIdent(ArgNum)) {
343 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
344 Diag(Loc->Loc, diag::err_attribute_argument_type)
345 << Attr.getName() << AANT_ArgumentString
346 << FixItHint::CreateInsertion(Loc->Loc, "\"")
347 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
348 Str = Loc->Ident->getName();
350 *ArgLocation = Loc->Loc;
354 // Now check for an actual string literal.
355 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
356 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
358 *ArgLocation = ArgExpr->getLocStart();
360 if (!Literal || !Literal->isAscii()) {
361 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
362 << Attr.getName() << AANT_ArgumentString;
366 Str = Literal->getString();
370 /// \brief Applies the given attribute to the Decl without performing any
371 /// additional semantic checking.
372 template <typename AttrType>
373 static void handleSimpleAttribute(Sema &S, Decl *D,
374 const AttributeList &Attr) {
375 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
376 Attr.getAttributeSpellingListIndex()));
379 template <typename AttrType>
380 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
381 const AttributeList &Attr) {
382 handleSimpleAttribute<AttrType>(S, D, Attr);
385 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't
386 /// already have one of the given incompatible attributes.
387 template <typename AttrType, typename IncompatibleAttrType,
388 typename... IncompatibleAttrTypes>
389 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
390 const AttributeList &Attr) {
391 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(),
394 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
398 /// \brief Check if the passed-in expression is of type int or bool.
399 static bool isIntOrBool(Expr *Exp) {
400 QualType QT = Exp->getType();
401 return QT->isBooleanType() || QT->isIntegerType();
405 // Check to see if the type is a smart pointer of some kind. We assume
406 // it's a smart pointer if it defines both operator-> and operator*.
407 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
408 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
409 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
413 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
414 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
421 /// \brief Check if passed in Decl is a pointer type.
422 /// Note that this function may produce an error message.
423 /// \return true if the Decl is a pointer type; false otherwise
424 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
425 const AttributeList &Attr) {
426 const ValueDecl *vd = cast<ValueDecl>(D);
427 QualType QT = vd->getType();
428 if (QT->isAnyPointerType())
431 if (const RecordType *RT = QT->getAs<RecordType>()) {
432 // If it's an incomplete type, it could be a smart pointer; skip it.
433 // (We don't want to force template instantiation if we can avoid it,
434 // since that would alter the order in which templates are instantiated.)
435 if (RT->isIncompleteType())
438 if (threadSafetyCheckIsSmartPointer(S, RT))
442 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
443 << Attr.getName() << QT;
447 /// \brief Checks that the passed in QualType either is of RecordType or points
448 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
449 static const RecordType *getRecordType(QualType QT) {
450 if (const RecordType *RT = QT->getAs<RecordType>())
453 // Now check if we point to record type.
454 if (const PointerType *PT = QT->getAs<PointerType>())
455 return PT->getPointeeType()->getAs<RecordType>();
460 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
461 const RecordType *RT = getRecordType(Ty);
466 // Don't check for the capability if the class hasn't been defined yet.
467 if (RT->isIncompleteType())
470 // Allow smart pointers to be used as capability objects.
471 // FIXME -- Check the type that the smart pointer points to.
472 if (threadSafetyCheckIsSmartPointer(S, RT))
475 // Check if the record itself has a capability.
476 RecordDecl *RD = RT->getDecl();
477 if (RD->hasAttr<CapabilityAttr>())
480 // Else check if any base classes have a capability.
481 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
482 CXXBasePaths BPaths(false, false);
483 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
484 const auto *Type = BS->getType()->getAs<RecordType>();
485 return Type->getDecl()->hasAttr<CapabilityAttr>();
492 static bool checkTypedefTypeForCapability(QualType Ty) {
493 const auto *TD = Ty->getAs<TypedefType>();
497 TypedefNameDecl *TN = TD->getDecl();
501 return TN->hasAttr<CapabilityAttr>();
504 static bool typeHasCapability(Sema &S, QualType Ty) {
505 if (checkTypedefTypeForCapability(Ty))
508 if (checkRecordTypeForCapability(S, Ty))
514 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
515 // Capability expressions are simple expressions involving the boolean logic
516 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
517 // a DeclRefExpr is found, its type should be checked to determine whether it
518 // is a capability or not.
520 if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
521 return typeHasCapability(S, E->getType());
522 else if (const auto *E = dyn_cast<CastExpr>(Ex))
523 return isCapabilityExpr(S, E->getSubExpr());
524 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
525 return isCapabilityExpr(S, E->getSubExpr());
526 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
527 if (E->getOpcode() == UO_LNot)
528 return isCapabilityExpr(S, E->getSubExpr());
530 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
531 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
532 return isCapabilityExpr(S, E->getLHS()) &&
533 isCapabilityExpr(S, E->getRHS());
540 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
541 /// a capability object.
542 /// \param Sidx The attribute argument index to start checking with.
543 /// \param ParamIdxOk Whether an argument can be indexing into a function
545 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
546 const AttributeList &Attr,
547 SmallVectorImpl<Expr *> &Args,
549 bool ParamIdxOk = false) {
550 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
551 Expr *ArgExp = Attr.getArgAsExpr(Idx);
553 if (ArgExp->isTypeDependent()) {
554 // FIXME -- need to check this again on template instantiation
555 Args.push_back(ArgExp);
559 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
560 if (StrLit->getLength() == 0 ||
561 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
562 // Pass empty strings to the analyzer without warnings.
563 // Treat "*" as the universal lock.
564 Args.push_back(ArgExp);
568 // We allow constant strings to be used as a placeholder for expressions
569 // that are not valid C++ syntax, but warn that they are ignored.
570 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
572 Args.push_back(ArgExp);
576 QualType ArgTy = ArgExp->getType();
578 // A pointer to member expression of the form &MyClass::mu is treated
579 // specially -- we need to look at the type of the member.
580 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
581 if (UOp->getOpcode() == UO_AddrOf)
582 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
583 if (DRE->getDecl()->isCXXInstanceMember())
584 ArgTy = DRE->getDecl()->getType();
586 // First see if we can just cast to record type, or pointer to record type.
587 const RecordType *RT = getRecordType(ArgTy);
589 // Now check if we index into a record type function param.
590 if(!RT && ParamIdxOk) {
591 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
592 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
594 unsigned int NumParams = FD->getNumParams();
595 llvm::APInt ArgValue = IL->getValue();
596 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
597 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
598 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
599 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
600 << Attr.getName() << Idx + 1 << NumParams;
603 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
607 // If the type does not have a capability, see if the components of the
608 // expression have capabilities. This allows for writing C code where the
609 // capability may be on the type, and the expression is a capability
610 // boolean logic expression. Eg) requires_capability(A || B && !C)
611 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
612 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
613 << Attr.getName() << ArgTy;
615 Args.push_back(ArgExp);
619 //===----------------------------------------------------------------------===//
620 // Attribute Implementations
621 //===----------------------------------------------------------------------===//
623 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
624 const AttributeList &Attr) {
625 if (!threadSafetyCheckIsPointer(S, D, Attr))
628 D->addAttr(::new (S.Context)
629 PtGuardedVarAttr(Attr.getRange(), S.Context,
630 Attr.getAttributeSpellingListIndex()));
633 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
634 const AttributeList &Attr,
636 SmallVector<Expr*, 1> Args;
637 // check that all arguments are lockable objects
638 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
639 unsigned Size = Args.size();
648 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
650 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
653 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
654 Attr.getAttributeSpellingListIndex()));
657 static void handlePtGuardedByAttr(Sema &S, Decl *D,
658 const AttributeList &Attr) {
660 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
663 if (!threadSafetyCheckIsPointer(S, D, Attr))
666 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
668 Attr.getAttributeSpellingListIndex()));
671 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
672 const AttributeList &Attr,
673 SmallVectorImpl<Expr *> &Args) {
674 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
677 // Check that this attribute only applies to lockable types.
678 QualType QT = cast<ValueDecl>(D)->getType();
679 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
680 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
685 // Check that all arguments are lockable objects.
686 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
693 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
694 const AttributeList &Attr) {
695 SmallVector<Expr*, 1> Args;
696 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
699 Expr **StartArg = &Args[0];
700 D->addAttr(::new (S.Context)
701 AcquiredAfterAttr(Attr.getRange(), S.Context,
702 StartArg, Args.size(),
703 Attr.getAttributeSpellingListIndex()));
706 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
707 const AttributeList &Attr) {
708 SmallVector<Expr*, 1> Args;
709 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
712 Expr **StartArg = &Args[0];
713 D->addAttr(::new (S.Context)
714 AcquiredBeforeAttr(Attr.getRange(), S.Context,
715 StartArg, Args.size(),
716 Attr.getAttributeSpellingListIndex()));
719 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
720 const AttributeList &Attr,
721 SmallVectorImpl<Expr *> &Args) {
722 // zero or more arguments ok
723 // check that all arguments are lockable objects
724 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
729 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
730 const AttributeList &Attr) {
731 SmallVector<Expr*, 1> Args;
732 if (!checkLockFunAttrCommon(S, D, Attr, Args))
735 unsigned Size = Args.size();
736 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
737 D->addAttr(::new (S.Context)
738 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
739 Attr.getAttributeSpellingListIndex()));
742 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
743 const AttributeList &Attr) {
744 SmallVector<Expr*, 1> Args;
745 if (!checkLockFunAttrCommon(S, D, Attr, Args))
748 unsigned Size = Args.size();
749 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
750 D->addAttr(::new (S.Context)
751 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
753 Attr.getAttributeSpellingListIndex()));
756 /// \brief Checks to be sure that the given parameter number is inbounds, and is
757 /// an some integral type. Will emit appropriate diagnostics if this returns
760 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used
761 /// to actually retrieve the argument, so it's base-0.
762 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
763 const AttributeList &Attr,
764 unsigned FuncParamNo, unsigned AttrArgNo) {
765 assert(Attr.isArgExpr(AttrArgNo) && "Expected expression argument");
767 if (!checkFunctionOrMethodParameterIndex(S, FD, Attr, FuncParamNo,
768 Attr.getArgAsExpr(AttrArgNo), Idx))
771 const ParmVarDecl *Param = FD->getParamDecl(Idx);
772 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
773 SourceLocation SrcLoc = Attr.getArgAsExpr(AttrArgNo)->getLocStart();
774 S.Diag(SrcLoc, diag::err_attribute_integers_only)
775 << Attr.getName() << Param->getSourceRange();
781 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
782 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
783 !checkAttributeAtMostNumArgs(S, Attr, 2))
786 const auto *FD = cast<FunctionDecl>(D);
787 if (!FD->getReturnType()->isPointerType()) {
788 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
793 const Expr *SizeExpr = Attr.getArgAsExpr(0);
795 // Paramater indices are 1-indexed, hence Index=1
796 if (!checkPositiveIntArgument(S, Attr, SizeExpr, SizeArgNo, /*Index=*/1))
799 if (!checkParamIsIntegerType(S, FD, Attr, SizeArgNo, /*AttrArgNo=*/0))
802 // Args are 1-indexed, so 0 implies that the arg was not present
804 if (Attr.getNumArgs() == 2) {
805 const Expr *NumberExpr = Attr.getArgAsExpr(1);
806 // Paramater indices are 1-based, hence Index=2
807 if (!checkPositiveIntArgument(S, Attr, NumberExpr, NumberArgNo,
811 if (!checkParamIsIntegerType(S, FD, Attr, NumberArgNo, /*AttrArgNo=*/1))
815 D->addAttr(::new (S.Context) AllocSizeAttr(
816 Attr.getRange(), S.Context, SizeArgNo, NumberArgNo,
817 Attr.getAttributeSpellingListIndex()));
820 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
821 const AttributeList &Attr,
822 SmallVectorImpl<Expr *> &Args) {
823 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
826 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
827 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
828 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
832 // check that all arguments are lockable objects
833 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
838 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
839 const AttributeList &Attr) {
840 SmallVector<Expr*, 2> Args;
841 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
844 D->addAttr(::new (S.Context)
845 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
846 Attr.getArgAsExpr(0),
847 Args.data(), Args.size(),
848 Attr.getAttributeSpellingListIndex()));
851 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
852 const AttributeList &Attr) {
853 SmallVector<Expr*, 2> Args;
854 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
857 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
858 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
859 Args.size(), Attr.getAttributeSpellingListIndex()));
862 static void handleLockReturnedAttr(Sema &S, Decl *D,
863 const AttributeList &Attr) {
864 // check that the argument is lockable object
865 SmallVector<Expr*, 1> Args;
866 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
867 unsigned Size = Args.size();
871 D->addAttr(::new (S.Context)
872 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
873 Attr.getAttributeSpellingListIndex()));
876 static void handleLocksExcludedAttr(Sema &S, Decl *D,
877 const AttributeList &Attr) {
878 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
881 // check that all arguments are lockable objects
882 SmallVector<Expr*, 1> Args;
883 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
884 unsigned Size = Args.size();
887 Expr **StartArg = &Args[0];
889 D->addAttr(::new (S.Context)
890 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
891 Attr.getAttributeSpellingListIndex()));
894 static bool checkFunctionConditionAttr(Sema &S, Decl *D,
895 const AttributeList &Attr,
896 Expr *&Cond, StringRef &Msg) {
897 Cond = Attr.getArgAsExpr(0);
898 if (!Cond->isTypeDependent()) {
899 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
900 if (Converted.isInvalid())
902 Cond = Converted.get();
905 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
909 Msg = "<no message provided>";
911 SmallVector<PartialDiagnosticAt, 8> Diags;
912 if (!Cond->isValueDependent() &&
913 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
915 S.Diag(Attr.getLoc(), diag::err_attr_cond_never_constant_expr)
917 for (const PartialDiagnosticAt &PDiag : Diags)
918 S.Diag(PDiag.first, PDiag.second);
924 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
925 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if);
929 if (checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
930 D->addAttr(::new (S.Context)
931 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
932 Attr.getAttributeSpellingListIndex()));
936 /// Determines if a given Expr references any of the given function's
937 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
938 class ArgumentDependenceChecker
939 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
941 const CXXRecordDecl *ClassType;
943 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
947 ArgumentDependenceChecker(const FunctionDecl *FD) {
949 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
950 ClassType = MD->getParent();
954 Parms.insert(FD->param_begin(), FD->param_end());
957 bool referencesArgs(Expr *E) {
963 bool VisitCXXThisExpr(CXXThisExpr *E) {
964 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
965 "`this` doesn't refer to the enclosing class?");
970 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
971 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
972 if (Parms.count(PVD)) {
981 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
982 S.Diag(Attr.getLoc(), diag::ext_clang_diagnose_if);
986 if (!checkFunctionConditionAttr(S, D, Attr, Cond, Msg))
989 StringRef DiagTypeStr;
990 if (!S.checkStringLiteralArgumentAttr(Attr, 2, DiagTypeStr))
993 DiagnoseIfAttr::DiagnosticType DiagType;
994 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
995 S.Diag(Attr.getArgAsExpr(2)->getLocStart(),
996 diag::err_diagnose_if_invalid_diagnostic_type);
1000 auto *FD = cast<FunctionDecl>(D);
1001 bool ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1002 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1003 Attr.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, FD,
1004 Attr.getAttributeSpellingListIndex()));
1007 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
1008 const AttributeList &Attr) {
1009 if (D->hasAttr<PassObjectSizeAttr>()) {
1010 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1015 Expr *E = Attr.getArgAsExpr(0);
1017 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
1020 // pass_object_size's argument is passed in as the second argument of
1021 // __builtin_object_size. So, it has the same constraints as that second
1022 // argument; namely, it must be in the range [0, 3].
1024 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1025 << Attr.getName() << 0 << 3 << E->getSourceRange();
1029 // pass_object_size is only supported on constant pointer parameters; as a
1030 // kindness to users, we allow the parameter to be non-const for declarations.
1031 // At this point, we have no clue if `D` belongs to a function declaration or
1032 // definition, so we defer the constness check until later.
1033 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1034 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1035 << Attr.getName() << 1;
1039 D->addAttr(::new (S.Context)
1040 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
1041 Attr.getAttributeSpellingListIndex()));
1044 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1045 ConsumableAttr::ConsumedState DefaultState;
1047 if (Attr.isArgIdent(0)) {
1048 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1049 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1051 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1052 << Attr.getName() << IL->Ident;
1056 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1057 << Attr.getName() << AANT_ArgumentIdentifier;
1061 D->addAttr(::new (S.Context)
1062 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
1063 Attr.getAttributeSpellingListIndex()));
1066 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1067 const AttributeList &Attr) {
1068 ASTContext &CurrContext = S.getASTContext();
1069 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1071 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1072 if (!RD->hasAttr<ConsumableAttr>()) {
1073 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1074 RD->getNameAsString();
1083 static void handleCallableWhenAttr(Sema &S, Decl *D,
1084 const AttributeList &Attr) {
1085 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1088 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1091 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1092 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1093 CallableWhenAttr::ConsumedState CallableState;
1095 StringRef StateString;
1097 if (Attr.isArgIdent(ArgIndex)) {
1098 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
1099 StateString = Ident->Ident->getName();
1102 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1106 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1108 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1109 << Attr.getName() << StateString;
1113 States.push_back(CallableState);
1116 D->addAttr(::new (S.Context)
1117 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1118 States.size(), Attr.getAttributeSpellingListIndex()));
1121 static void handleParamTypestateAttr(Sema &S, Decl *D,
1122 const AttributeList &Attr) {
1123 ParamTypestateAttr::ConsumedState ParamState;
1125 if (Attr.isArgIdent(0)) {
1126 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1127 StringRef StateString = Ident->Ident->getName();
1129 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1131 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1132 << Attr.getName() << StateString;
1136 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1137 Attr.getName() << AANT_ArgumentIdentifier;
1141 // FIXME: This check is currently being done in the analysis. It can be
1142 // enabled here only after the parser propagates attributes at
1143 // template specialization definition, not declaration.
1144 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1145 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1147 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1148 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1149 // ReturnType.getAsString();
1153 D->addAttr(::new (S.Context)
1154 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1155 Attr.getAttributeSpellingListIndex()));
1158 static void handleReturnTypestateAttr(Sema &S, Decl *D,
1159 const AttributeList &Attr) {
1160 ReturnTypestateAttr::ConsumedState ReturnState;
1162 if (Attr.isArgIdent(0)) {
1163 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1164 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1166 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1167 << Attr.getName() << IL->Ident;
1171 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1172 Attr.getName() << AANT_ArgumentIdentifier;
1176 // FIXME: This check is currently being done in the analysis. It can be
1177 // enabled here only after the parser propagates attributes at
1178 // template specialization definition, not declaration.
1179 //QualType ReturnType;
1181 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1182 // ReturnType = Param->getType();
1184 //} else if (const CXXConstructorDecl *Constructor =
1185 // dyn_cast<CXXConstructorDecl>(D)) {
1186 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1190 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1193 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1195 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1196 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1197 // ReturnType.getAsString();
1201 D->addAttr(::new (S.Context)
1202 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1203 Attr.getAttributeSpellingListIndex()));
1206 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1207 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1210 SetTypestateAttr::ConsumedState NewState;
1211 if (Attr.isArgIdent(0)) {
1212 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1213 StringRef Param = Ident->Ident->getName();
1214 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1215 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1216 << Attr.getName() << Param;
1220 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1221 Attr.getName() << AANT_ArgumentIdentifier;
1225 D->addAttr(::new (S.Context)
1226 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1227 Attr.getAttributeSpellingListIndex()));
1230 static void handleTestTypestateAttr(Sema &S, Decl *D,
1231 const AttributeList &Attr) {
1232 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1235 TestTypestateAttr::ConsumedState TestState;
1236 if (Attr.isArgIdent(0)) {
1237 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1238 StringRef Param = Ident->Ident->getName();
1239 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1240 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1241 << Attr.getName() << Param;
1245 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1246 Attr.getName() << AANT_ArgumentIdentifier;
1250 D->addAttr(::new (S.Context)
1251 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1252 Attr.getAttributeSpellingListIndex()));
1255 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1256 const AttributeList &Attr) {
1257 // Remember this typedef decl, we will need it later for diagnostics.
1258 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1261 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1262 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1263 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
1264 Attr.getAttributeSpellingListIndex()));
1265 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1266 // Report warning about changed offset in the newer compiler versions.
1267 if (!FD->getType()->isDependentType() &&
1268 !FD->getType()->isIncompleteType() && FD->isBitField() &&
1269 S.Context.getTypeAlign(FD->getType()) <= 8)
1270 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
1272 FD->addAttr(::new (S.Context) PackedAttr(
1273 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1275 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1278 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1279 // The IBOutlet/IBOutletCollection attributes only apply to instance
1280 // variables or properties of Objective-C classes. The outlet must also
1281 // have an object reference type.
1282 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1283 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1284 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1285 << Attr.getName() << VD->getType() << 0;
1289 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1290 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1291 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1292 << Attr.getName() << PD->getType() << 1;
1297 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1304 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1305 if (!checkIBOutletCommon(S, D, Attr))
1308 D->addAttr(::new (S.Context)
1309 IBOutletAttr(Attr.getRange(), S.Context,
1310 Attr.getAttributeSpellingListIndex()));
1313 static void handleIBOutletCollection(Sema &S, Decl *D,
1314 const AttributeList &Attr) {
1316 // The iboutletcollection attribute can have zero or one arguments.
1317 if (Attr.getNumArgs() > 1) {
1318 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1319 << Attr.getName() << 1;
1323 if (!checkIBOutletCommon(S, D, Attr))
1328 if (Attr.hasParsedType())
1329 PT = Attr.getTypeArg();
1331 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1332 S.getScopeForContext(D->getDeclContext()->getParent()));
1334 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1339 TypeSourceInfo *QTLoc = nullptr;
1340 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1342 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1344 // Diagnose use of non-object type in iboutletcollection attribute.
1345 // FIXME. Gnu attribute extension ignores use of builtin types in
1346 // attributes. So, __attribute__((iboutletcollection(char))) will be
1347 // treated as __attribute__((iboutletcollection())).
1348 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1349 S.Diag(Attr.getLoc(),
1350 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1351 : diag::err_iboutletcollection_type) << QT;
1355 D->addAttr(::new (S.Context)
1356 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1357 Attr.getAttributeSpellingListIndex()));
1360 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1362 if (T->isReferenceType())
1365 T = T.getNonReferenceType();
1368 // The nonnull attribute, and other similar attributes, can be applied to a
1369 // transparent union that contains a pointer type.
1370 if (const RecordType *UT = T->getAsUnionType()) {
1371 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1372 RecordDecl *UD = UT->getDecl();
1373 for (const auto *I : UD->fields()) {
1374 QualType QT = I->getType();
1375 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1381 return T->isAnyPointerType() || T->isBlockPointerType();
1384 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
1385 SourceRange AttrParmRange,
1386 SourceRange TypeRange,
1387 bool isReturnValue = false) {
1388 if (!S.isValidPointerAttrType(T)) {
1390 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1391 << Attr.getName() << AttrParmRange << TypeRange;
1393 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
1394 << Attr.getName() << AttrParmRange << TypeRange << 0;
1400 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1401 SmallVector<unsigned, 8> NonNullArgs;
1402 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
1403 Expr *Ex = Attr.getArgAsExpr(I);
1405 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
1408 // Is the function argument a pointer type?
1409 if (Idx < getFunctionOrMethodNumParams(D) &&
1410 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
1411 Ex->getSourceRange(),
1412 getFunctionOrMethodParamRange(D, Idx)))
1415 NonNullArgs.push_back(Idx);
1418 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1419 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1420 // check if the attribute came from a macro expansion or a template
1422 if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
1423 S.ActiveTemplateInstantiations.empty()) {
1424 bool AnyPointers = isFunctionOrMethodVariadic(D);
1425 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1426 I != E && !AnyPointers; ++I) {
1427 QualType T = getFunctionOrMethodParamType(D, I);
1428 if (T->isDependentType() || S.isValidPointerAttrType(T))
1433 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1436 unsigned *Start = NonNullArgs.data();
1437 unsigned Size = NonNullArgs.size();
1438 llvm::array_pod_sort(Start, Start + Size);
1439 D->addAttr(::new (S.Context)
1440 NonNullAttr(Attr.getRange(), S.Context, Start, Size,
1441 Attr.getAttributeSpellingListIndex()));
1444 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1445 const AttributeList &Attr) {
1446 if (Attr.getNumArgs() > 0) {
1447 if (D->getFunctionType()) {
1448 handleNonNullAttr(S, D, Attr);
1450 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1451 << D->getSourceRange();
1456 // Is the argument a pointer type?
1457 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
1458 D->getSourceRange()))
1461 D->addAttr(::new (S.Context)
1462 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
1463 Attr.getAttributeSpellingListIndex()));
1466 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
1467 const AttributeList &Attr) {
1468 QualType ResultType = getFunctionOrMethodResultType(D);
1469 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1470 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
1471 /* isReturnValue */ true))
1474 D->addAttr(::new (S.Context)
1475 ReturnsNonNullAttr(Attr.getRange(), S.Context,
1476 Attr.getAttributeSpellingListIndex()));
1479 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
1480 const AttributeList &Attr) {
1481 Expr *E = Attr.getArgAsExpr(0),
1482 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
1483 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
1484 Attr.getAttributeSpellingListIndex());
1487 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1488 Expr *OE, unsigned SpellingListIndex) {
1489 QualType ResultType = getFunctionOrMethodResultType(D);
1490 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1492 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1493 SourceLocation AttrLoc = AttrRange.getBegin();
1495 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1496 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1497 << &TmpAttr << AttrRange << SR;
1501 if (!E->isValueDependent()) {
1503 if (!E->isIntegerConstantExpr(I, Context)) {
1505 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1506 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1507 << E->getSourceRange();
1509 Diag(AttrLoc, diag::err_attribute_argument_type)
1510 << &TmpAttr << AANT_ArgumentIntegerConstant
1511 << E->getSourceRange();
1515 if (!I.isPowerOf2()) {
1516 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1517 << E->getSourceRange();
1523 if (!OE->isValueDependent()) {
1525 if (!OE->isIntegerConstantExpr(I, Context)) {
1526 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1527 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1528 << OE->getSourceRange();
1534 D->addAttr(::new (Context)
1535 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1538 /// Normalize the attribute, __foo__ becomes foo.
1539 /// Returns true if normalization was applied.
1540 static bool normalizeName(StringRef &AttrName) {
1541 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1542 AttrName.endswith("__")) {
1543 AttrName = AttrName.drop_front(2).drop_back(2);
1549 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1550 // This attribute must be applied to a function declaration. The first
1551 // argument to the attribute must be an identifier, the name of the resource,
1552 // for example: malloc. The following arguments must be argument indexes, the
1553 // arguments must be of integer type for Returns, otherwise of pointer type.
1554 // The difference between Holds and Takes is that a pointer may still be used
1555 // after being held. free() should be __attribute((ownership_takes)), whereas
1556 // a list append function may well be __attribute((ownership_holds)).
1558 if (!AL.isArgIdent(0)) {
1559 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1560 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1564 // Figure out our Kind.
1565 OwnershipAttr::OwnershipKind K =
1566 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1567 AL.getAttributeSpellingListIndex()).getOwnKind();
1571 case OwnershipAttr::Takes:
1572 case OwnershipAttr::Holds:
1573 if (AL.getNumArgs() < 2) {
1574 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1575 << AL.getName() << 2;
1579 case OwnershipAttr::Returns:
1580 if (AL.getNumArgs() > 2) {
1581 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1582 << AL.getName() << 1;
1588 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1590 StringRef ModuleName = Module->getName();
1591 if (normalizeName(ModuleName)) {
1592 Module = &S.PP.getIdentifierTable().get(ModuleName);
1595 SmallVector<unsigned, 8> OwnershipArgs;
1596 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1597 Expr *Ex = AL.getArgAsExpr(i);
1599 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1602 // Is the function argument a pointer type?
1603 QualType T = getFunctionOrMethodParamType(D, Idx);
1604 int Err = -1; // No error
1606 case OwnershipAttr::Takes:
1607 case OwnershipAttr::Holds:
1608 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1611 case OwnershipAttr::Returns:
1612 if (!T->isIntegerType())
1617 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1618 << Ex->getSourceRange();
1622 // Check we don't have a conflict with another ownership attribute.
1623 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1624 // Cannot have two ownership attributes of different kinds for the same
1626 if (I->getOwnKind() != K && I->args_end() !=
1627 std::find(I->args_begin(), I->args_end(), Idx)) {
1628 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1629 << AL.getName() << I;
1631 } else if (K == OwnershipAttr::Returns &&
1632 I->getOwnKind() == OwnershipAttr::Returns) {
1633 // A returns attribute conflicts with any other returns attribute using
1634 // a different index. Note, diagnostic reporting is 1-based, but stored
1635 // argument indexes are 0-based.
1636 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1637 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1638 << *(I->args_begin()) + 1;
1640 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1641 << (unsigned)Idx + 1 << Ex->getSourceRange();
1646 OwnershipArgs.push_back(Idx);
1649 unsigned* start = OwnershipArgs.data();
1650 unsigned size = OwnershipArgs.size();
1651 llvm::array_pod_sort(start, start + size);
1653 D->addAttr(::new (S.Context)
1654 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
1655 AL.getAttributeSpellingListIndex()));
1658 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1659 // Check the attribute arguments.
1660 if (Attr.getNumArgs() > 1) {
1661 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1662 << Attr.getName() << 1;
1666 NamedDecl *nd = cast<NamedDecl>(D);
1670 // static int a __attribute__((weakref ("v2")));
1671 // static int b() __attribute__((weakref ("f3")));
1673 // and ignores the attributes of
1675 // static int a __attribute__((weakref ("v2")));
1678 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1679 if (!Ctx->isFileContext()) {
1680 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
1685 // The GCC manual says
1687 // At present, a declaration to which `weakref' is attached can only
1692 // Without a TARGET,
1693 // given as an argument to `weakref' or to `alias', `weakref' is
1694 // equivalent to `weak'.
1696 // gcc 4.4.1 will accept
1697 // int a7 __attribute__((weakref));
1699 // int a7 __attribute__((weak));
1700 // This looks like a bug in gcc. We reject that for now. We should revisit
1701 // it if this behaviour is actually used.
1704 // static ((alias ("y"), weakref)).
1705 // Should we? How to check that weakref is before or after alias?
1707 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1708 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1709 // StringRef parameter it was given anyway.
1711 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1712 // GCC will accept anything as the argument of weakref. Should we
1713 // check for an existing decl?
1714 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1715 Attr.getAttributeSpellingListIndex()));
1717 D->addAttr(::new (S.Context)
1718 WeakRefAttr(Attr.getRange(), S.Context,
1719 Attr.getAttributeSpellingListIndex()));
1722 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1724 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1727 // Aliases should be on declarations, not definitions.
1728 const auto *FD = cast<FunctionDecl>(D);
1729 if (FD->isThisDeclarationADefinition()) {
1730 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1;
1733 // FIXME: it should be handled as a target specific attribute.
1734 if (S.Context.getTargetInfo().getTriple().getObjectFormat() !=
1735 llvm::Triple::ELF) {
1736 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1740 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str,
1741 Attr.getAttributeSpellingListIndex()));
1744 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1746 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1749 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1750 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1753 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1754 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx);
1757 // Aliases should be on declarations, not definitions.
1758 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1759 if (FD->isThisDeclarationADefinition()) {
1760 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0;
1764 const auto *VD = cast<VarDecl>(D);
1765 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1766 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0;
1771 // FIXME: check if target symbol exists in current file
1773 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1774 Attr.getAttributeSpellingListIndex()));
1777 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1778 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
1781 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1782 Attr.getAttributeSpellingListIndex()));
1785 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1786 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
1789 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1790 Attr.getAttributeSpellingListIndex()));
1793 static void handleTLSModelAttr(Sema &S, Decl *D,
1794 const AttributeList &Attr) {
1796 SourceLocation LiteralLoc;
1797 // Check that it is a string.
1798 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1801 // Check that the value.
1802 if (Model != "global-dynamic" && Model != "local-dynamic"
1803 && Model != "initial-exec" && Model != "local-exec") {
1804 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1808 D->addAttr(::new (S.Context)
1809 TLSModelAttr(Attr.getRange(), S.Context, Model,
1810 Attr.getAttributeSpellingListIndex()));
1813 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1814 QualType ResultType = getFunctionOrMethodResultType(D);
1815 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1816 D->addAttr(::new (S.Context) RestrictAttr(
1817 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1821 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
1822 << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
1825 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1826 if (S.LangOpts.CPlusPlus) {
1827 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
1828 << Attr.getName() << AttributeLangSupport::Cpp;
1832 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
1833 Attr.getAttributeSpellingListIndex()))
1837 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1838 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
1842 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
1843 Attr.getAttributeSpellingListIndex()));
1846 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1847 if (hasDeclarator(D)) return;
1849 if (S.CheckNoReturnAttr(attr)) return;
1851 if (!isa<ObjCMethodDecl>(D)) {
1852 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1853 << attr.getName() << ExpectedFunctionOrMethod;
1857 D->addAttr(::new (S.Context)
1858 NoReturnAttr(attr.getRange(), S.Context,
1859 attr.getAttributeSpellingListIndex()));
1862 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1863 if (!checkAttributeNumArgs(*this, attr, 0)) {
1871 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1872 const AttributeList &Attr) {
1874 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1875 // because 'analyzer_noreturn' does not impact the type.
1876 if (!isFunctionOrMethodOrBlock(D)) {
1877 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1878 if (!VD || (!VD->getType()->isBlockPointerType() &&
1879 !VD->getType()->isFunctionPointerType())) {
1880 S.Diag(Attr.getLoc(),
1881 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1882 : diag::warn_attribute_wrong_decl_type)
1883 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1888 D->addAttr(::new (S.Context)
1889 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1890 Attr.getAttributeSpellingListIndex()));
1893 // PS3 PPU-specific.
1894 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1896 Returning a Vector Class in Registers
1898 According to the PPU ABI specifications, a class with a single member of
1899 vector type is returned in memory when used as the return value of a function.
1900 This results in inefficient code when implementing vector classes. To return
1901 the value in a single vector register, add the vecreturn attribute to the
1902 class definition. This attribute is also applicable to struct types.
1908 __vector float xyzw;
1909 } __attribute__((vecreturn));
1911 Vector Add(Vector lhs, Vector rhs)
1914 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1915 return result; // This will be returned in a register
1918 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1919 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
1923 RecordDecl *record = cast<RecordDecl>(D);
1926 if (!isa<CXXRecordDecl>(record)) {
1927 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1931 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1932 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1936 for (const auto *I : record->fields()) {
1937 if ((count == 1) || !I->getType()->isVectorType()) {
1938 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1944 D->addAttr(::new (S.Context)
1945 VecReturnAttr(Attr.getRange(), S.Context,
1946 Attr.getAttributeSpellingListIndex()));
1949 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1950 const AttributeList &Attr) {
1951 if (isa<ParmVarDecl>(D)) {
1952 // [[carries_dependency]] can only be applied to a parameter if it is a
1953 // parameter of a function declaration or lambda.
1954 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1955 S.Diag(Attr.getLoc(),
1956 diag::err_carries_dependency_param_not_function_decl);
1961 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1962 Attr.getRange(), S.Context,
1963 Attr.getAttributeSpellingListIndex()));
1966 static void handleNotTailCalledAttr(Sema &S, Decl *D,
1967 const AttributeList &Attr) {
1968 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
1972 D->addAttr(::new (S.Context) NotTailCalledAttr(
1973 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1976 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
1977 const AttributeList &Attr) {
1978 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
1982 D->addAttr(::new (S.Context) DisableTailCallsAttr(
1983 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
1986 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1987 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1988 if (VD->hasLocalStorage()) {
1989 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1992 } else if (!isFunctionOrMethod(D)) {
1993 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1994 << Attr.getName() << ExpectedVariableOrFunction;
1998 D->addAttr(::new (S.Context)
1999 UsedAttr(Attr.getRange(), S.Context,
2000 Attr.getAttributeSpellingListIndex()));
2003 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2004 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName();
2006 if (IsCXX1zAttr && isa<VarDecl>(D)) {
2007 // The C++1z spelling of this attribute cannot be applied to a static data
2008 // member per [dcl.attr.unused]p2.
2009 if (cast<VarDecl>(D)->isStaticDataMember()) {
2010 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2011 << Attr.getName() << ExpectedForMaybeUnused;
2016 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2017 // about using it as an extension.
2018 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr)
2019 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2021 D->addAttr(::new (S.Context) UnusedAttr(
2022 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
2025 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2026 uint32_t priority = ConstructorAttr::DefaultPriority;
2027 if (Attr.getNumArgs() &&
2028 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2031 D->addAttr(::new (S.Context)
2032 ConstructorAttr(Attr.getRange(), S.Context, priority,
2033 Attr.getAttributeSpellingListIndex()));
2036 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2037 uint32_t priority = DestructorAttr::DefaultPriority;
2038 if (Attr.getNumArgs() &&
2039 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
2042 D->addAttr(::new (S.Context)
2043 DestructorAttr(Attr.getRange(), S.Context, priority,
2044 Attr.getAttributeSpellingListIndex()));
2047 template <typename AttrTy>
2048 static void handleAttrWithMessage(Sema &S, Decl *D,
2049 const AttributeList &Attr) {
2050 // Handle the case where the attribute has a text message.
2052 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2055 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2056 Attr.getAttributeSpellingListIndex()));
2059 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2060 const AttributeList &Attr) {
2061 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2062 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2063 << Attr.getName() << Attr.getRange();
2067 D->addAttr(::new (S.Context)
2068 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
2069 Attr.getAttributeSpellingListIndex()));
2072 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2073 IdentifierInfo *Platform,
2074 VersionTuple Introduced,
2075 VersionTuple Deprecated,
2076 VersionTuple Obsoleted) {
2077 StringRef PlatformName
2078 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2079 if (PlatformName.empty())
2080 PlatformName = Platform->getName();
2082 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2083 // of these steps are needed).
2084 if (!Introduced.empty() && !Deprecated.empty() &&
2085 !(Introduced <= Deprecated)) {
2086 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2087 << 1 << PlatformName << Deprecated.getAsString()
2088 << 0 << Introduced.getAsString();
2092 if (!Introduced.empty() && !Obsoleted.empty() &&
2093 !(Introduced <= Obsoleted)) {
2094 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2095 << 2 << PlatformName << Obsoleted.getAsString()
2096 << 0 << Introduced.getAsString();
2100 if (!Deprecated.empty() && !Obsoleted.empty() &&
2101 !(Deprecated <= Obsoleted)) {
2102 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2103 << 2 << PlatformName << Obsoleted.getAsString()
2104 << 1 << Deprecated.getAsString();
2111 /// \brief Check whether the two versions match.
2113 /// If either version tuple is empty, then they are assumed to match. If
2114 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2115 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2116 bool BeforeIsOkay) {
2117 if (X.empty() || Y.empty())
2123 if (BeforeIsOkay && X < Y)
2129 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2130 IdentifierInfo *Platform,
2132 VersionTuple Introduced,
2133 VersionTuple Deprecated,
2134 VersionTuple Obsoleted,
2138 StringRef Replacement,
2139 AvailabilityMergeKind AMK,
2140 unsigned AttrSpellingListIndex) {
2141 VersionTuple MergedIntroduced = Introduced;
2142 VersionTuple MergedDeprecated = Deprecated;
2143 VersionTuple MergedObsoleted = Obsoleted;
2144 bool FoundAny = false;
2145 bool OverrideOrImpl = false;
2148 case AMK_Redeclaration:
2149 OverrideOrImpl = false;
2153 case AMK_ProtocolImplementation:
2154 OverrideOrImpl = true;
2158 if (D->hasAttrs()) {
2159 AttrVec &Attrs = D->getAttrs();
2160 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2161 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2167 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2168 if (OldPlatform != Platform) {
2173 // If there is an existing availability attribute for this platform that
2174 // is explicit and the new one is implicit use the explicit one and
2175 // discard the new implicit attribute.
2176 if (!OldAA->isImplicit() && Implicit) {
2180 // If there is an existing attribute for this platform that is implicit
2181 // and the new attribute is explicit then erase the old one and
2182 // continue processing the attributes.
2183 if (!Implicit && OldAA->isImplicit()) {
2184 Attrs.erase(Attrs.begin() + i);
2190 VersionTuple OldIntroduced = OldAA->getIntroduced();
2191 VersionTuple OldDeprecated = OldAA->getDeprecated();
2192 VersionTuple OldObsoleted = OldAA->getObsoleted();
2193 bool OldIsUnavailable = OldAA->getUnavailable();
2195 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2196 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2197 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2198 !(OldIsUnavailable == IsUnavailable ||
2199 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2200 if (OverrideOrImpl) {
2202 VersionTuple FirstVersion;
2203 VersionTuple SecondVersion;
2204 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2206 FirstVersion = OldIntroduced;
2207 SecondVersion = Introduced;
2208 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2210 FirstVersion = Deprecated;
2211 SecondVersion = OldDeprecated;
2212 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2214 FirstVersion = Obsoleted;
2215 SecondVersion = OldObsoleted;
2219 Diag(OldAA->getLocation(),
2220 diag::warn_mismatched_availability_override_unavail)
2221 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2222 << (AMK == AMK_Override);
2224 Diag(OldAA->getLocation(),
2225 diag::warn_mismatched_availability_override)
2227 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2228 << FirstVersion.getAsString() << SecondVersion.getAsString()
2229 << (AMK == AMK_Override);
2231 if (AMK == AMK_Override)
2232 Diag(Range.getBegin(), diag::note_overridden_method);
2234 Diag(Range.getBegin(), diag::note_protocol_method);
2236 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2237 Diag(Range.getBegin(), diag::note_previous_attribute);
2240 Attrs.erase(Attrs.begin() + i);
2245 VersionTuple MergedIntroduced2 = MergedIntroduced;
2246 VersionTuple MergedDeprecated2 = MergedDeprecated;
2247 VersionTuple MergedObsoleted2 = MergedObsoleted;
2249 if (MergedIntroduced2.empty())
2250 MergedIntroduced2 = OldIntroduced;
2251 if (MergedDeprecated2.empty())
2252 MergedDeprecated2 = OldDeprecated;
2253 if (MergedObsoleted2.empty())
2254 MergedObsoleted2 = OldObsoleted;
2256 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2257 MergedIntroduced2, MergedDeprecated2,
2258 MergedObsoleted2)) {
2259 Attrs.erase(Attrs.begin() + i);
2264 MergedIntroduced = MergedIntroduced2;
2265 MergedDeprecated = MergedDeprecated2;
2266 MergedObsoleted = MergedObsoleted2;
2272 MergedIntroduced == Introduced &&
2273 MergedDeprecated == Deprecated &&
2274 MergedObsoleted == Obsoleted)
2277 // Only create a new attribute if !OverrideOrImpl, but we want to do
2279 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2280 MergedDeprecated, MergedObsoleted) &&
2282 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2283 Introduced, Deprecated,
2284 Obsoleted, IsUnavailable, Message,
2285 IsStrict, Replacement,
2286 AttrSpellingListIndex);
2287 Avail->setImplicit(Implicit);
2293 static void handleAvailabilityAttr(Sema &S, Decl *D,
2294 const AttributeList &Attr) {
2295 if (!checkAttributeNumArgs(S, Attr, 1))
2297 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2298 unsigned Index = Attr.getAttributeSpellingListIndex();
2300 IdentifierInfo *II = Platform->Ident;
2301 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2302 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2305 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2307 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2311 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2312 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2313 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2314 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2315 bool IsStrict = Attr.getStrictLoc().isValid();
2317 if (const StringLiteral *SE =
2318 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2319 Str = SE->getString();
2320 StringRef Replacement;
2321 if (const StringLiteral *SE =
2322 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr()))
2323 Replacement = SE->getString();
2325 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2331 IsStrict, Replacement,
2335 D->addAttr(NewAttr);
2337 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2338 // matches before the start of the watchOS platform.
2339 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2340 IdentifierInfo *NewII = nullptr;
2341 if (II->getName() == "ios")
2342 NewII = &S.Context.Idents.get("watchos");
2343 else if (II->getName() == "ios_app_extension")
2344 NewII = &S.Context.Idents.get("watchos_app_extension");
2347 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2348 if (Version.empty())
2350 auto Major = Version.getMajor();
2351 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2352 if (NewMajor >= 2) {
2353 if (Version.getMinor().hasValue()) {
2354 if (Version.getSubminor().hasValue())
2355 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2356 Version.getSubminor().getValue());
2358 return VersionTuple(NewMajor, Version.getMinor().getValue());
2362 return VersionTuple(2, 0);
2365 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2366 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2367 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2369 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2382 D->addAttr(NewAttr);
2384 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2385 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2386 // matches before the start of the tvOS platform.
2387 IdentifierInfo *NewII = nullptr;
2388 if (II->getName() == "ios")
2389 NewII = &S.Context.Idents.get("tvos");
2390 else if (II->getName() == "ios_app_extension")
2391 NewII = &S.Context.Idents.get("tvos_app_extension");
2394 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2407 D->addAttr(NewAttr);
2413 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2414 typename T::VisibilityType value,
2415 unsigned attrSpellingListIndex) {
2416 T *existingAttr = D->getAttr<T>();
2418 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2419 if (existingValue == value)
2421 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2422 S.Diag(range.getBegin(), diag::note_previous_attribute);
2425 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2428 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2429 VisibilityAttr::VisibilityType Vis,
2430 unsigned AttrSpellingListIndex) {
2431 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2432 AttrSpellingListIndex);
2435 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2436 TypeVisibilityAttr::VisibilityType Vis,
2437 unsigned AttrSpellingListIndex) {
2438 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2439 AttrSpellingListIndex);
2442 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2443 bool isTypeVisibility) {
2444 // Visibility attributes don't mean anything on a typedef.
2445 if (isa<TypedefNameDecl>(D)) {
2446 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2451 // 'type_visibility' can only go on a type or namespace.
2452 if (isTypeVisibility &&
2453 !(isa<TagDecl>(D) ||
2454 isa<ObjCInterfaceDecl>(D) ||
2455 isa<NamespaceDecl>(D))) {
2456 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2457 << Attr.getName() << ExpectedTypeOrNamespace;
2461 // Check that the argument is a string literal.
2463 SourceLocation LiteralLoc;
2464 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2467 VisibilityAttr::VisibilityType type;
2468 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2469 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2470 << Attr.getName() << TypeStr;
2474 // Complain about attempts to use protected visibility on targets
2475 // (like Darwin) that don't support it.
2476 if (type == VisibilityAttr::Protected &&
2477 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2478 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2479 type = VisibilityAttr::Default;
2482 unsigned Index = Attr.getAttributeSpellingListIndex();
2483 clang::Attr *newAttr;
2484 if (isTypeVisibility) {
2485 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2486 (TypeVisibilityAttr::VisibilityType) type,
2489 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2492 D->addAttr(newAttr);
2495 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2496 const AttributeList &Attr) {
2497 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
2498 if (!Attr.isArgIdent(0)) {
2499 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2500 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2504 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2505 ObjCMethodFamilyAttr::FamilyKind F;
2506 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2507 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2512 if (F == ObjCMethodFamilyAttr::OMF_init &&
2513 !method->getReturnType()->isObjCObjectPointerType()) {
2514 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2515 << method->getReturnType();
2516 // Ignore the attribute.
2520 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2522 Attr.getAttributeSpellingListIndex()));
2525 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2526 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2527 QualType T = TD->getUnderlyingType();
2528 if (!T->isCARCBridgableType()) {
2529 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2533 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2534 QualType T = PD->getType();
2535 if (!T->isCARCBridgableType()) {
2536 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2541 // It is okay to include this attribute on properties, e.g.:
2543 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2545 // In this case it follows tradition and suppresses an error in the above
2547 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2549 D->addAttr(::new (S.Context)
2550 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2551 Attr.getAttributeSpellingListIndex()));
2554 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
2555 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2556 QualType T = TD->getUnderlyingType();
2557 if (!T->isObjCObjectPointerType()) {
2558 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2562 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2565 D->addAttr(::new (S.Context)
2566 ObjCIndependentClassAttr(Attr.getRange(), S.Context,
2567 Attr.getAttributeSpellingListIndex()));
2570 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2571 if (!Attr.isArgIdent(0)) {
2572 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2573 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2577 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2578 BlocksAttr::BlockType type;
2579 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2580 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2581 << Attr.getName() << II;
2585 D->addAttr(::new (S.Context)
2586 BlocksAttr(Attr.getRange(), S.Context, type,
2587 Attr.getAttributeSpellingListIndex()));
2590 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2591 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2592 if (Attr.getNumArgs() > 0) {
2593 Expr *E = Attr.getArgAsExpr(0);
2594 llvm::APSInt Idx(32);
2595 if (E->isTypeDependent() || E->isValueDependent() ||
2596 !E->isIntegerConstantExpr(Idx, S.Context)) {
2597 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2598 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2599 << E->getSourceRange();
2603 if (Idx.isSigned() && Idx.isNegative()) {
2604 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2605 << E->getSourceRange();
2609 sentinel = Idx.getZExtValue();
2612 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2613 if (Attr.getNumArgs() > 1) {
2614 Expr *E = Attr.getArgAsExpr(1);
2615 llvm::APSInt Idx(32);
2616 if (E->isTypeDependent() || E->isValueDependent() ||
2617 !E->isIntegerConstantExpr(Idx, S.Context)) {
2618 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2619 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2620 << E->getSourceRange();
2623 nullPos = Idx.getZExtValue();
2625 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2626 // FIXME: This error message could be improved, it would be nice
2627 // to say what the bounds actually are.
2628 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2629 << E->getSourceRange();
2634 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2635 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2636 if (isa<FunctionNoProtoType>(FT)) {
2637 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2641 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2642 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2645 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2646 if (!MD->isVariadic()) {
2647 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2650 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2651 if (!BD->isVariadic()) {
2652 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2655 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2656 QualType Ty = V->getType();
2657 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2658 const FunctionType *FT = Ty->isFunctionPointerType()
2659 ? D->getFunctionType()
2660 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2661 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2662 int m = Ty->isFunctionPointerType() ? 0 : 1;
2663 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2667 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2668 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2672 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2673 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2676 D->addAttr(::new (S.Context)
2677 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2678 Attr.getAttributeSpellingListIndex()));
2681 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2682 if (D->getFunctionType() &&
2683 D->getFunctionType()->getReturnType()->isVoidType()) {
2684 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2685 << Attr.getName() << 0;
2688 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2689 if (MD->getReturnType()->isVoidType()) {
2690 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2691 << Attr.getName() << 1;
2695 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn
2696 // about using it as an extension.
2697 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() &&
2698 !Attr.getScopeName())
2699 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName();
2701 D->addAttr(::new (S.Context)
2702 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2703 Attr.getAttributeSpellingListIndex()));
2706 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2707 // weak_import only applies to variable & function declarations.
2709 if (!D->canBeWeakImported(isDef)) {
2711 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2713 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2714 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2715 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2716 // Nothing to warn about here.
2718 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2719 << Attr.getName() << ExpectedVariableOrFunction;
2724 D->addAttr(::new (S.Context)
2725 WeakImportAttr(Attr.getRange(), S.Context,
2726 Attr.getAttributeSpellingListIndex()));
2729 // Handles reqd_work_group_size and work_group_size_hint.
2730 template <typename WorkGroupAttr>
2731 static void handleWorkGroupSize(Sema &S, Decl *D,
2732 const AttributeList &Attr) {
2734 for (unsigned i = 0; i < 3; ++i) {
2735 const Expr *E = Attr.getArgAsExpr(i);
2736 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
2738 if (WGSize[i] == 0) {
2739 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
2740 << Attr.getName() << E->getSourceRange();
2745 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2746 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2747 Existing->getYDim() == WGSize[1] &&
2748 Existing->getZDim() == WGSize[2]))
2749 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2751 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
2752 WGSize[0], WGSize[1], WGSize[2],
2753 Attr.getAttributeSpellingListIndex()));
2756 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2757 if (!Attr.hasParsedType()) {
2758 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2759 << Attr.getName() << 1;
2763 TypeSourceInfo *ParmTSI = nullptr;
2764 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2765 assert(ParmTSI && "no type source info for attribute argument");
2767 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2768 (ParmType->isBooleanType() ||
2769 !ParmType->isIntegralType(S.getASTContext()))) {
2770 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2775 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2776 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2777 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2782 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2784 Attr.getAttributeSpellingListIndex()));
2787 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2789 unsigned AttrSpellingListIndex) {
2790 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2791 if (ExistingAttr->getName() == Name)
2793 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2794 Diag(Range.getBegin(), diag::note_previous_attribute);
2797 return ::new (Context) SectionAttr(Range, Context, Name,
2798 AttrSpellingListIndex);
2801 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2802 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2803 if (!Error.empty()) {
2804 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
2810 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2811 // Make sure that there is a string literal as the sections's single
2814 SourceLocation LiteralLoc;
2815 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2818 if (!S.checkSectionName(LiteralLoc, Str))
2821 // If the target wants to validate the section specifier, make it happen.
2822 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2823 if (!Error.empty()) {
2824 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2829 unsigned Index = Attr.getAttributeSpellingListIndex();
2830 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2832 D->addAttr(NewAttr);
2835 // Check for things we'd like to warn about, no errors or validation for now.
2836 // TODO: Validation should use a backend target library that specifies
2837 // the allowable subtarget features and cpus. We could use something like a
2838 // TargetCodeGenInfo hook here to do validation.
2839 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2840 for (auto Str : {"tune=", "fpmath="})
2841 if (AttrStr.find(Str) != StringRef::npos)
2842 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
2845 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2847 SourceLocation LiteralLoc;
2848 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2850 S.checkTargetAttr(LiteralLoc, Str);
2851 unsigned Index = Attr.getAttributeSpellingListIndex();
2852 TargetAttr *NewAttr =
2853 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
2854 D->addAttr(NewAttr);
2857 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2858 VarDecl *VD = cast<VarDecl>(D);
2859 if (!VD->hasLocalStorage()) {
2860 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2864 Expr *E = Attr.getArgAsExpr(0);
2865 SourceLocation Loc = E->getExprLoc();
2866 FunctionDecl *FD = nullptr;
2867 DeclarationNameInfo NI;
2869 // gcc only allows for simple identifiers. Since we support more than gcc, we
2870 // will warn the user.
2871 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2872 if (DRE->hasQualifier())
2873 S.Diag(Loc, diag::warn_cleanup_ext);
2874 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2875 NI = DRE->getNameInfo();
2877 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2881 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2882 if (ULE->hasExplicitTemplateArgs())
2883 S.Diag(Loc, diag::warn_cleanup_ext);
2884 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2885 NI = ULE->getNameInfo();
2887 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2889 if (ULE->getType() == S.Context.OverloadTy)
2890 S.NoteAllOverloadCandidates(ULE);
2894 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2898 if (FD->getNumParams() != 1) {
2899 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2904 // We're currently more strict than GCC about what function types we accept.
2905 // If this ever proves to be a problem it should be easy to fix.
2906 QualType Ty = S.Context.getPointerType(VD->getType());
2907 QualType ParamTy = FD->getParamDecl(0)->getType();
2908 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2909 ParamTy, Ty) != Sema::Compatible) {
2910 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2911 << NI.getName() << ParamTy << Ty;
2915 D->addAttr(::new (S.Context)
2916 CleanupAttr(Attr.getRange(), S.Context, FD,
2917 Attr.getAttributeSpellingListIndex()));
2920 /// Handle __attribute__((format_arg((idx)))) attribute based on
2921 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2922 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2923 Expr *IdxExpr = Attr.getArgAsExpr(0);
2925 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
2928 // Make sure the format string is really a string.
2929 QualType Ty = getFunctionOrMethodParamType(D, Idx);
2931 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
2932 if (NotNSStringTy &&
2933 !isCFStringType(Ty, S.Context) &&
2934 (!Ty->isPointerType() ||
2935 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2936 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2937 << "a string type" << IdxExpr->getSourceRange()
2938 << getFunctionOrMethodParamRange(D, 0);
2941 Ty = getFunctionOrMethodResultType(D);
2942 if (!isNSStringType(Ty, S.Context) &&
2943 !isCFStringType(Ty, S.Context) &&
2944 (!Ty->isPointerType() ||
2945 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2946 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2947 << (NotNSStringTy ? "string type" : "NSString")
2948 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
2952 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
2953 // because that has corrected for the implicit this parameter, and is zero-
2954 // based. The attribute expects what the user wrote explicitly.
2956 IdxExpr->EvaluateAsInt(Val, S.Context);
2958 D->addAttr(::new (S.Context)
2959 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2960 Attr.getAttributeSpellingListIndex()));
2963 enum FormatAttrKind {
2972 /// getFormatAttrKind - Map from format attribute names to supported format
2974 static FormatAttrKind getFormatAttrKind(StringRef Format) {
2975 return llvm::StringSwitch<FormatAttrKind>(Format)
2976 // Check for formats that get handled specially.
2977 .Case("NSString", NSStringFormat)
2978 .Case("CFString", CFStringFormat)
2979 .Case("strftime", StrftimeFormat)
2981 // Otherwise, check for supported formats.
2982 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2983 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2984 .Case("kprintf", SupportedFormat) // OpenBSD.
2985 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
2986 .Case("os_trace", SupportedFormat)
2987 .Case("os_log", SupportedFormat)
2989 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2990 .Default(InvalidFormat);
2993 /// Handle __attribute__((init_priority(priority))) attributes based on
2994 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2995 static void handleInitPriorityAttr(Sema &S, Decl *D,
2996 const AttributeList &Attr) {
2997 if (!S.getLangOpts().CPlusPlus) {
2998 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3002 if (S.getCurFunctionOrMethodDecl()) {
3003 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3007 QualType T = cast<VarDecl>(D)->getType();
3008 if (S.Context.getAsArrayType(T))
3009 T = S.Context.getBaseElementType(T);
3010 if (!T->getAs<RecordType>()) {
3011 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3016 Expr *E = Attr.getArgAsExpr(0);
3017 uint32_t prioritynum;
3018 if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
3023 if (prioritynum < 101 || prioritynum > 65535) {
3024 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3025 << E->getSourceRange() << Attr.getName() << 101 << 65535;
3029 D->addAttr(::new (S.Context)
3030 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3031 Attr.getAttributeSpellingListIndex()));
3034 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3035 IdentifierInfo *Format, int FormatIdx,
3037 unsigned AttrSpellingListIndex) {
3038 // Check whether we already have an equivalent format attribute.
3039 for (auto *F : D->specific_attrs<FormatAttr>()) {
3040 if (F->getType() == Format &&
3041 F->getFormatIdx() == FormatIdx &&
3042 F->getFirstArg() == FirstArg) {
3043 // If we don't have a valid location for this attribute, adopt the
3045 if (F->getLocation().isInvalid())
3051 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3052 FirstArg, AttrSpellingListIndex);
3055 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3056 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3057 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3058 if (!Attr.isArgIdent(0)) {
3059 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3060 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3064 // In C++ the implicit 'this' function parameter also counts, and they are
3065 // counted from one.
3066 bool HasImplicitThisParam = isInstanceMethod(D);
3067 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3069 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3070 StringRef Format = II->getName();
3072 if (normalizeName(Format)) {
3073 // If we've modified the string name, we need a new identifier for it.
3074 II = &S.Context.Idents.get(Format);
3077 // Check for supported formats.
3078 FormatAttrKind Kind = getFormatAttrKind(Format);
3080 if (Kind == IgnoredFormat)
3083 if (Kind == InvalidFormat) {
3084 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3085 << Attr.getName() << II->getName();
3089 // checks for the 2nd argument
3090 Expr *IdxExpr = Attr.getArgAsExpr(1);
3092 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
3095 if (Idx < 1 || Idx > NumArgs) {
3096 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3097 << Attr.getName() << 2 << IdxExpr->getSourceRange();
3101 // FIXME: Do we need to bounds check?
3102 unsigned ArgIdx = Idx - 1;
3104 if (HasImplicitThisParam) {
3106 S.Diag(Attr.getLoc(),
3107 diag::err_format_attribute_implicit_this_format_string)
3108 << IdxExpr->getSourceRange();
3114 // make sure the format string is really a string
3115 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3117 if (Kind == CFStringFormat) {
3118 if (!isCFStringType(Ty, S.Context)) {
3119 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3120 << "a CFString" << IdxExpr->getSourceRange()
3121 << getFunctionOrMethodParamRange(D, ArgIdx);
3124 } else if (Kind == NSStringFormat) {
3125 // FIXME: do we need to check if the type is NSString*? What are the
3127 if (!isNSStringType(Ty, S.Context)) {
3128 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3129 << "an NSString" << IdxExpr->getSourceRange()
3130 << getFunctionOrMethodParamRange(D, ArgIdx);
3133 } else if (!Ty->isPointerType() ||
3134 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3135 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3136 << "a string type" << IdxExpr->getSourceRange()
3137 << getFunctionOrMethodParamRange(D, ArgIdx);
3141 // check the 3rd argument
3142 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3144 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
3147 // check if the function is variadic if the 3rd argument non-zero
3148 if (FirstArg != 0) {
3149 if (isFunctionOrMethodVariadic(D)) {
3150 ++NumArgs; // +1 for ...
3152 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3157 // strftime requires FirstArg to be 0 because it doesn't read from any
3158 // variable the input is just the current time + the format string.
3159 if (Kind == StrftimeFormat) {
3160 if (FirstArg != 0) {
3161 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3162 << FirstArgExpr->getSourceRange();
3165 // if 0 it disables parameter checking (to use with e.g. va_list)
3166 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3167 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3168 << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
3172 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3174 Attr.getAttributeSpellingListIndex());
3176 D->addAttr(NewAttr);
3179 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3180 const AttributeList &Attr) {
3181 // Try to find the underlying union declaration.
3182 RecordDecl *RD = nullptr;
3183 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3184 if (TD && TD->getUnderlyingType()->isUnionType())
3185 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3187 RD = dyn_cast<RecordDecl>(D);
3189 if (!RD || !RD->isUnion()) {
3190 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3191 << Attr.getName() << ExpectedUnion;
3195 if (!RD->isCompleteDefinition()) {
3196 S.Diag(Attr.getLoc(),
3197 diag::warn_transparent_union_attribute_not_definition);
3201 RecordDecl::field_iterator Field = RD->field_begin(),
3202 FieldEnd = RD->field_end();
3203 if (Field == FieldEnd) {
3204 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3208 FieldDecl *FirstField = *Field;
3209 QualType FirstType = FirstField->getType();
3210 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3211 S.Diag(FirstField->getLocation(),
3212 diag::warn_transparent_union_attribute_floating)
3213 << FirstType->isVectorType() << FirstType;
3217 if (FirstType->isIncompleteType())
3219 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3220 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3221 for (; Field != FieldEnd; ++Field) {
3222 QualType FieldType = Field->getType();
3223 if (FieldType->isIncompleteType())
3225 // FIXME: this isn't fully correct; we also need to test whether the
3226 // members of the union would all have the same calling convention as the
3227 // first member of the union. Checking just the size and alignment isn't
3228 // sufficient (consider structs passed on the stack instead of in registers
3230 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3231 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3232 // Warn if we drop the attribute.
3233 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3234 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3235 : S.Context.getTypeAlign(FieldType);
3236 S.Diag(Field->getLocation(),
3237 diag::warn_transparent_union_attribute_field_size_align)
3238 << isSize << Field->getDeclName() << FieldBits;
3239 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3240 S.Diag(FirstField->getLocation(),
3241 diag::note_transparent_union_first_field_size_align)
3242 << isSize << FirstBits;
3247 RD->addAttr(::new (S.Context)
3248 TransparentUnionAttr(Attr.getRange(), S.Context,
3249 Attr.getAttributeSpellingListIndex()));
3252 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3253 // Make sure that there is a string literal as the annotation's single
3256 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3259 // Don't duplicate annotations that are already set.
3260 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3261 if (I->getAnnotation() == Str)
3265 D->addAttr(::new (S.Context)
3266 AnnotateAttr(Attr.getRange(), S.Context, Str,
3267 Attr.getAttributeSpellingListIndex()));
3270 static void handleAlignValueAttr(Sema &S, Decl *D,
3271 const AttributeList &Attr) {
3272 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
3273 Attr.getAttributeSpellingListIndex());
3276 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3277 unsigned SpellingListIndex) {
3278 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3279 SourceLocation AttrLoc = AttrRange.getBegin();
3282 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3283 T = TD->getUnderlyingType();
3284 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3287 llvm_unreachable("Unknown decl type for align_value");
3289 if (!T->isDependentType() && !T->isAnyPointerType() &&
3290 !T->isReferenceType() && !T->isMemberPointerType()) {
3291 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3292 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3296 if (!E->isValueDependent()) {
3297 llvm::APSInt Alignment;
3299 = VerifyIntegerConstantExpression(E, &Alignment,
3300 diag::err_align_value_attribute_argument_not_int,
3301 /*AllowFold*/ false);
3302 if (ICE.isInvalid())
3305 if (!Alignment.isPowerOf2()) {
3306 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3307 << E->getSourceRange();
3311 D->addAttr(::new (Context)
3312 AlignValueAttr(AttrRange, Context, ICE.get(),
3313 SpellingListIndex));
3317 // Save dependent expressions in the AST to be instantiated.
3318 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3321 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3322 // check the attribute arguments.
3323 if (Attr.getNumArgs() > 1) {
3324 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3325 << Attr.getName() << 1;
3329 if (Attr.getNumArgs() == 0) {
3330 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3331 true, nullptr, Attr.getAttributeSpellingListIndex()));
3335 Expr *E = Attr.getArgAsExpr(0);
3336 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3337 S.Diag(Attr.getEllipsisLoc(),
3338 diag::err_pack_expansion_without_parameter_packs);
3342 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3345 if (E->isValueDependent()) {
3346 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3347 if (!TND->getUnderlyingType()->isDependentType()) {
3348 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
3349 << E->getSourceRange();
3355 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3356 Attr.isPackExpansion());
3359 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3360 unsigned SpellingListIndex, bool IsPackExpansion) {
3361 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3362 SourceLocation AttrLoc = AttrRange.getBegin();
3364 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3365 if (TmpAttr.isAlignas()) {
3366 // C++11 [dcl.align]p1:
3367 // An alignment-specifier may be applied to a variable or to a class
3368 // data member, but it shall not be applied to a bit-field, a function
3369 // parameter, the formal parameter of a catch clause, or a variable
3370 // declared with the register storage class specifier. An
3371 // alignment-specifier may also be applied to the declaration of a class
3372 // or enumeration type.
3374 // An alignment attribute shall not be specified in a declaration of
3375 // a typedef, or a bit-field, or a function, or a parameter, or an
3376 // object declared with the register storage-class specifier.
3378 if (isa<ParmVarDecl>(D)) {
3380 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3381 if (VD->getStorageClass() == SC_Register)
3383 if (VD->isExceptionVariable())
3385 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3386 if (FD->isBitField())
3388 } else if (!isa<TagDecl>(D)) {
3389 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3390 << (TmpAttr.isC11() ? ExpectedVariableOrField
3391 : ExpectedVariableFieldOrTag);
3394 if (DiagKind != -1) {
3395 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3396 << &TmpAttr << DiagKind;
3401 if (E->isTypeDependent() || E->isValueDependent()) {
3402 // Save dependent expressions in the AST to be instantiated.
3403 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3404 AA->setPackExpansion(IsPackExpansion);
3409 // FIXME: Cache the number on the Attr object?
3410 llvm::APSInt Alignment;
3412 = VerifyIntegerConstantExpression(E, &Alignment,
3413 diag::err_aligned_attribute_argument_not_int,
3414 /*AllowFold*/ false);
3415 if (ICE.isInvalid())
3418 uint64_t AlignVal = Alignment.getZExtValue();
3420 // C++11 [dcl.align]p2:
3421 // -- if the constant expression evaluates to zero, the alignment
3422 // specifier shall have no effect
3424 // An alignment specification of zero has no effect.
3425 if (!(TmpAttr.isAlignas() && !Alignment)) {
3426 if (!llvm::isPowerOf2_64(AlignVal)) {
3427 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3428 << E->getSourceRange();
3433 // Alignment calculations can wrap around if it's greater than 2**28.
3434 unsigned MaxValidAlignment =
3435 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3437 if (AlignVal > MaxValidAlignment) {
3438 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3439 << E->getSourceRange();
3443 if (Context.getTargetInfo().isTLSSupported()) {
3444 unsigned MaxTLSAlign =
3445 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3447 auto *VD = dyn_cast<VarDecl>(D);
3448 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3449 VD->getTLSKind() != VarDecl::TLS_None) {
3450 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3451 << (unsigned)AlignVal << VD << MaxTLSAlign;
3456 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3457 ICE.get(), SpellingListIndex);
3458 AA->setPackExpansion(IsPackExpansion);
3462 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3463 unsigned SpellingListIndex, bool IsPackExpansion) {
3464 // FIXME: Cache the number on the Attr object if non-dependent?
3465 // FIXME: Perform checking of type validity
3466 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3468 AA->setPackExpansion(IsPackExpansion);
3472 void Sema::CheckAlignasUnderalignment(Decl *D) {
3473 assert(D->hasAttrs() && "no attributes on decl");
3475 QualType UnderlyingTy, DiagTy;
3476 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
3477 UnderlyingTy = DiagTy = VD->getType();
3479 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3480 if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3481 UnderlyingTy = ED->getIntegerType();
3483 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3486 // C++11 [dcl.align]p5, C11 6.7.5/4:
3487 // The combined effect of all alignment attributes in a declaration shall
3488 // not specify an alignment that is less strict than the alignment that
3489 // would otherwise be required for the entity being declared.
3490 AlignedAttr *AlignasAttr = nullptr;
3492 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3493 if (I->isAlignmentDependent())
3497 Align = std::max(Align, I->getAlignment(Context));
3500 if (AlignasAttr && Align) {
3501 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3502 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3503 if (NaturalAlign > RequestedAlign)
3504 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3505 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3509 bool Sema::checkMSInheritanceAttrOnDefinition(
3510 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3511 MSInheritanceAttr::Spelling SemanticSpelling) {
3512 assert(RD->hasDefinition() && "RD has no definition!");
3514 // We may not have seen base specifiers or any virtual methods yet. We will
3515 // have to wait until the record is defined to catch any mismatches.
3516 if (!RD->getDefinition()->isCompleteDefinition())
3519 // The unspecified model never matches what a definition could need.
3520 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3524 if (RD->calculateInheritanceModel() == SemanticSpelling)
3527 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3531 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3532 << 0 /*definition*/;
3533 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3534 << RD->getNameAsString();
3538 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3540 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3541 bool &IntegerMode, bool &ComplexMode) {
3543 ComplexMode = false;
3544 switch (Str.size()) {
3566 if (Str[1] == 'F') {
3567 IntegerMode = false;
3568 } else if (Str[1] == 'C') {
3569 IntegerMode = false;
3571 } else if (Str[1] != 'I') {
3576 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3577 // pointer on PIC16 and other embedded platforms.
3579 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3580 else if (Str == "byte")
3581 DestWidth = S.Context.getTargetInfo().getCharWidth();
3584 if (Str == "pointer")
3585 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3588 if (Str == "unwind_word")
3589 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3594 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3597 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3598 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3599 /// HImode, not an intermediate pointer.
3600 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3601 // This attribute isn't documented, but glibc uses it. It changes
3602 // the width of an int or unsigned int to the specified size.
3603 if (!Attr.isArgIdent(0)) {
3604 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3605 << AANT_ArgumentIdentifier;
3609 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3611 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex());
3614 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3615 unsigned SpellingListIndex, bool InInstantiation) {
3616 StringRef Str = Name->getName();
3618 SourceLocation AttrLoc = AttrRange.getBegin();
3620 unsigned DestWidth = 0;
3621 bool IntegerMode = true;
3622 bool ComplexMode = false;
3623 llvm::APInt VectorSize(64, 0);
3624 if (Str.size() >= 4 && Str[0] == 'V') {
3625 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3626 size_t StrSize = Str.size();
3627 size_t VectorStringLength = 0;
3628 while ((VectorStringLength + 1) < StrSize &&
3629 isdigit(Str[VectorStringLength + 1]))
3630 ++VectorStringLength;
3631 if (VectorStringLength &&
3632 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3633 VectorSize.isPowerOf2()) {
3634 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3635 IntegerMode, ComplexMode);
3636 // Avoid duplicate warning from template instantiation.
3637 if (!InInstantiation)
3638 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3645 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3647 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3648 // and friends, at least with glibc.
3649 // FIXME: Make sure floating-point mappings are accurate
3650 // FIXME: Support XF and TF types
3652 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3657 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3658 OldTy = TD->getUnderlyingType();
3659 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
3660 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3661 // Try to get type from enum declaration, default to int.
3662 OldTy = ED->getIntegerType();
3664 OldTy = Context.IntTy;
3666 OldTy = cast<ValueDecl>(D)->getType();
3668 if (OldTy->isDependentType()) {
3669 D->addAttr(::new (Context)
3670 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3674 // Base type can also be a vector type (see PR17453).
3675 // Distinguish between base type and base element type.
3676 QualType OldElemTy = OldTy;
3677 if (const VectorType *VT = OldTy->getAs<VectorType>())
3678 OldElemTy = VT->getElementType();
3680 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3681 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3682 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3683 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3684 VectorSize.getBoolValue()) {
3685 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3688 bool IntegralOrAnyEnumType =
3689 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3691 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3692 !IntegralOrAnyEnumType)
3693 Diag(AttrLoc, diag::err_mode_not_primitive);
3694 else if (IntegerMode) {
3695 if (!IntegralOrAnyEnumType)
3696 Diag(AttrLoc, diag::err_mode_wrong_type);
3697 } else if (ComplexMode) {
3698 if (!OldElemTy->isComplexType())
3699 Diag(AttrLoc, diag::err_mode_wrong_type);
3701 if (!OldElemTy->isFloatingType())
3702 Diag(AttrLoc, diag::err_mode_wrong_type);
3708 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3709 OldElemTy->isSignedIntegerType());
3711 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3713 if (NewElemTy.isNull()) {
3714 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3719 NewElemTy = Context.getComplexType(NewElemTy);
3722 QualType NewTy = NewElemTy;
3723 if (VectorSize.getBoolValue()) {
3724 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3725 VectorType::GenericVector);
3726 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
3727 // Complex machine mode does not support base vector types.
3729 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3732 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3733 OldVT->getNumElements() /
3734 Context.getTypeSize(NewElemTy);
3736 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3739 if (NewTy.isNull()) {
3740 Diag(AttrLoc, diag::err_mode_wrong_type);
3744 // Install the new type.
3745 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3746 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3747 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
3748 ED->setIntegerType(NewTy);
3750 cast<ValueDecl>(D)->setType(NewTy);
3752 D->addAttr(::new (Context)
3753 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3756 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3757 D->addAttr(::new (S.Context)
3758 NoDebugAttr(Attr.getRange(), S.Context,
3759 Attr.getAttributeSpellingListIndex()));
3762 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3763 IdentifierInfo *Ident,
3764 unsigned AttrSpellingListIndex) {
3765 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3766 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3767 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3771 if (D->hasAttr<AlwaysInlineAttr>())
3774 return ::new (Context) AlwaysInlineAttr(Range, Context,
3775 AttrSpellingListIndex);
3778 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3779 IdentifierInfo *Ident,
3780 unsigned AttrSpellingListIndex) {
3781 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3784 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3787 InternalLinkageAttr *
3788 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3789 IdentifierInfo *Ident,
3790 unsigned AttrSpellingListIndex) {
3791 if (auto VD = dyn_cast<VarDecl>(D)) {
3792 // Attribute applies to Var but not any subclass of it (like ParmVar,
3793 // ImplicitParm or VarTemplateSpecialization).
3794 if (VD->getKind() != Decl::Var) {
3795 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3796 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3797 : ExpectedVariableOrFunction);
3800 // Attribute does not apply to non-static local variables.
3801 if (VD->hasLocalStorage()) {
3802 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3807 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3810 return ::new (Context)
3811 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3814 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3815 unsigned AttrSpellingListIndex) {
3816 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3817 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3818 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3822 if (D->hasAttr<MinSizeAttr>())
3825 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3828 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3829 unsigned AttrSpellingListIndex) {
3830 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3831 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3832 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3833 D->dropAttr<AlwaysInlineAttr>();
3835 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3836 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3837 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3838 D->dropAttr<MinSizeAttr>();
3841 if (D->hasAttr<OptimizeNoneAttr>())
3844 return ::new (Context) OptimizeNoneAttr(Range, Context,
3845 AttrSpellingListIndex);
3848 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
3849 const AttributeList &Attr) {
3850 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
3854 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
3855 D, Attr.getRange(), Attr.getName(),
3856 Attr.getAttributeSpellingListIndex()))
3860 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3861 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
3862 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3863 D->addAttr(MinSize);
3866 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
3867 const AttributeList &Attr) {
3868 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
3869 D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
3870 D->addAttr(Optnone);
3873 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3874 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, Attr.getRange(),
3877 auto *VD = cast<VarDecl>(D);
3878 if (!VD->hasGlobalStorage()) {
3879 S.Diag(Attr.getLoc(), diag::err_cuda_nonglobal_constant);
3882 D->addAttr(::new (S.Context) CUDAConstantAttr(
3883 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3886 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3887 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, Attr.getRange(),
3890 auto *VD = cast<VarDecl>(D);
3891 // extern __shared__ is only allowed on arrays with no length (e.g.
3893 if (VD->hasExternalStorage() && !isa<IncompleteArrayType>(VD->getType())) {
3894 S.Diag(Attr.getLoc(), diag::err_cuda_extern_shared) << VD;
3897 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
3898 S.CUDADiagIfHostCode(Attr.getLoc(), diag::err_cuda_host_shared)
3899 << S.CurrentCUDATarget())
3901 D->addAttr(::new (S.Context) CUDASharedAttr(
3902 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
3905 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3906 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(),
3908 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(),
3912 FunctionDecl *FD = cast<FunctionDecl>(D);
3913 if (!FD->getReturnType()->isVoidType()) {
3914 SourceRange RTRange = FD->getReturnTypeSourceRange();
3915 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3917 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
3921 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
3922 if (Method->isInstance()) {
3923 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
3927 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
3929 // Only warn for "inline" when compiling for host, to cut down on noise.
3930 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
3931 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
3933 D->addAttr(::new (S.Context)
3934 CUDAGlobalAttr(Attr.getRange(), S.Context,
3935 Attr.getAttributeSpellingListIndex()));
3938 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3939 FunctionDecl *Fn = cast<FunctionDecl>(D);
3940 if (!Fn->isInlineSpecified()) {
3941 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3945 D->addAttr(::new (S.Context)
3946 GNUInlineAttr(Attr.getRange(), S.Context,
3947 Attr.getAttributeSpellingListIndex()));
3950 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3951 if (hasDeclarator(D)) return;
3953 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3954 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3956 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
3959 if (!isa<ObjCMethodDecl>(D)) {
3960 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3961 << Attr.getName() << ExpectedFunctionOrMethod;
3965 switch (Attr.getKind()) {
3966 case AttributeList::AT_FastCall:
3967 D->addAttr(::new (S.Context)
3968 FastCallAttr(Attr.getRange(), S.Context,
3969 Attr.getAttributeSpellingListIndex()));
3971 case AttributeList::AT_StdCall:
3972 D->addAttr(::new (S.Context)
3973 StdCallAttr(Attr.getRange(), S.Context,
3974 Attr.getAttributeSpellingListIndex()));
3976 case AttributeList::AT_ThisCall:
3977 D->addAttr(::new (S.Context)
3978 ThisCallAttr(Attr.getRange(), S.Context,
3979 Attr.getAttributeSpellingListIndex()));
3981 case AttributeList::AT_CDecl:
3982 D->addAttr(::new (S.Context)
3983 CDeclAttr(Attr.getRange(), S.Context,
3984 Attr.getAttributeSpellingListIndex()));
3986 case AttributeList::AT_Pascal:
3987 D->addAttr(::new (S.Context)
3988 PascalAttr(Attr.getRange(), S.Context,
3989 Attr.getAttributeSpellingListIndex()));
3991 case AttributeList::AT_SwiftCall:
3992 D->addAttr(::new (S.Context)
3993 SwiftCallAttr(Attr.getRange(), S.Context,
3994 Attr.getAttributeSpellingListIndex()));
3996 case AttributeList::AT_VectorCall:
3997 D->addAttr(::new (S.Context)
3998 VectorCallAttr(Attr.getRange(), S.Context,
3999 Attr.getAttributeSpellingListIndex()));
4001 case AttributeList::AT_MSABI:
4002 D->addAttr(::new (S.Context)
4003 MSABIAttr(Attr.getRange(), S.Context,
4004 Attr.getAttributeSpellingListIndex()));
4006 case AttributeList::AT_SysVABI:
4007 D->addAttr(::new (S.Context)
4008 SysVABIAttr(Attr.getRange(), S.Context,
4009 Attr.getAttributeSpellingListIndex()));
4011 case AttributeList::AT_RegCall:
4012 D->addAttr(::new (S.Context) RegCallAttr(
4013 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4015 case AttributeList::AT_Pcs: {
4016 PcsAttr::PCSType PCS;
4019 PCS = PcsAttr::AAPCS;
4022 PCS = PcsAttr::AAPCS_VFP;
4025 llvm_unreachable("unexpected calling convention in pcs attribute");
4028 D->addAttr(::new (S.Context)
4029 PcsAttr(Attr.getRange(), S.Context, PCS,
4030 Attr.getAttributeSpellingListIndex()));
4033 case AttributeList::AT_IntelOclBicc:
4034 D->addAttr(::new (S.Context)
4035 IntelOclBiccAttr(Attr.getRange(), S.Context,
4036 Attr.getAttributeSpellingListIndex()));
4038 case AttributeList::AT_PreserveMost:
4039 D->addAttr(::new (S.Context) PreserveMostAttr(
4040 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4042 case AttributeList::AT_PreserveAll:
4043 D->addAttr(::new (S.Context) PreserveAllAttr(
4044 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4047 llvm_unreachable("unexpected attribute kind");
4051 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
4052 const FunctionDecl *FD) {
4053 if (attr.isInvalid())
4056 if (attr.hasProcessingCache()) {
4057 CC = (CallingConv) attr.getProcessingCache();
4061 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
4062 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
4067 // TODO: diagnose uses of these conventions on the wrong target.
4068 switch (attr.getKind()) {
4069 case AttributeList::AT_CDecl: CC = CC_C; break;
4070 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
4071 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
4072 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
4073 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
4074 case AttributeList::AT_SwiftCall: CC = CC_Swift; break;
4075 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
4076 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break;
4077 case AttributeList::AT_MSABI:
4078 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4081 case AttributeList::AT_SysVABI:
4082 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4085 case AttributeList::AT_Pcs: {
4087 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
4091 if (StrRef == "aapcs") {
4094 } else if (StrRef == "aapcs-vfp") {
4100 Diag(attr.getLoc(), diag::err_invalid_pcs);
4103 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
4104 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break;
4105 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break;
4106 default: llvm_unreachable("unexpected attribute kind");
4109 const TargetInfo &TI = Context.getTargetInfo();
4110 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4111 if (A != TargetInfo::CCCR_OK) {
4112 if (A == TargetInfo::CCCR_Warning)
4113 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
4115 // This convention is not valid for the target. Use the default function or
4116 // method calling convention.
4117 bool IsCXXMethod = false, IsVariadic = false;
4119 IsCXXMethod = FD->isCXXInstanceMember();
4120 IsVariadic = FD->isVariadic();
4122 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4125 attr.setProcessingCache((unsigned) CC);
4129 /// Pointer-like types in the default address space.
4130 static bool isValidSwiftContextType(QualType type) {
4131 if (!type->hasPointerRepresentation())
4132 return type->isDependentType();
4133 return type->getPointeeType().getAddressSpace() == 0;
4136 /// Pointers and references in the default address space.
4137 static bool isValidSwiftIndirectResultType(QualType type) {
4138 if (auto ptrType = type->getAs<PointerType>()) {
4139 type = ptrType->getPointeeType();
4140 } else if (auto refType = type->getAs<ReferenceType>()) {
4141 type = refType->getPointeeType();
4143 return type->isDependentType();
4145 return type.getAddressSpace() == 0;
4148 /// Pointers and references to pointers in the default address space.
4149 static bool isValidSwiftErrorResultType(QualType type) {
4150 if (auto ptrType = type->getAs<PointerType>()) {
4151 type = ptrType->getPointeeType();
4152 } else if (auto refType = type->getAs<ReferenceType>()) {
4153 type = refType->getPointeeType();
4155 return type->isDependentType();
4157 if (!type.getQualifiers().empty())
4159 return isValidSwiftContextType(type);
4162 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr,
4164 S.AddParameterABIAttr(attr.getRange(), D, abi,
4165 attr.getAttributeSpellingListIndex());
4168 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4169 unsigned spellingIndex) {
4171 QualType type = cast<ParmVarDecl>(D)->getType();
4173 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4174 if (existingAttr->getABI() != abi) {
4175 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4176 << getParameterABISpelling(abi) << existingAttr;
4177 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4183 case ParameterABI::Ordinary:
4184 llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4186 case ParameterABI::SwiftContext:
4187 if (!isValidSwiftContextType(type)) {
4188 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4189 << getParameterABISpelling(abi)
4190 << /*pointer to pointer */ 0 << type;
4192 D->addAttr(::new (Context)
4193 SwiftContextAttr(range, Context, spellingIndex));
4196 case ParameterABI::SwiftErrorResult:
4197 if (!isValidSwiftErrorResultType(type)) {
4198 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4199 << getParameterABISpelling(abi)
4200 << /*pointer to pointer */ 1 << type;
4202 D->addAttr(::new (Context)
4203 SwiftErrorResultAttr(range, Context, spellingIndex));
4206 case ParameterABI::SwiftIndirectResult:
4207 if (!isValidSwiftIndirectResultType(type)) {
4208 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4209 << getParameterABISpelling(abi)
4210 << /*pointer*/ 0 << type;
4212 D->addAttr(::new (Context)
4213 SwiftIndirectResultAttr(range, Context, spellingIndex));
4216 llvm_unreachable("bad parameter ABI attribute");
4219 /// Checks a regparm attribute, returning true if it is ill-formed and
4220 /// otherwise setting numParams to the appropriate value.
4221 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
4222 if (Attr.isInvalid())
4225 if (!checkAttributeNumArgs(*this, Attr, 1)) {
4231 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
4232 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
4237 if (Context.getTargetInfo().getRegParmMax() == 0) {
4238 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
4239 << NumParamsExpr->getSourceRange();
4245 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4246 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
4247 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4255 // Checks whether an argument of launch_bounds attribute is
4256 // acceptable, performs implicit conversion to Rvalue, and returns
4257 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4258 // and may output an error.
4259 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4260 const CUDALaunchBoundsAttr &Attr,
4261 const unsigned Idx) {
4262 if (S.DiagnoseUnexpandedParameterPack(E))
4265 // Accept template arguments for now as they depend on something else.
4266 // We'll get to check them when they eventually get instantiated.
4267 if (E->isValueDependent())
4271 if (!E->isIntegerConstantExpr(I, S.Context)) {
4272 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4273 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4276 // Make sure we can fit it in 32 bits.
4277 if (!I.isIntN(32)) {
4278 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4279 << 32 << /* Unsigned */ 1;
4283 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4284 << &Attr << Idx << E->getSourceRange();
4286 // We may need to perform implicit conversion of the argument.
4287 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4288 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4289 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4290 assert(!ValArg.isInvalid() &&
4291 "Unexpected PerformCopyInitialization() failure.");
4293 return ValArg.getAs<Expr>();
4296 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4297 Expr *MinBlocks, unsigned SpellingListIndex) {
4298 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4300 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4301 if (MaxThreads == nullptr)
4305 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4306 if (MinBlocks == nullptr)
4310 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4311 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4314 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
4315 const AttributeList &Attr) {
4316 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
4317 !checkAttributeAtMostNumArgs(S, Attr, 2))
4320 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
4321 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
4322 Attr.getAttributeSpellingListIndex());
4325 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4326 const AttributeList &Attr) {
4327 if (!Attr.isArgIdent(0)) {
4328 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4329 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4333 if (!checkAttributeNumArgs(S, Attr, 3))
4336 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4338 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4339 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4340 << Attr.getName() << ExpectedFunctionOrMethod;
4344 uint64_t ArgumentIdx;
4345 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
4349 uint64_t TypeTagIdx;
4350 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
4354 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
4356 // Ensure that buffer has a pointer type.
4357 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
4358 if (!BufferTy->isPointerType()) {
4359 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4360 << Attr.getName() << 0;
4364 D->addAttr(::new (S.Context)
4365 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4366 ArgumentIdx, TypeTagIdx, IsPointer,
4367 Attr.getAttributeSpellingListIndex()));
4370 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4371 const AttributeList &Attr) {
4372 if (!Attr.isArgIdent(0)) {
4373 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4374 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4378 if (!checkAttributeNumArgs(S, Attr, 1))
4381 if (!isa<VarDecl>(D)) {
4382 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4383 << Attr.getName() << ExpectedVariable;
4387 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4388 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4389 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4390 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4392 D->addAttr(::new (S.Context)
4393 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4395 Attr.getLayoutCompatible(),
4396 Attr.getMustBeNull(),
4397 Attr.getAttributeSpellingListIndex()));
4400 //===----------------------------------------------------------------------===//
4401 // Checker-specific attribute handlers.
4402 //===----------------------------------------------------------------------===//
4404 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
4405 return type->isDependentType() ||
4406 type->isObjCRetainableType();
4409 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4410 return type->isDependentType() ||
4411 type->isObjCObjectPointerType() ||
4412 S.Context.isObjCNSObjectType(type);
4415 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4416 return type->isDependentType() ||
4417 type->isPointerType() ||
4418 isValidSubjectOfNSAttribute(S, type);
4421 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4422 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(),
4423 Attr.getKind() == AttributeList::AT_NSConsumed,
4424 /*template instantiation*/ false);
4427 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D,
4428 unsigned spellingIndex, bool isNSConsumed,
4429 bool isTemplateInstantiation) {
4430 ParmVarDecl *param = cast<ParmVarDecl>(D);
4434 typeOK = isValidSubjectOfNSAttribute(*this, param->getType());
4436 typeOK = isValidSubjectOfCFAttribute(*this, param->getType());
4440 // These attributes are normally just advisory, but in ARC, ns_consumed
4441 // is significant. Allow non-dependent code to contain inappropriate
4442 // attributes even in ARC, but require template instantiations to be
4443 // set up correctly.
4444 Diag(D->getLocStart(),
4445 (isTemplateInstantiation && isNSConsumed &&
4446 getLangOpts().ObjCAutoRefCount
4447 ? diag::err_ns_attribute_wrong_parameter_type
4448 : diag::warn_ns_attribute_wrong_parameter_type))
4450 << (isNSConsumed ? "ns_consumed" : "cf_consumed")
4451 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4456 param->addAttr(::new (Context)
4457 NSConsumedAttr(attrRange, Context, spellingIndex));
4459 param->addAttr(::new (Context)
4460 CFConsumedAttr(attrRange, Context, spellingIndex));
4463 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4464 const AttributeList &Attr) {
4465 QualType returnType;
4467 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4468 returnType = MD->getReturnType();
4469 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4470 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4471 return; // ignore: was handled as a type attribute
4472 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4473 returnType = PD->getType();
4474 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4475 returnType = FD->getReturnType();
4476 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
4477 returnType = Param->getType()->getPointeeType();
4478 if (returnType.isNull()) {
4479 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4480 << Attr.getName() << /*pointer-to-CF*/2
4485 AttributeDeclKind ExpectedDeclKind;
4486 switch (Attr.getKind()) {
4487 default: llvm_unreachable("invalid ownership attribute");
4488 case AttributeList::AT_NSReturnsRetained:
4489 case AttributeList::AT_NSReturnsAutoreleased:
4490 case AttributeList::AT_NSReturnsNotRetained:
4491 ExpectedDeclKind = ExpectedFunctionOrMethod;
4494 case AttributeList::AT_CFReturnsRetained:
4495 case AttributeList::AT_CFReturnsNotRetained:
4496 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4499 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4500 << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
4506 switch (Attr.getKind()) {
4507 default: llvm_unreachable("invalid ownership attribute");
4508 case AttributeList::AT_NSReturnsRetained:
4509 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
4513 case AttributeList::AT_NSReturnsAutoreleased:
4514 case AttributeList::AT_NSReturnsNotRetained:
4515 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4519 case AttributeList::AT_CFReturnsRetained:
4520 case AttributeList::AT_CFReturnsNotRetained:
4521 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4527 if (isa<ParmVarDecl>(D)) {
4528 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4529 << Attr.getName() << /*pointer-to-CF*/2
4532 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4537 } SubjectKind = Function;
4538 if (isa<ObjCMethodDecl>(D))
4539 SubjectKind = Method;
4540 else if (isa<ObjCPropertyDecl>(D))
4541 SubjectKind = Property;
4542 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4543 << Attr.getName() << SubjectKind << cf
4549 switch (Attr.getKind()) {
4551 llvm_unreachable("invalid ownership attribute");
4552 case AttributeList::AT_NSReturnsAutoreleased:
4553 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4554 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4556 case AttributeList::AT_CFReturnsNotRetained:
4557 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4558 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4560 case AttributeList::AT_NSReturnsNotRetained:
4561 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4562 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4564 case AttributeList::AT_CFReturnsRetained:
4565 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4566 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4568 case AttributeList::AT_NSReturnsRetained:
4569 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4570 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4575 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4576 const AttributeList &attr) {
4577 const int EP_ObjCMethod = 1;
4578 const int EP_ObjCProperty = 2;
4580 SourceLocation loc = attr.getLoc();
4581 QualType resultType;
4582 if (isa<ObjCMethodDecl>(D))
4583 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4585 resultType = cast<ObjCPropertyDecl>(D)->getType();
4587 if (!resultType->isReferenceType() &&
4588 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4589 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4592 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4593 << /*non-retainable pointer*/ 2;
4595 // Drop the attribute.
4599 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4600 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
4603 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4604 const AttributeList &attr) {
4605 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
4607 DeclContext *DC = method->getDeclContext();
4608 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4609 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4610 << attr.getName() << 0;
4611 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4614 if (method->getMethodFamily() == OMF_dealloc) {
4615 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4616 << attr.getName() << 1;
4620 method->addAttr(::new (S.Context)
4621 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4622 attr.getAttributeSpellingListIndex()));
4625 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
4626 const AttributeList &Attr) {
4627 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
4631 D->addAttr(::new (S.Context)
4632 CFAuditedTransferAttr(Attr.getRange(), S.Context,
4633 Attr.getAttributeSpellingListIndex()));
4636 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
4637 const AttributeList &Attr) {
4638 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
4642 D->addAttr(::new (S.Context)
4643 CFUnknownTransferAttr(Attr.getRange(), S.Context,
4644 Attr.getAttributeSpellingListIndex()));
4647 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4648 const AttributeList &Attr) {
4649 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4652 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4656 // Typedefs only allow objc_bridge(id) and have some additional checking.
4657 if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
4658 if (!Parm->Ident->isStr("id")) {
4659 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
4664 // Only allow 'cv void *'.
4665 QualType T = TD->getUnderlyingType();
4666 if (!T->isVoidPointerType()) {
4667 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4672 D->addAttr(::new (S.Context)
4673 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
4674 Attr.getAttributeSpellingListIndex()));
4677 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
4678 const AttributeList &Attr) {
4679 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
4682 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4686 D->addAttr(::new (S.Context)
4687 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
4688 Attr.getAttributeSpellingListIndex()));
4691 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
4692 const AttributeList &Attr) {
4693 IdentifierInfo *RelatedClass =
4694 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
4695 if (!RelatedClass) {
4696 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
4699 IdentifierInfo *ClassMethod =
4700 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
4701 IdentifierInfo *InstanceMethod =
4702 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
4703 D->addAttr(::new (S.Context)
4704 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
4705 ClassMethod, InstanceMethod,
4706 Attr.getAttributeSpellingListIndex()));
4709 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4710 const AttributeList &Attr) {
4711 ObjCInterfaceDecl *IFace;
4712 if (ObjCCategoryDecl *CatDecl =
4713 dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4714 IFace = CatDecl->getClassInterface();
4716 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4721 IFace->setHasDesignatedInitializers();
4722 D->addAttr(::new (S.Context)
4723 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
4724 Attr.getAttributeSpellingListIndex()));
4727 static void handleObjCRuntimeName(Sema &S, Decl *D,
4728 const AttributeList &Attr) {
4729 StringRef MetaDataName;
4730 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
4732 D->addAttr(::new (S.Context)
4733 ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
4735 Attr.getAttributeSpellingListIndex()));
4738 // When a user wants to use objc_boxable with a union or struct
4739 // but they don't have access to the declaration (legacy/third-party code)
4740 // then they can 'enable' this feature with a typedef:
4741 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4742 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
4743 bool notify = false;
4745 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4746 if (RD && RD->getDefinition()) {
4747 RD = RD->getDefinition();
4752 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4753 ObjCBoxableAttr(Attr.getRange(), S.Context,
4754 Attr.getAttributeSpellingListIndex());
4755 RD->addAttr(BoxableAttr);
4757 // we need to notify ASTReader/ASTWriter about
4758 // modification of existing declaration
4759 if (ASTMutationListener *L = S.getASTMutationListener())
4760 L->AddedAttributeToRecord(BoxableAttr, RD);
4765 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4766 const AttributeList &Attr) {
4767 if (hasDeclarator(D)) return;
4769 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4770 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4773 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4774 const AttributeList &Attr) {
4775 ValueDecl *vd = cast<ValueDecl>(D);
4776 QualType type = vd->getType();
4778 if (!type->isDependentType() &&
4779 !type->isObjCLifetimeType()) {
4780 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4785 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4787 // If we have no lifetime yet, check the lifetime we're presumably
4789 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4790 lifetime = type->getObjCARCImplicitLifetime();
4793 case Qualifiers::OCL_None:
4794 assert(type->isDependentType() &&
4795 "didn't infer lifetime for non-dependent type?");
4798 case Qualifiers::OCL_Weak: // meaningful
4799 case Qualifiers::OCL_Strong: // meaningful
4802 case Qualifiers::OCL_ExplicitNone:
4803 case Qualifiers::OCL_Autoreleasing:
4804 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4805 << (lifetime == Qualifiers::OCL_Autoreleasing);
4809 D->addAttr(::new (S.Context)
4810 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4811 Attr.getAttributeSpellingListIndex()));
4814 //===----------------------------------------------------------------------===//
4815 // Microsoft specific attribute handlers.
4816 //===----------------------------------------------------------------------===//
4818 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4819 unsigned AttrSpellingListIndex, StringRef Uuid) {
4820 if (const auto *UA = D->getAttr<UuidAttr>()) {
4821 if (UA->getGuid().equals_lower(Uuid))
4823 Diag(UA->getLocation(), diag::err_mismatched_uuid);
4824 Diag(Range.getBegin(), diag::note_previous_uuid);
4825 D->dropAttr<UuidAttr>();
4828 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
4831 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4832 if (!S.LangOpts.CPlusPlus) {
4833 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4834 << Attr.getName() << AttributeLangSupport::C;
4839 SourceLocation LiteralLoc;
4840 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4843 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4844 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4845 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4846 StrRef = StrRef.drop_front().drop_back();
4848 // Validate GUID length.
4849 if (StrRef.size() != 36) {
4850 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4854 for (unsigned i = 0; i < 36; ++i) {
4855 if (i == 8 || i == 13 || i == 18 || i == 23) {
4856 if (StrRef[i] != '-') {
4857 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4860 } else if (!isHexDigit(StrRef[i])) {
4861 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4866 UuidAttr *UA = S.mergeUuidAttr(D, Attr.getRange(),
4867 Attr.getAttributeSpellingListIndex(), StrRef);
4872 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4873 if (!S.LangOpts.CPlusPlus) {
4874 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
4875 << Attr.getName() << AttributeLangSupport::C;
4878 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
4879 D, Attr.getRange(), /*BestCase=*/true,
4880 Attr.getAttributeSpellingListIndex(),
4881 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
4884 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
4888 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
4889 const AttributeList &Attr) {
4890 VarDecl *VD = cast<VarDecl>(D);
4891 if (!S.Context.getTargetInfo().isTLSSupported()) {
4892 S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
4895 if (VD->getTSCSpec() != TSCS_unspecified) {
4896 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
4899 if (VD->hasLocalStorage()) {
4900 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
4903 VD->addAttr(::new (S.Context) ThreadAttr(
4904 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
4907 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4908 SmallVector<StringRef, 4> Tags;
4909 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
4911 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag))
4913 Tags.push_back(Tag);
4916 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
4917 if (!NS->isInline()) {
4918 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
4921 if (NS->isAnonymousNamespace()) {
4922 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
4925 if (Attr.getNumArgs() == 0)
4926 Tags.push_back(NS->getName());
4927 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
4930 // Store tags sorted and without duplicates.
4931 std::sort(Tags.begin(), Tags.end());
4932 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
4934 D->addAttr(::new (S.Context)
4935 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(),
4936 Attr.getAttributeSpellingListIndex()));
4939 static void handleARMInterruptAttr(Sema &S, Decl *D,
4940 const AttributeList &Attr) {
4941 // Check the attribute arguments.
4942 if (Attr.getNumArgs() > 1) {
4943 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
4944 << Attr.getName() << 1;
4949 SourceLocation ArgLoc;
4951 if (Attr.getNumArgs() == 0)
4953 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
4956 ARMInterruptAttr::InterruptType Kind;
4957 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
4958 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
4959 << Attr.getName() << Str << ArgLoc;
4963 unsigned Index = Attr.getAttributeSpellingListIndex();
4964 D->addAttr(::new (S.Context)
4965 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
4968 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
4969 const AttributeList &Attr) {
4970 if (!checkAttributeNumArgs(S, Attr, 1))
4973 if (!Attr.isArgExpr(0)) {
4974 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
4975 << AANT_ArgumentIntegerConstant;
4979 // FIXME: Check for decl - it should be void ()(void).
4981 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4982 llvm::APSInt NumParams(32);
4983 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
4984 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4985 << Attr.getName() << AANT_ArgumentIntegerConstant
4986 << NumParamsExpr->getSourceRange();
4990 unsigned Num = NumParams.getLimitedValue(255);
4991 if ((Num & 1) || Num > 30) {
4992 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
4993 << Attr.getName() << (int)NumParams.getSExtValue()
4994 << NumParamsExpr->getSourceRange();
4998 D->addAttr(::new (S.Context)
4999 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num,
5000 Attr.getAttributeSpellingListIndex()));
5001 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5004 static void handleMipsInterruptAttr(Sema &S, Decl *D,
5005 const AttributeList &Attr) {
5006 // Only one optional argument permitted.
5007 if (Attr.getNumArgs() > 1) {
5008 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
5009 << Attr.getName() << 1;
5014 SourceLocation ArgLoc;
5016 if (Attr.getNumArgs() == 0)
5018 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
5021 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5022 // a) Must be a function.
5023 // b) Must have no parameters.
5024 // c) Must have the 'void' return type.
5025 // d) Cannot have the 'mips16' attribute, as that instruction set
5026 // lacks the 'eret' instruction.
5027 // e) The attribute itself must either have no argument or one of the
5028 // valid interrupt types, see [MipsInterruptDocs].
5030 if (!isFunctionOrMethod(D)) {
5031 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5032 << "'interrupt'" << ExpectedFunctionOrMethod;
5036 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5037 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5042 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5043 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5048 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(),
5052 MipsInterruptAttr::InterruptType Kind;
5053 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5054 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
5055 << Attr.getName() << "'" + std::string(Str) + "'";
5059 D->addAttr(::new (S.Context) MipsInterruptAttr(
5060 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex()));
5063 static void handleAnyX86InterruptAttr(Sema &S, Decl *D,
5064 const AttributeList &Attr) {
5065 // Semantic checks for a function with the 'interrupt' attribute.
5066 // a) Must be a function.
5067 // b) Must have the 'void' return type.
5068 // c) Must take 1 or 2 arguments.
5069 // d) The 1st argument must be a pointer.
5070 // e) The 2nd argument (if any) must be an unsigned integer.
5071 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5072 CXXMethodDecl::isStaticOverloadedOperator(
5073 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5074 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5075 << Attr.getName() << ExpectedFunctionWithProtoType;
5078 // Interrupt handler must have void return type.
5079 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5080 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5081 diag::err_anyx86_interrupt_attribute)
5082 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5088 // Interrupt handler must have 1 or 2 parameters.
5089 unsigned NumParams = getFunctionOrMethodNumParams(D);
5090 if (NumParams < 1 || NumParams > 2) {
5091 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5092 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5098 // The first argument must be a pointer.
5099 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5100 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5101 diag::err_anyx86_interrupt_attribute)
5102 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5108 // The second argument, if present, must be an unsigned integer.
5110 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5113 if (NumParams == 2 &&
5114 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5115 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5116 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5117 diag::err_anyx86_interrupt_attribute)
5118 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5121 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5124 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5125 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex()));
5126 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5129 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5130 // Dispatch the interrupt attribute based on the current target.
5131 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5132 case llvm::Triple::msp430:
5133 handleMSP430InterruptAttr(S, D, Attr);
5135 case llvm::Triple::mipsel:
5136 case llvm::Triple::mips:
5137 handleMipsInterruptAttr(S, D, Attr);
5139 case llvm::Triple::x86:
5140 case llvm::Triple::x86_64:
5141 handleAnyX86InterruptAttr(S, D, Attr);
5144 handleARMInterruptAttr(S, D, Attr);
5149 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5150 const AttributeList &Attr) {
5152 Expr *MinExpr = Attr.getArgAsExpr(0);
5153 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5157 Expr *MaxExpr = Attr.getArgAsExpr(1);
5158 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5161 if (Min == 0 && Max != 0) {
5162 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5163 << Attr.getName() << 0;
5167 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5168 << Attr.getName() << 1;
5172 D->addAttr(::new (S.Context)
5173 AMDGPUFlatWorkGroupSizeAttr(Attr.getLoc(), S.Context, Min, Max,
5174 Attr.getAttributeSpellingListIndex()));
5177 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D,
5178 const AttributeList &Attr) {
5180 Expr *MinExpr = Attr.getArgAsExpr(0);
5181 if (!checkUInt32Argument(S, Attr, MinExpr, Min))
5185 if (Attr.getNumArgs() == 2) {
5186 Expr *MaxExpr = Attr.getArgAsExpr(1);
5187 if (!checkUInt32Argument(S, Attr, MaxExpr, Max))
5191 if (Min == 0 && Max != 0) {
5192 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5193 << Attr.getName() << 0;
5196 if (Max != 0 && Min > Max) {
5197 S.Diag(Attr.getLoc(), diag::err_attribute_argument_invalid)
5198 << Attr.getName() << 1;
5202 D->addAttr(::new (S.Context)
5203 AMDGPUWavesPerEUAttr(Attr.getLoc(), S.Context, Min, Max,
5204 Attr.getAttributeSpellingListIndex()));
5207 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D,
5208 const AttributeList &Attr) {
5209 uint32_t NumSGPR = 0;
5210 Expr *NumSGPRExpr = Attr.getArgAsExpr(0);
5211 if (!checkUInt32Argument(S, Attr, NumSGPRExpr, NumSGPR))
5214 D->addAttr(::new (S.Context)
5215 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, NumSGPR,
5216 Attr.getAttributeSpellingListIndex()));
5219 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D,
5220 const AttributeList &Attr) {
5221 uint32_t NumVGPR = 0;
5222 Expr *NumVGPRExpr = Attr.getArgAsExpr(0);
5223 if (!checkUInt32Argument(S, Attr, NumVGPRExpr, NumVGPR))
5226 D->addAttr(::new (S.Context)
5227 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, NumVGPR,
5228 Attr.getAttributeSpellingListIndex()));
5231 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5232 const AttributeList& Attr) {
5233 // If we try to apply it to a function pointer, don't warn, but don't
5234 // do anything, either. It doesn't matter anyway, because there's nothing
5235 // special about calling a force_align_arg_pointer function.
5236 ValueDecl *VD = dyn_cast<ValueDecl>(D);
5237 if (VD && VD->getType()->isFunctionPointerType())
5239 // Also don't warn on function pointer typedefs.
5240 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
5241 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5242 TD->getUnderlyingType()->isFunctionType()))
5244 // Attribute can only be applied to function types.
5245 if (!isa<FunctionDecl>(D)) {
5246 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
5247 << Attr.getName() << /* function */0;
5251 D->addAttr(::new (S.Context)
5252 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context,
5253 Attr.getAttributeSpellingListIndex()));
5256 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) {
5258 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5259 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version))
5262 // TODO: Investigate what happens with the next major version of MSVC.
5263 if (Version != LangOptions::MSVC2015) {
5264 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
5265 << Attr.getName() << Version << VersionExpr->getSourceRange();
5269 D->addAttr(::new (S.Context)
5270 LayoutVersionAttr(Attr.getRange(), S.Context, Version,
5271 Attr.getAttributeSpellingListIndex()));
5274 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5275 unsigned AttrSpellingListIndex) {
5276 if (D->hasAttr<DLLExportAttr>()) {
5277 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5281 if (D->hasAttr<DLLImportAttr>())
5284 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5287 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5288 unsigned AttrSpellingListIndex) {
5289 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5290 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5291 D->dropAttr<DLLImportAttr>();
5294 if (D->hasAttr<DLLExportAttr>())
5297 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5300 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) {
5301 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5302 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5303 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5308 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5309 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport &&
5310 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5311 // MinGW doesn't allow dllimport on inline functions.
5312 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5318 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5319 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5320 MD->getParent()->isLambda()) {
5321 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5326 unsigned Index = A.getAttributeSpellingListIndex();
5327 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport
5328 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5329 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5331 D->addAttr(NewAttr);
5335 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5336 unsigned AttrSpellingListIndex,
5337 MSInheritanceAttr::Spelling SemanticSpelling) {
5338 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5339 if (IA->getSemanticSpelling() == SemanticSpelling)
5341 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5342 << 1 /*previous declaration*/;
5343 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5344 D->dropAttr<MSInheritanceAttr>();
5347 CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
5348 if (RD->hasDefinition()) {
5349 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5350 SemanticSpelling)) {
5354 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5355 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5356 << 1 /*partial specialization*/;
5359 if (RD->getDescribedClassTemplate()) {
5360 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5361 << 0 /*primary template*/;
5366 return ::new (Context)
5367 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5370 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5371 // The capability attributes take a single string parameter for the name of
5372 // the capability they represent. The lockable attribute does not take any
5373 // parameters. However, semantically, both attributes represent the same
5374 // concept, and so they use the same semantic attribute. Eventually, the
5375 // lockable attribute will be removed.
5377 // For backward compatibility, any capability which has no specified string
5378 // literal will be considered a "mutex."
5379 StringRef N("mutex");
5380 SourceLocation LiteralLoc;
5381 if (Attr.getKind() == AttributeList::AT_Capability &&
5382 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc))
5385 // Currently, there are only two names allowed for a capability: role and
5386 // mutex (case insensitive). Diagnose other capability names.
5387 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5388 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5390 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N,
5391 Attr.getAttributeSpellingListIndex()));
5394 static void handleAssertCapabilityAttr(Sema &S, Decl *D,
5395 const AttributeList &Attr) {
5396 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context,
5397 Attr.getArgAsExpr(0),
5398 Attr.getAttributeSpellingListIndex()));
5401 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5402 const AttributeList &Attr) {
5403 SmallVector<Expr*, 1> Args;
5404 if (!checkLockFunAttrCommon(S, D, Attr, Args))
5407 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(),
5409 Args.data(), Args.size(),
5410 Attr.getAttributeSpellingListIndex()));
5413 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5414 const AttributeList &Attr) {
5415 SmallVector<Expr*, 2> Args;
5416 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
5419 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(),
5421 Attr.getArgAsExpr(0),
5424 Attr.getAttributeSpellingListIndex()));
5427 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5428 const AttributeList &Attr) {
5429 // Check that all arguments are lockable objects.
5430 SmallVector<Expr *, 1> Args;
5431 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true);
5433 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5434 Attr.getRange(), S.Context, Args.data(), Args.size(),
5435 Attr.getAttributeSpellingListIndex()));
5438 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5439 const AttributeList &Attr) {
5440 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5443 // check that all arguments are lockable objects
5444 SmallVector<Expr*, 1> Args;
5445 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
5449 RequiresCapabilityAttr *RCA = ::new (S.Context)
5450 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(),
5451 Args.size(), Attr.getAttributeSpellingListIndex());
5456 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5457 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5458 if (NSD->isAnonymousNamespace()) {
5459 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace);
5460 // Do not want to attach the attribute to the namespace because that will
5461 // cause confusing diagnostic reports for uses of declarations within the
5467 // Handle the cases where the attribute has a text message.
5468 StringRef Str, Replacement;
5469 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) &&
5470 !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
5473 // Only support a single optional message for Declspec and CXX11.
5474 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute())
5475 checkAttributeAtMostNumArgs(S, Attr, 1);
5476 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) &&
5477 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement))
5480 if (!S.getLangOpts().CPlusPlus14)
5481 if (Attr.isCXX11Attribute() &&
5482 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu")))
5483 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName();
5485 D->addAttr(::new (S.Context)
5486 DeprecatedAttr(Attr.getRange(), S.Context, Str, Replacement,
5487 Attr.getAttributeSpellingListIndex()));
5490 static bool isGlobalVar(const Decl *D) {
5491 if (const auto *S = dyn_cast<VarDecl>(D))
5492 return S->hasGlobalStorage();
5496 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5497 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
5500 std::vector<StringRef> Sanitizers;
5502 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) {
5503 StringRef SanitizerName;
5504 SourceLocation LiteralLoc;
5506 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc))
5509 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5510 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5511 else if (isGlobalVar(D) && SanitizerName != "address")
5512 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5513 << Attr.getName() << ExpectedFunctionOrMethod;
5514 Sanitizers.push_back(SanitizerName);
5517 D->addAttr(::new (S.Context) NoSanitizeAttr(
5518 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5519 Attr.getAttributeSpellingListIndex()));
5522 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5523 const AttributeList &Attr) {
5524 StringRef AttrName = Attr.getName()->getName();
5525 normalizeName(AttrName);
5526 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5527 .Case("no_address_safety_analysis", "address")
5528 .Case("no_sanitize_address", "address")
5529 .Case("no_sanitize_thread", "thread")
5530 .Case("no_sanitize_memory", "memory");
5531 if (isGlobalVar(D) && SanitizerName != "address")
5532 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5533 << Attr.getName() << ExpectedFunction;
5534 D->addAttr(::new (S.Context)
5535 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1,
5536 Attr.getAttributeSpellingListIndex()));
5539 static void handleInternalLinkageAttr(Sema &S, Decl *D,
5540 const AttributeList &Attr) {
5541 if (InternalLinkageAttr *Internal =
5542 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(),
5543 Attr.getAttributeSpellingListIndex()))
5544 D->addAttr(Internal);
5547 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) {
5548 if (S.LangOpts.OpenCLVersion != 200)
5549 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version)
5550 << Attr.getName() << "2.0" << 0;
5552 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5553 << Attr.getName() << "2.0";
5556 /// Handles semantic checking for features that are common to all attributes,
5557 /// such as checking whether a parameter was properly specified, or the correct
5558 /// number of arguments were passed, etc.
5559 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
5560 const AttributeList &Attr) {
5561 // Several attributes carry different semantics than the parsing requires, so
5562 // those are opted out of the common handling.
5564 // We also bail on unknown and ignored attributes because those are handled
5565 // as part of the target-specific handling logic.
5566 if (Attr.hasCustomParsing() ||
5567 Attr.getKind() == AttributeList::UnknownAttribute)
5570 // Check whether the attribute requires specific language extensions to be
5572 if (!Attr.diagnoseLangOpts(S))
5575 if (Attr.getMinArgs() == Attr.getMaxArgs()) {
5576 // If there are no optional arguments, then checking for the argument count
5578 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
5581 // There are optional arguments, so checking is slightly more involved.
5582 if (Attr.getMinArgs() &&
5583 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs()))
5585 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() &&
5586 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs()))
5590 // Check whether the attribute appertains to the given subject.
5591 if (!Attr.diagnoseAppertainsTo(S, D))
5597 static void handleOpenCLAccessAttr(Sema &S, Decl *D,
5598 const AttributeList &Attr) {
5599 if (D->isInvalidDecl())
5602 // Check if there is only one access qualifier.
5603 if (D->hasAttr<OpenCLAccessAttr>()) {
5604 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5605 << D->getSourceRange();
5606 D->setInvalidDecl(true);
5610 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5611 // image object can be read and written.
5612 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5613 // object. Using the read_write (or __read_write) qualifier with the pipe
5614 // qualifier is a compilation error.
5615 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) {
5616 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5617 if (Attr.getName()->getName().find("read_write") != StringRef::npos) {
5618 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5619 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write)
5620 << Attr.getName() << PDecl->getType() << DeclTy->isImageType();
5621 D->setInvalidDecl(true);
5627 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5628 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
5631 //===----------------------------------------------------------------------===//
5632 // Top Level Sema Entry Points
5633 //===----------------------------------------------------------------------===//
5635 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5636 /// the attribute applies to decls. If the attribute is a type attribute, just
5637 /// silently ignore it if a GNU attribute.
5638 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5639 const AttributeList &Attr,
5640 bool IncludeCXX11Attributes) {
5641 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute)
5644 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5646 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
5649 // Unknown attributes are automatically warned on. Target-specific attributes
5650 // which do not apply to the current target architecture are treated as
5651 // though they were unknown attributes.
5652 if (Attr.getKind() == AttributeList::UnknownAttribute ||
5653 !Attr.existsInTarget(S.Context.getTargetInfo())) {
5654 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute()
5655 ? diag::warn_unhandled_ms_attribute_ignored
5656 : diag::warn_unknown_attribute_ignored)
5661 if (handleCommonAttributeFeatures(S, scope, D, Attr))
5664 switch (Attr.getKind()) {
5666 if (!Attr.isStmtAttr()) {
5667 // Type attributes are handled elsewhere; silently move on.
5668 assert(Attr.isTypeAttr() && "Non-type attribute not handled");
5671 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5672 << Attr.getName() << D->getLocation();
5674 case AttributeList::AT_Interrupt:
5675 handleInterruptAttr(S, D, Attr);
5677 case AttributeList::AT_X86ForceAlignArgPointer:
5678 handleX86ForceAlignArgPointerAttr(S, D, Attr);
5680 case AttributeList::AT_DLLExport:
5681 case AttributeList::AT_DLLImport:
5682 handleDLLAttr(S, D, Attr);
5684 case AttributeList::AT_Mips16:
5685 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D,
5688 case AttributeList::AT_NoMips16:
5689 handleSimpleAttribute<NoMips16Attr>(S, D, Attr);
5691 case AttributeList::AT_AMDGPUFlatWorkGroupSize:
5692 handleAMDGPUFlatWorkGroupSizeAttr(S, D, Attr);
5694 case AttributeList::AT_AMDGPUWavesPerEU:
5695 handleAMDGPUWavesPerEUAttr(S, D, Attr);
5697 case AttributeList::AT_AMDGPUNumSGPR:
5698 handleAMDGPUNumSGPRAttr(S, D, Attr);
5700 case AttributeList::AT_AMDGPUNumVGPR:
5701 handleAMDGPUNumVGPRAttr(S, D, Attr);
5703 case AttributeList::AT_IBAction:
5704 handleSimpleAttribute<IBActionAttr>(S, D, Attr);
5706 case AttributeList::AT_IBOutlet:
5707 handleIBOutlet(S, D, Attr);
5709 case AttributeList::AT_IBOutletCollection:
5710 handleIBOutletCollection(S, D, Attr);
5712 case AttributeList::AT_IFunc:
5713 handleIFuncAttr(S, D, Attr);
5715 case AttributeList::AT_Alias:
5716 handleAliasAttr(S, D, Attr);
5718 case AttributeList::AT_Aligned:
5719 handleAlignedAttr(S, D, Attr);
5721 case AttributeList::AT_AlignValue:
5722 handleAlignValueAttr(S, D, Attr);
5724 case AttributeList::AT_AllocSize:
5725 handleAllocSizeAttr(S, D, Attr);
5727 case AttributeList::AT_AlwaysInline:
5728 handleAlwaysInlineAttr(S, D, Attr);
5730 case AttributeList::AT_AnalyzerNoReturn:
5731 handleAnalyzerNoReturnAttr(S, D, Attr);
5733 case AttributeList::AT_TLSModel:
5734 handleTLSModelAttr(S, D, Attr);
5736 case AttributeList::AT_Annotate:
5737 handleAnnotateAttr(S, D, Attr);
5739 case AttributeList::AT_Availability:
5740 handleAvailabilityAttr(S, D, Attr);
5742 case AttributeList::AT_CarriesDependency:
5743 handleDependencyAttr(S, scope, D, Attr);
5745 case AttributeList::AT_Common:
5746 handleCommonAttr(S, D, Attr);
5748 case AttributeList::AT_CUDAConstant:
5749 handleConstantAttr(S, D, Attr);
5751 case AttributeList::AT_PassObjectSize:
5752 handlePassObjectSizeAttr(S, D, Attr);
5754 case AttributeList::AT_Constructor:
5755 handleConstructorAttr(S, D, Attr);
5757 case AttributeList::AT_CXX11NoReturn:
5758 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr);
5760 case AttributeList::AT_Deprecated:
5761 handleDeprecatedAttr(S, D, Attr);
5763 case AttributeList::AT_Destructor:
5764 handleDestructorAttr(S, D, Attr);
5766 case AttributeList::AT_EnableIf:
5767 handleEnableIfAttr(S, D, Attr);
5769 case AttributeList::AT_DiagnoseIf:
5770 handleDiagnoseIfAttr(S, D, Attr);
5772 case AttributeList::AT_ExtVectorType:
5773 handleExtVectorTypeAttr(S, scope, D, Attr);
5775 case AttributeList::AT_MinSize:
5776 handleMinSizeAttr(S, D, Attr);
5778 case AttributeList::AT_OptimizeNone:
5779 handleOptimizeNoneAttr(S, D, Attr);
5781 case AttributeList::AT_FlagEnum:
5782 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr);
5784 case AttributeList::AT_Flatten:
5785 handleSimpleAttribute<FlattenAttr>(S, D, Attr);
5787 case AttributeList::AT_Format:
5788 handleFormatAttr(S, D, Attr);
5790 case AttributeList::AT_FormatArg:
5791 handleFormatArgAttr(S, D, Attr);
5793 case AttributeList::AT_CUDAGlobal:
5794 handleGlobalAttr(S, D, Attr);
5796 case AttributeList::AT_CUDADevice:
5797 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
5800 case AttributeList::AT_CUDAHost:
5801 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D,
5804 case AttributeList::AT_GNUInline:
5805 handleGNUInlineAttr(S, D, Attr);
5807 case AttributeList::AT_CUDALaunchBounds:
5808 handleLaunchBoundsAttr(S, D, Attr);
5810 case AttributeList::AT_Restrict:
5811 handleRestrictAttr(S, D, Attr);
5813 case AttributeList::AT_MayAlias:
5814 handleSimpleAttribute<MayAliasAttr>(S, D, Attr);
5816 case AttributeList::AT_Mode:
5817 handleModeAttr(S, D, Attr);
5819 case AttributeList::AT_NoAlias:
5820 handleSimpleAttribute<NoAliasAttr>(S, D, Attr);
5822 case AttributeList::AT_NoCommon:
5823 handleSimpleAttribute<NoCommonAttr>(S, D, Attr);
5825 case AttributeList::AT_NoSplitStack:
5826 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr);
5828 case AttributeList::AT_NonNull:
5829 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D))
5830 handleNonNullAttrParameter(S, PVD, Attr);
5832 handleNonNullAttr(S, D, Attr);
5834 case AttributeList::AT_ReturnsNonNull:
5835 handleReturnsNonNullAttr(S, D, Attr);
5837 case AttributeList::AT_AssumeAligned:
5838 handleAssumeAlignedAttr(S, D, Attr);
5840 case AttributeList::AT_Overloadable:
5841 handleSimpleAttribute<OverloadableAttr>(S, D, Attr);
5843 case AttributeList::AT_Ownership:
5844 handleOwnershipAttr(S, D, Attr);
5846 case AttributeList::AT_Cold:
5847 handleColdAttr(S, D, Attr);
5849 case AttributeList::AT_Hot:
5850 handleHotAttr(S, D, Attr);
5852 case AttributeList::AT_Naked:
5853 handleNakedAttr(S, D, Attr);
5855 case AttributeList::AT_NoReturn:
5856 handleNoReturnAttr(S, D, Attr);
5858 case AttributeList::AT_NoThrow:
5859 handleSimpleAttribute<NoThrowAttr>(S, D, Attr);
5861 case AttributeList::AT_CUDAShared:
5862 handleSharedAttr(S, D, Attr);
5864 case AttributeList::AT_VecReturn:
5865 handleVecReturnAttr(S, D, Attr);
5867 case AttributeList::AT_ObjCOwnership:
5868 handleObjCOwnershipAttr(S, D, Attr);
5870 case AttributeList::AT_ObjCPreciseLifetime:
5871 handleObjCPreciseLifetimeAttr(S, D, Attr);
5873 case AttributeList::AT_ObjCReturnsInnerPointer:
5874 handleObjCReturnsInnerPointerAttr(S, D, Attr);
5876 case AttributeList::AT_ObjCRequiresSuper:
5877 handleObjCRequiresSuperAttr(S, D, Attr);
5879 case AttributeList::AT_ObjCBridge:
5880 handleObjCBridgeAttr(S, scope, D, Attr);
5882 case AttributeList::AT_ObjCBridgeMutable:
5883 handleObjCBridgeMutableAttr(S, scope, D, Attr);
5885 case AttributeList::AT_ObjCBridgeRelated:
5886 handleObjCBridgeRelatedAttr(S, scope, D, Attr);
5888 case AttributeList::AT_ObjCDesignatedInitializer:
5889 handleObjCDesignatedInitializer(S, D, Attr);
5891 case AttributeList::AT_ObjCRuntimeName:
5892 handleObjCRuntimeName(S, D, Attr);
5894 case AttributeList::AT_ObjCRuntimeVisible:
5895 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr);
5897 case AttributeList::AT_ObjCBoxable:
5898 handleObjCBoxable(S, D, Attr);
5900 case AttributeList::AT_CFAuditedTransfer:
5901 handleCFAuditedTransferAttr(S, D, Attr);
5903 case AttributeList::AT_CFUnknownTransfer:
5904 handleCFUnknownTransferAttr(S, D, Attr);
5906 case AttributeList::AT_CFConsumed:
5907 case AttributeList::AT_NSConsumed:
5908 handleNSConsumedAttr(S, D, Attr);
5910 case AttributeList::AT_NSConsumesSelf:
5911 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr);
5913 case AttributeList::AT_NSReturnsAutoreleased:
5914 case AttributeList::AT_NSReturnsNotRetained:
5915 case AttributeList::AT_CFReturnsNotRetained:
5916 case AttributeList::AT_NSReturnsRetained:
5917 case AttributeList::AT_CFReturnsRetained:
5918 handleNSReturnsRetainedAttr(S, D, Attr);
5920 case AttributeList::AT_WorkGroupSizeHint:
5921 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr);
5923 case AttributeList::AT_ReqdWorkGroupSize:
5924 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr);
5926 case AttributeList::AT_VecTypeHint:
5927 handleVecTypeHint(S, D, Attr);
5929 case AttributeList::AT_RequireConstantInit:
5930 handleSimpleAttribute<RequireConstantInitAttr>(S, D, Attr);
5932 case AttributeList::AT_InitPriority:
5933 handleInitPriorityAttr(S, D, Attr);
5935 case AttributeList::AT_Packed:
5936 handlePackedAttr(S, D, Attr);
5938 case AttributeList::AT_Section:
5939 handleSectionAttr(S, D, Attr);
5941 case AttributeList::AT_Target:
5942 handleTargetAttr(S, D, Attr);
5944 case AttributeList::AT_Unavailable:
5945 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
5947 case AttributeList::AT_ArcWeakrefUnavailable:
5948 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr);
5950 case AttributeList::AT_ObjCRootClass:
5951 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr);
5953 case AttributeList::AT_ObjCSubclassingRestricted:
5954 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, Attr);
5956 case AttributeList::AT_ObjCExplicitProtocolImpl:
5957 handleObjCSuppresProtocolAttr(S, D, Attr);
5959 case AttributeList::AT_ObjCRequiresPropertyDefs:
5960 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr);
5962 case AttributeList::AT_Unused:
5963 handleUnusedAttr(S, D, Attr);
5965 case AttributeList::AT_ReturnsTwice:
5966 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr);
5968 case AttributeList::AT_NotTailCalled:
5969 handleNotTailCalledAttr(S, D, Attr);
5971 case AttributeList::AT_DisableTailCalls:
5972 handleDisableTailCallsAttr(S, D, Attr);
5974 case AttributeList::AT_Used:
5975 handleUsedAttr(S, D, Attr);
5977 case AttributeList::AT_Visibility:
5978 handleVisibilityAttr(S, D, Attr, false);
5980 case AttributeList::AT_TypeVisibility:
5981 handleVisibilityAttr(S, D, Attr, true);
5983 case AttributeList::AT_WarnUnused:
5984 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr);
5986 case AttributeList::AT_WarnUnusedResult:
5987 handleWarnUnusedResult(S, D, Attr);
5989 case AttributeList::AT_Weak:
5990 handleSimpleAttribute<WeakAttr>(S, D, Attr);
5992 case AttributeList::AT_WeakRef:
5993 handleWeakRefAttr(S, D, Attr);
5995 case AttributeList::AT_WeakImport:
5996 handleWeakImportAttr(S, D, Attr);
5998 case AttributeList::AT_TransparentUnion:
5999 handleTransparentUnionAttr(S, D, Attr);
6001 case AttributeList::AT_ObjCException:
6002 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr);
6004 case AttributeList::AT_ObjCMethodFamily:
6005 handleObjCMethodFamilyAttr(S, D, Attr);
6007 case AttributeList::AT_ObjCNSObject:
6008 handleObjCNSObject(S, D, Attr);
6010 case AttributeList::AT_ObjCIndependentClass:
6011 handleObjCIndependentClass(S, D, Attr);
6013 case AttributeList::AT_Blocks:
6014 handleBlocksAttr(S, D, Attr);
6016 case AttributeList::AT_Sentinel:
6017 handleSentinelAttr(S, D, Attr);
6019 case AttributeList::AT_Const:
6020 handleSimpleAttribute<ConstAttr>(S, D, Attr);
6022 case AttributeList::AT_Pure:
6023 handleSimpleAttribute<PureAttr>(S, D, Attr);
6025 case AttributeList::AT_Cleanup:
6026 handleCleanupAttr(S, D, Attr);
6028 case AttributeList::AT_NoDebug:
6029 handleNoDebugAttr(S, D, Attr);
6031 case AttributeList::AT_NoDuplicate:
6032 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr);
6034 case AttributeList::AT_Convergent:
6035 handleSimpleAttribute<ConvergentAttr>(S, D, Attr);
6037 case AttributeList::AT_NoInline:
6038 handleSimpleAttribute<NoInlineAttr>(S, D, Attr);
6040 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
6041 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr);
6043 case AttributeList::AT_StdCall:
6044 case AttributeList::AT_CDecl:
6045 case AttributeList::AT_FastCall:
6046 case AttributeList::AT_ThisCall:
6047 case AttributeList::AT_Pascal:
6048 case AttributeList::AT_RegCall:
6049 case AttributeList::AT_SwiftCall:
6050 case AttributeList::AT_VectorCall:
6051 case AttributeList::AT_MSABI:
6052 case AttributeList::AT_SysVABI:
6053 case AttributeList::AT_Pcs:
6054 case AttributeList::AT_IntelOclBicc:
6055 case AttributeList::AT_PreserveMost:
6056 case AttributeList::AT_PreserveAll:
6057 handleCallConvAttr(S, D, Attr);
6059 case AttributeList::AT_OpenCLKernel:
6060 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr);
6062 case AttributeList::AT_OpenCLAccess:
6063 handleOpenCLAccessAttr(S, D, Attr);
6065 case AttributeList::AT_OpenCLNoSVM:
6066 handleOpenCLNoSVMAttr(S, D, Attr);
6068 case AttributeList::AT_SwiftContext:
6069 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext);
6071 case AttributeList::AT_SwiftErrorResult:
6072 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult);
6074 case AttributeList::AT_SwiftIndirectResult:
6075 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult);
6077 case AttributeList::AT_InternalLinkage:
6078 handleInternalLinkageAttr(S, D, Attr);
6080 case AttributeList::AT_LTOVisibilityPublic:
6081 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr);
6084 // Microsoft attributes:
6085 case AttributeList::AT_EmptyBases:
6086 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr);
6088 case AttributeList::AT_LayoutVersion:
6089 handleLayoutVersion(S, D, Attr);
6091 case AttributeList::AT_MSNoVTable:
6092 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr);
6094 case AttributeList::AT_MSStruct:
6095 handleSimpleAttribute<MSStructAttr>(S, D, Attr);
6097 case AttributeList::AT_Uuid:
6098 handleUuidAttr(S, D, Attr);
6100 case AttributeList::AT_MSInheritance:
6101 handleMSInheritanceAttr(S, D, Attr);
6103 case AttributeList::AT_SelectAny:
6104 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr);
6106 case AttributeList::AT_Thread:
6107 handleDeclspecThreadAttr(S, D, Attr);
6110 case AttributeList::AT_AbiTag:
6111 handleAbiTagAttr(S, D, Attr);
6114 // Thread safety attributes:
6115 case AttributeList::AT_AssertExclusiveLock:
6116 handleAssertExclusiveLockAttr(S, D, Attr);
6118 case AttributeList::AT_AssertSharedLock:
6119 handleAssertSharedLockAttr(S, D, Attr);
6121 case AttributeList::AT_GuardedVar:
6122 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr);
6124 case AttributeList::AT_PtGuardedVar:
6125 handlePtGuardedVarAttr(S, D, Attr);
6127 case AttributeList::AT_ScopedLockable:
6128 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr);
6130 case AttributeList::AT_NoSanitize:
6131 handleNoSanitizeAttr(S, D, Attr);
6133 case AttributeList::AT_NoSanitizeSpecific:
6134 handleNoSanitizeSpecificAttr(S, D, Attr);
6136 case AttributeList::AT_NoThreadSafetyAnalysis:
6137 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr);
6139 case AttributeList::AT_GuardedBy:
6140 handleGuardedByAttr(S, D, Attr);
6142 case AttributeList::AT_PtGuardedBy:
6143 handlePtGuardedByAttr(S, D, Attr);
6145 case AttributeList::AT_ExclusiveTrylockFunction:
6146 handleExclusiveTrylockFunctionAttr(S, D, Attr);
6148 case AttributeList::AT_LockReturned:
6149 handleLockReturnedAttr(S, D, Attr);
6151 case AttributeList::AT_LocksExcluded:
6152 handleLocksExcludedAttr(S, D, Attr);
6154 case AttributeList::AT_SharedTrylockFunction:
6155 handleSharedTrylockFunctionAttr(S, D, Attr);
6157 case AttributeList::AT_AcquiredBefore:
6158 handleAcquiredBeforeAttr(S, D, Attr);
6160 case AttributeList::AT_AcquiredAfter:
6161 handleAcquiredAfterAttr(S, D, Attr);
6164 // Capability analysis attributes.
6165 case AttributeList::AT_Capability:
6166 case AttributeList::AT_Lockable:
6167 handleCapabilityAttr(S, D, Attr);
6169 case AttributeList::AT_RequiresCapability:
6170 handleRequiresCapabilityAttr(S, D, Attr);
6173 case AttributeList::AT_AssertCapability:
6174 handleAssertCapabilityAttr(S, D, Attr);
6176 case AttributeList::AT_AcquireCapability:
6177 handleAcquireCapabilityAttr(S, D, Attr);
6179 case AttributeList::AT_ReleaseCapability:
6180 handleReleaseCapabilityAttr(S, D, Attr);
6182 case AttributeList::AT_TryAcquireCapability:
6183 handleTryAcquireCapabilityAttr(S, D, Attr);
6186 // Consumed analysis attributes.
6187 case AttributeList::AT_Consumable:
6188 handleConsumableAttr(S, D, Attr);
6190 case AttributeList::AT_ConsumableAutoCast:
6191 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr);
6193 case AttributeList::AT_ConsumableSetOnRead:
6194 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr);
6196 case AttributeList::AT_CallableWhen:
6197 handleCallableWhenAttr(S, D, Attr);
6199 case AttributeList::AT_ParamTypestate:
6200 handleParamTypestateAttr(S, D, Attr);
6202 case AttributeList::AT_ReturnTypestate:
6203 handleReturnTypestateAttr(S, D, Attr);
6205 case AttributeList::AT_SetTypestate:
6206 handleSetTypestateAttr(S, D, Attr);
6208 case AttributeList::AT_TestTypestate:
6209 handleTestTypestateAttr(S, D, Attr);
6212 // Type safety attributes.
6213 case AttributeList::AT_ArgumentWithTypeTag:
6214 handleArgumentWithTypeTagAttr(S, D, Attr);
6216 case AttributeList::AT_TypeTagForDatatype:
6217 handleTypeTagForDatatypeAttr(S, D, Attr);
6219 case AttributeList::AT_RenderScriptKernel:
6220 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr);
6223 case AttributeList::AT_XRayInstrument:
6224 handleSimpleAttribute<XRayInstrumentAttr>(S, D, Attr);
6229 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
6230 /// attribute list to the specified decl, ignoring any type attributes.
6231 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
6232 const AttributeList *AttrList,
6233 bool IncludeCXX11Attributes) {
6234 for (const AttributeList* l = AttrList; l; l = l->getNext())
6235 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
6237 // FIXME: We should be able to handle these cases in TableGen.
6239 // static int a9 __attribute__((weakref));
6240 // but that looks really pointless. We reject it.
6241 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
6242 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias)
6243 << cast<NamedDecl>(D);
6244 D->dropAttr<WeakRefAttr>();
6248 // FIXME: We should be able to handle this in TableGen as well. It would be
6249 // good to have a way to specify "these attributes must appear as a group",
6250 // for these. Additionally, it would be good to have a way to specify "these
6251 // attribute must never appear as a group" for attributes like cold and hot.
6252 if (!D->hasAttr<OpenCLKernelAttr>()) {
6253 // These attributes cannot be applied to a non-kernel function.
6254 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
6255 // FIXME: This emits a different error message than
6256 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
6257 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6258 D->setInvalidDecl();
6259 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) {
6260 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6261 D->setInvalidDecl();
6262 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) {
6263 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
6264 D->setInvalidDecl();
6265 } else if (Attr *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
6266 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6267 << A << ExpectedKernelFunction;
6268 D->setInvalidDecl();
6269 } else if (Attr *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
6270 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6271 << A << ExpectedKernelFunction;
6272 D->setInvalidDecl();
6273 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
6274 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6275 << A << ExpectedKernelFunction;
6276 D->setInvalidDecl();
6277 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
6278 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6279 << A << ExpectedKernelFunction;
6280 D->setInvalidDecl();
6285 // Annotation attributes are the only attributes allowed after an access
6287 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
6288 const AttributeList *AttrList) {
6289 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6290 if (l->getKind() == AttributeList::AT_Annotate) {
6291 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute());
6293 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
6301 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
6302 /// contains any decl attributes that we should warn about.
6303 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
6304 for ( ; A; A = A->getNext()) {
6305 // Only warn if the attribute is an unignored, non-type attribute.
6306 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
6307 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
6309 if (A->getKind() == AttributeList::UnknownAttribute) {
6310 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
6311 << A->getName() << A->getRange();
6313 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
6314 << A->getName() << A->getRange();
6319 /// checkUnusedDeclAttributes - Given a declarator which is not being
6320 /// used to build a declaration, complain about any decl attributes
6321 /// which might be lying around on it.
6322 void Sema::checkUnusedDeclAttributes(Declarator &D) {
6323 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
6324 ::checkUnusedDeclAttributes(*this, D.getAttributes());
6325 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
6326 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
6329 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
6330 /// \#pragma weak needs a non-definition decl and source may not have one.
6331 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
6332 SourceLocation Loc) {
6333 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
6334 NamedDecl *NewD = nullptr;
6335 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
6336 FunctionDecl *NewFD;
6337 // FIXME: Missing call to CheckFunctionDeclaration().
6339 // FIXME: Is the qualifier info correct?
6340 // FIXME: Is the DeclContext correct?
6341 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
6342 Loc, Loc, DeclarationName(II),
6343 FD->getType(), FD->getTypeSourceInfo(),
6344 SC_None, false/*isInlineSpecified*/,
6346 false/*isConstexprSpecified*/);
6349 if (FD->getQualifier())
6350 NewFD->setQualifierInfo(FD->getQualifierLoc());
6352 // Fake up parameter variables; they are declared as if this were
6354 QualType FDTy = FD->getType();
6355 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
6356 SmallVector<ParmVarDecl*, 16> Params;
6357 for (const auto &AI : FT->param_types()) {
6358 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
6359 Param->setScopeInfo(0, Params.size());
6360 Params.push_back(Param);
6362 NewFD->setParams(Params);
6364 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
6365 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
6366 VD->getInnerLocStart(), VD->getLocation(), II,
6367 VD->getType(), VD->getTypeSourceInfo(),
6368 VD->getStorageClass());
6369 if (VD->getQualifier()) {
6370 VarDecl *NewVD = cast<VarDecl>(NewD);
6371 NewVD->setQualifierInfo(VD->getQualifierLoc());
6377 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
6378 /// applied to it, possibly with an alias.
6379 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
6380 if (W.getUsed()) return; // only do this once
6382 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
6383 IdentifierInfo *NDId = ND->getIdentifier();
6384 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
6385 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(),
6387 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6388 WeakTopLevelDecl.push_back(NewD);
6389 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
6390 // to insert Decl at TU scope, sorry.
6391 DeclContext *SavedContext = CurContext;
6392 CurContext = Context.getTranslationUnitDecl();
6393 NewD->setDeclContext(CurContext);
6394 NewD->setLexicalDeclContext(CurContext);
6395 PushOnScopeChains(NewD, S);
6396 CurContext = SavedContext;
6397 } else { // just add weak to existing
6398 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
6402 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
6403 // It's valid to "forward-declare" #pragma weak, in which case we
6405 LoadExternalWeakUndeclaredIdentifiers();
6406 if (!WeakUndeclaredIdentifiers.empty()) {
6407 NamedDecl *ND = nullptr;
6408 if (VarDecl *VD = dyn_cast<VarDecl>(D))
6409 if (VD->isExternC())
6411 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6412 if (FD->isExternC())
6415 if (IdentifierInfo *Id = ND->getIdentifier()) {
6416 auto I = WeakUndeclaredIdentifiers.find(Id);
6417 if (I != WeakUndeclaredIdentifiers.end()) {
6418 WeakInfo W = I->second;
6419 DeclApplyPragmaWeak(S, ND, W);
6420 WeakUndeclaredIdentifiers[Id] = W;
6427 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
6428 /// it, apply them to D. This is a bit tricky because PD can have attributes
6429 /// specified in many different places, and we need to find and apply them all.
6430 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
6431 // Apply decl attributes from the DeclSpec if present.
6432 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
6433 ProcessDeclAttributeList(S, D, Attrs);
6435 // Walk the declarator structure, applying decl attributes that were in a type
6436 // position to the decl itself. This handles cases like:
6437 // int *__attr__(x)** D;
6438 // when X is a decl attribute.
6439 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
6440 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
6441 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
6443 // Finally, apply any attributes on the decl itself.
6444 if (const AttributeList *Attrs = PD.getAttributes())
6445 ProcessDeclAttributeList(S, D, Attrs);
6448 /// Is the given declaration allowed to use a forbidden type?
6449 /// If so, it'll still be annotated with an attribute that makes it
6450 /// illegal to actually use.
6451 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl,
6452 const DelayedDiagnostic &diag,
6453 UnavailableAttr::ImplicitReason &reason) {
6454 // Private ivars are always okay. Unfortunately, people don't
6455 // always properly make their ivars private, even in system headers.
6456 // Plus we need to make fields okay, too.
6457 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
6458 !isa<FunctionDecl>(decl))
6461 // Silently accept unsupported uses of __weak in both user and system
6462 // declarations when it's been disabled, for ease of integration with
6463 // -fno-objc-arc files. We do have to take some care against attempts
6464 // to define such things; for now, we've only done that for ivars
6466 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) {
6467 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
6468 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
6469 reason = UnavailableAttr::IR_ForbiddenWeak;
6474 // Allow all sorts of things in system headers.
6475 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) {
6476 // Currently, all the failures dealt with this way are due to ARC
6478 reason = UnavailableAttr::IR_ARCForbiddenType;
6485 /// Handle a delayed forbidden-type diagnostic.
6486 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
6488 auto reason = UnavailableAttr::IR_None;
6489 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) {
6490 assert(reason && "didn't set reason?");
6491 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason,
6495 if (S.getLangOpts().ObjCAutoRefCount)
6496 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
6497 // FIXME: we may want to suppress diagnostics for all
6498 // kind of forbidden type messages on unavailable functions.
6499 if (FD->hasAttr<UnavailableAttr>() &&
6500 diag.getForbiddenTypeDiagnostic() ==
6501 diag::err_arc_array_param_no_ownership) {
6502 diag.Triggered = true;
6507 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
6508 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
6509 diag.Triggered = true;
6512 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
6514 // Check each AvailabilityAttr to find the one for this platform.
6515 for (const auto *A : D->attrs()) {
6516 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
6517 // FIXME: this is copied from CheckAvailability. We should try to
6520 // Check if this is an App Extension "platform", and if so chop off
6521 // the suffix for matching with the actual platform.
6522 StringRef ActualPlatform = Avail->getPlatform()->getName();
6523 StringRef RealizedPlatform = ActualPlatform;
6524 if (Context.getLangOpts().AppExt) {
6525 size_t suffix = RealizedPlatform.rfind("_app_extension");
6526 if (suffix != StringRef::npos)
6527 RealizedPlatform = RealizedPlatform.slice(0, suffix);
6530 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
6532 // Match the platform name.
6533 if (RealizedPlatform == TargetPlatform)
6540 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in
6541 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic
6542 /// in a deprecated context, but not the other way around.
6543 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
6544 VersionTuple DeclVersion,
6546 assert(K != AR_Available && "Expected an unavailable declaration here!");
6548 // Checks if we should emit the availability diagnostic in the context of C.
6549 auto CheckContext = [&](const Decl *C) {
6550 if (K == AR_NotYetIntroduced) {
6551 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
6552 if (AA->getIntroduced() >= DeclVersion)
6554 } else if (K == AR_Deprecated)
6555 if (C->isDeprecated())
6558 if (C->isUnavailable())
6563 // FIXME: This is a temporary workaround! Some existing Apple headers depends
6564 // on nested declarations in an @interface having the availability of the
6565 // interface when they really shouldn't: they are members of the enclosing
6566 // context, and can referenced from there.
6567 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) {
6568 auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext);
6569 if (CheckContext(OrigCtx))
6572 // An implementation implicitly has the availability of the interface.
6573 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) {
6574 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6575 if (CheckContext(Interface))
6578 // A category implicitly has the availability of the interface.
6579 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx))
6580 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6581 if (CheckContext(Interface))
6586 if (CheckContext(Ctx))
6589 // An implementation implicitly has the availability of the interface.
6590 if (auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
6591 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
6592 if (CheckContext(Interface))
6595 // A category implicitly has the availability of the interface.
6596 else if (auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
6597 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
6598 if (CheckContext(Interface))
6600 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
6605 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
6606 Decl *Ctx, const NamedDecl *D,
6607 StringRef Message, SourceLocation Loc,
6608 const ObjCInterfaceDecl *UnknownObjCClass,
6609 const ObjCPropertyDecl *ObjCProperty,
6610 bool ObjCPropertyAccess) {
6611 // Diagnostics for deprecated or unavailable.
6612 unsigned diag, diag_message, diag_fwdclass_message;
6613 unsigned diag_available_here = diag::note_availability_specified_here;
6615 // Matches 'diag::note_property_attribute' options.
6616 unsigned property_note_select;
6618 // Matches diag::note_availability_specified_here.
6619 unsigned available_here_select_kind;
6621 VersionTuple DeclVersion;
6622 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, D))
6623 DeclVersion = AA->getIntroduced();
6625 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx))
6630 diag = !ObjCPropertyAccess ? diag::warn_deprecated
6631 : diag::warn_property_method_deprecated;
6632 diag_message = diag::warn_deprecated_message;
6633 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
6634 property_note_select = /* deprecated */ 0;
6635 available_here_select_kind = /* deprecated */ 2;
6638 case AR_Unavailable:
6639 diag = !ObjCPropertyAccess ? diag::err_unavailable
6640 : diag::err_property_method_unavailable;
6641 diag_message = diag::err_unavailable_message;
6642 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
6643 property_note_select = /* unavailable */ 1;
6644 available_here_select_kind = /* unavailable */ 0;
6646 if (auto attr = D->getAttr<UnavailableAttr>()) {
6647 if (attr->isImplicit() && attr->getImplicitReason()) {
6648 // Most of these failures are due to extra restrictions in ARC;
6649 // reflect that in the primary diagnostic when applicable.
6650 auto flagARCError = [&] {
6651 if (S.getLangOpts().ObjCAutoRefCount &&
6652 S.getSourceManager().isInSystemHeader(D->getLocation()))
6653 diag = diag::err_unavailable_in_arc;
6656 switch (attr->getImplicitReason()) {
6657 case UnavailableAttr::IR_None: break;
6659 case UnavailableAttr::IR_ARCForbiddenType:
6661 diag_available_here = diag::note_arc_forbidden_type;
6664 case UnavailableAttr::IR_ForbiddenWeak:
6665 if (S.getLangOpts().ObjCWeakRuntime)
6666 diag_available_here = diag::note_arc_weak_disabled;
6668 diag_available_here = diag::note_arc_weak_no_runtime;
6671 case UnavailableAttr::IR_ARCForbiddenConversion:
6673 diag_available_here = diag::note_performs_forbidden_arc_conversion;
6676 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
6678 diag_available_here = diag::note_arc_init_returns_unrelated;
6681 case UnavailableAttr::IR_ARCFieldWithOwnership:
6683 diag_available_here = diag::note_arc_field_with_ownership;
6690 case AR_NotYetIntroduced:
6691 diag = diag::warn_partial_availability;
6692 diag_message = diag::warn_partial_message;
6693 diag_fwdclass_message = diag::warn_partial_fwdclass_message;
6694 property_note_select = /* partial */ 2;
6695 available_here_select_kind = /* partial */ 3;
6699 llvm_unreachable("Warning for availability of available declaration?");
6702 CharSourceRange UseRange;
6703 StringRef Replacement;
6704 if (K == AR_Deprecated) {
6705 if (auto attr = D->getAttr<DeprecatedAttr>())
6706 Replacement = attr->getReplacement();
6707 if (auto attr = getAttrForPlatform(S.Context, D))
6708 Replacement = attr->getReplacement();
6710 if (!Replacement.empty())
6712 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
6715 if (!Message.empty()) {
6716 S.Diag(Loc, diag_message) << D << Message
6717 << (UseRange.isValid() ?
6718 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6720 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6721 << ObjCProperty->getDeclName() << property_note_select;
6722 } else if (!UnknownObjCClass) {
6723 S.Diag(Loc, diag) << D
6724 << (UseRange.isValid() ?
6725 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6727 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
6728 << ObjCProperty->getDeclName() << property_note_select;
6730 S.Diag(Loc, diag_fwdclass_message) << D
6731 << (UseRange.isValid() ?
6732 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint());
6733 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
6736 // The declaration can have multiple availability attributes, we are looking
6738 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D);
6739 if (A && A->isInherited()) {
6740 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl;
6741 Redecl = Redecl->getPreviousDecl()) {
6742 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context,
6744 if (AForRedecl && !AForRedecl->isInherited()) {
6745 // If D is a declaration with inherited attributes, the note should
6746 // point to the declaration with actual attributes.
6747 S.Diag(Redecl->getLocation(), diag_available_here) << D
6748 << available_here_select_kind;
6754 S.Diag(D->getLocation(), diag_available_here)
6755 << D << available_here_select_kind;
6757 if (K == AR_NotYetIntroduced)
6758 S.Diag(Loc, diag::note_partial_availability_silence) << D;
6761 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
6763 assert(DD.Kind == DelayedDiagnostic::Availability &&
6764 "Expected an availability diagnostic here");
6766 DD.Triggered = true;
6767 DoEmitAvailabilityWarning(
6768 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityDecl(),
6769 DD.getAvailabilityMessage(), DD.Loc, DD.getUnknownObjCClass(),
6770 DD.getObjCProperty(), false);
6773 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
6774 assert(DelayedDiagnostics.getCurrentPool());
6775 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
6776 DelayedDiagnostics.popWithoutEmitting(state);
6778 // When delaying diagnostics to run in the context of a parsed
6779 // declaration, we only want to actually emit anything if parsing
6783 // We emit all the active diagnostics in this pool or any of its
6784 // parents. In general, we'll get one pool for the decl spec
6785 // and a child pool for each declarator; in a decl group like:
6786 // deprecated_typedef foo, *bar, baz();
6787 // only the declarator pops will be passed decls. This is correct;
6788 // we really do need to consider delayed diagnostics from the decl spec
6789 // for each of the different declarations.
6790 const DelayedDiagnosticPool *pool = &poppedPool;
6792 for (DelayedDiagnosticPool::pool_iterator
6793 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
6794 // This const_cast is a bit lame. Really, Triggered should be mutable.
6795 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
6799 switch (diag.Kind) {
6800 case DelayedDiagnostic::Availability:
6801 // Don't bother giving deprecation/unavailable diagnostics if
6802 // the decl is invalid.
6803 if (!decl->isInvalidDecl())
6804 handleDelayedAvailabilityCheck(*this, diag, decl);
6807 case DelayedDiagnostic::Access:
6808 HandleDelayedAccessCheck(diag, decl);
6811 case DelayedDiagnostic::ForbiddenType:
6812 handleDelayedForbiddenType(*this, diag, decl);
6816 } while ((pool = pool->getParent()));
6819 /// Given a set of delayed diagnostics, re-emit them as if they had
6820 /// been delayed in the current context instead of in the given pool.
6821 /// Essentially, this just moves them to the current pool.
6822 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
6823 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
6824 assert(curPool && "re-emitting in undelayed context not supported");
6825 curPool->steal(pool);
6828 void Sema::EmitAvailabilityWarning(AvailabilityResult AR,
6829 NamedDecl *D, StringRef Message,
6831 const ObjCInterfaceDecl *UnknownObjCClass,
6832 const ObjCPropertyDecl *ObjCProperty,
6833 bool ObjCPropertyAccess) {
6834 // Delay if we're currently parsing a declaration.
6835 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
6836 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(
6837 AR, Loc, D, UnknownObjCClass, ObjCProperty, Message,
6838 ObjCPropertyAccess));
6842 Decl *Ctx = cast<Decl>(getCurLexicalContext());
6843 DoEmitAvailabilityWarning(*this, AR, Ctx, D, Message, Loc, UnknownObjCClass,
6844 ObjCProperty, ObjCPropertyAccess);
6849 /// \brief This class implements -Wunguarded-availability.
6851 /// This is done with a traversal of the AST of a function that makes reference
6852 /// to a partially available declaration. Whenever we encounter an \c if of the
6853 /// form: \c if(@available(...)), we use the version from the condition to visit
6854 /// the then statement.
6855 class DiagnoseUnguardedAvailability
6856 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
6857 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
6862 /// Stack of potentially nested 'if (@available(...))'s.
6863 SmallVector<VersionTuple, 8> AvailabilityStack;
6865 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range);
6868 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
6869 : SemaRef(SemaRef), Ctx(Ctx) {
6870 AvailabilityStack.push_back(
6871 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
6874 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
6876 bool TraverseIfStmt(IfStmt *If);
6878 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
6879 if (ObjCMethodDecl *D = Msg->getMethodDecl())
6880 DiagnoseDeclAvailability(
6881 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd()));
6885 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
6886 DiagnoseDeclAvailability(DRE->getDecl(),
6887 SourceRange(DRE->getLocStart(), DRE->getLocEnd()));
6891 bool VisitMemberExpr(MemberExpr *ME) {
6892 DiagnoseDeclAvailability(ME->getMemberDecl(),
6893 SourceRange(ME->getLocStart(), ME->getLocEnd()));
6897 bool VisitTypeLoc(TypeLoc Ty);
6900 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
6901 NamedDecl *D, SourceRange Range) {
6903 VersionTuple ContextVersion = AvailabilityStack.back();
6904 if (AvailabilityResult Result =
6905 SemaRef.ShouldDiagnoseAvailabilityOfDecl(D, nullptr)) {
6906 // All other diagnostic kinds have already been handled in
6907 // DiagnoseAvailabilityOfDecl.
6908 if (Result != AR_NotYetIntroduced)
6911 const AvailabilityAttr *AA = getAttrForPlatform(SemaRef.getASTContext(), D);
6912 VersionTuple Introduced = AA->getIntroduced();
6914 if (ContextVersion >= Introduced)
6917 // If the context of this function is less available than D, we should not
6918 // emit a diagnostic.
6919 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx))
6922 SemaRef.Diag(Range.getBegin(), diag::warn_unguarded_availability)
6924 << AvailabilityAttr::getPrettyPlatformName(
6925 SemaRef.getASTContext().getTargetInfo().getPlatformName())
6926 << Introduced.getAsString();
6928 SemaRef.Diag(D->getLocation(), diag::note_availability_specified_here)
6929 << D << /* partial */ 3;
6931 // FIXME: Replace this with a fixit diagnostic.
6932 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
6937 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
6938 const Type *TyPtr = Ty.getTypePtr();
6939 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
6941 if (const TagType *TT = dyn_cast<TagType>(TyPtr)) {
6942 TagDecl *TD = TT->getDecl();
6943 DiagnoseDeclAvailability(TD, Range);
6945 } else if (const TypedefType *TD = dyn_cast<TypedefType>(TyPtr)) {
6946 TypedefNameDecl *D = TD->getDecl();
6947 DiagnoseDeclAvailability(D, Range);
6949 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
6950 if (NamedDecl *D = ObjCO->getInterface())
6951 DiagnoseDeclAvailability(D, Range);
6957 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
6958 VersionTuple CondVersion;
6959 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
6960 CondVersion = E->getVersion();
6962 // If we're using the '*' case here or if this check is redundant, then we
6963 // use the enclosing version to check both branches.
6964 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
6965 return Base::TraverseStmt(If->getThen()) &&
6966 Base::TraverseStmt(If->getElse());
6968 // This isn't an availability checking 'if', we can just continue.
6969 return Base::TraverseIfStmt(If);
6972 AvailabilityStack.push_back(CondVersion);
6973 bool ShouldContinue = TraverseStmt(If->getThen());
6974 AvailabilityStack.pop_back();
6976 return ShouldContinue && TraverseStmt(If->getElse());
6979 } // end anonymous namespace
6981 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
6982 Stmt *Body = nullptr;
6984 if (auto *FD = D->getAsFunction()) {
6985 // FIXME: We only examine the pattern decl for availability violations now,
6986 // but we should also examine instantiated templates.
6987 if (FD->isTemplateInstantiation())
6990 Body = FD->getBody();
6991 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
6992 Body = MD->getBody();
6994 assert(Body && "Need a body here!");
6996 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);