1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements decl-related attribute processing.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "TargetAttributesSema.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/Basic/CharInfo.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/Scope.h"
31 #include "llvm/ADT/StringExtras.h"
32 using namespace clang;
35 /// These constants match the enumerated choices of
36 /// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
37 enum AttributeDeclKind {
40 ExpectedVariableOrFunction,
41 ExpectedFunctionOrMethod,
43 ExpectedFunctionMethodOrBlock,
44 ExpectedFunctionMethodOrClass,
45 ExpectedFunctionMethodOrParameter,
49 ExpectedVariableFunctionOrLabel,
50 ExpectedFieldOrGlobalVar,
52 ExpectedVariableFunctionOrTag,
54 ExpectedVariableOrField,
55 ExpectedVariableFieldOrTag,
56 ExpectedTypeOrNamespace,
57 ExpectedObjectiveCInterface,
58 ExpectedMethodOrProperty,
59 ExpectedStructOrUnion,
60 ExpectedStructOrUnionOrClass
63 //===----------------------------------------------------------------------===//
65 //===----------------------------------------------------------------------===//
67 static const FunctionType *getFunctionType(const Decl *D,
68 bool blocksToo = true) {
70 if (const ValueDecl *decl = dyn_cast<ValueDecl>(D))
72 else if (const FieldDecl *decl = dyn_cast<FieldDecl>(D))
74 else if (const TypedefNameDecl* decl = dyn_cast<TypedefNameDecl>(D))
75 Ty = decl->getUnderlyingType();
79 if (Ty->isFunctionPointerType())
80 Ty = Ty->getAs<PointerType>()->getPointeeType();
81 else if (blocksToo && Ty->isBlockPointerType())
82 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
84 return Ty->getAs<FunctionType>();
87 // FIXME: We should provide an abstraction around a method or function
88 // to provide the following bits of information.
90 /// isFunction - Return true if the given decl has function
91 /// type (function or function-typed variable).
92 static bool isFunction(const Decl *D) {
93 return getFunctionType(D, false) != NULL;
96 /// isFunctionOrMethod - Return true if the given decl has function
97 /// type (function or function-typed variable) or an Objective-C
99 static bool isFunctionOrMethod(const Decl *D) {
100 return isFunction(D) || isa<ObjCMethodDecl>(D);
103 /// isFunctionOrMethodOrBlock - Return true if the given decl has function
104 /// type (function or function-typed variable) or an Objective-C
105 /// method or a block.
106 static bool isFunctionOrMethodOrBlock(const Decl *D) {
107 if (isFunctionOrMethod(D))
109 // check for block is more involved.
110 if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
111 QualType Ty = V->getType();
112 return Ty->isBlockPointerType();
114 return isa<BlockDecl>(D);
117 /// Return true if the given decl has a declarator that should have
118 /// been processed by Sema::GetTypeForDeclarator.
119 static bool hasDeclarator(const Decl *D) {
120 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
121 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
122 isa<ObjCPropertyDecl>(D);
125 /// hasFunctionProto - Return true if the given decl has a argument
126 /// information. This decl should have already passed
127 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
128 static bool hasFunctionProto(const Decl *D) {
129 if (const FunctionType *FnTy = getFunctionType(D))
130 return isa<FunctionProtoType>(FnTy);
132 assert(isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D));
137 /// getFunctionOrMethodNumArgs - Return number of function or method
138 /// arguments. It is an error to call this on a K&R function (use
139 /// hasFunctionProto first).
140 static unsigned getFunctionOrMethodNumArgs(const Decl *D) {
141 if (const FunctionType *FnTy = getFunctionType(D))
142 return cast<FunctionProtoType>(FnTy)->getNumArgs();
143 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
144 return BD->getNumParams();
145 return cast<ObjCMethodDecl>(D)->param_size();
148 static QualType getFunctionOrMethodArgType(const Decl *D, unsigned Idx) {
149 if (const FunctionType *FnTy = getFunctionType(D))
150 return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
151 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
152 return BD->getParamDecl(Idx)->getType();
154 return cast<ObjCMethodDecl>(D)->param_begin()[Idx]->getType();
157 static QualType getFunctionOrMethodResultType(const Decl *D) {
158 if (const FunctionType *FnTy = getFunctionType(D))
159 return cast<FunctionProtoType>(FnTy)->getResultType();
160 return cast<ObjCMethodDecl>(D)->getResultType();
163 static bool isFunctionOrMethodVariadic(const Decl *D) {
164 if (const FunctionType *FnTy = getFunctionType(D)) {
165 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
166 return proto->isVariadic();
167 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
168 return BD->isVariadic();
170 return cast<ObjCMethodDecl>(D)->isVariadic();
174 static bool isInstanceMethod(const Decl *D) {
175 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
176 return MethodDecl->isInstance();
180 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
181 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
185 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
189 IdentifierInfo* ClsName = Cls->getIdentifier();
191 // FIXME: Should we walk the chain of classes?
192 return ClsName == &Ctx.Idents.get("NSString") ||
193 ClsName == &Ctx.Idents.get("NSMutableString");
196 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
197 const PointerType *PT = T->getAs<PointerType>();
201 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
205 const RecordDecl *RD = RT->getDecl();
206 if (RD->getTagKind() != TTK_Struct)
209 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
212 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
213 // FIXME: Include the type in the argument list.
214 return Attr.getNumArgs() + Attr.hasParsedType();
217 /// \brief Check if the attribute has exactly as many args as Num. May
219 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
221 if (getNumAttributeArgs(Attr) != Num) {
222 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
223 << Attr.getName() << Num;
231 /// \brief Check if the attribute has at least as many args as Num. May
233 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
235 if (getNumAttributeArgs(Attr) < Num) {
236 S.Diag(Attr.getLoc(), diag::err_attribute_too_few_arguments) << Num;
243 /// \brief Check if IdxExpr is a valid argument index for a function or
244 /// instance method D. May output an error.
246 /// \returns true if IdxExpr is a valid index.
247 static bool checkFunctionOrMethodArgumentIndex(Sema &S, const Decl *D,
249 SourceLocation AttrLoc,
254 assert(isFunctionOrMethod(D));
256 // In C++ the implicit 'this' function parameter also counts.
257 // Parameters are counted from one.
258 bool HP = hasFunctionProto(D);
259 bool HasImplicitThisParam = isInstanceMethod(D);
260 bool IV = HP && isFunctionOrMethodVariadic(D);
261 unsigned NumArgs = (HP ? getFunctionOrMethodNumArgs(D) : 0) +
262 HasImplicitThisParam;
265 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
266 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
267 std::string Name = std::string("'") + AttrName.str() + std::string("'");
268 S.Diag(AttrLoc, diag::err_attribute_argument_n_type) << Name.c_str()
269 << AttrArgNum << AANT_ArgumentIntegerConstant << IdxExpr->getSourceRange();
273 Idx = IdxInt.getLimitedValue();
274 if (Idx < 1 || (!IV && Idx > NumArgs)) {
275 S.Diag(AttrLoc, diag::err_attribute_argument_out_of_bounds)
276 << AttrName << AttrArgNum << IdxExpr->getSourceRange();
279 Idx--; // Convert to zero-based.
280 if (HasImplicitThisParam) {
283 diag::err_attribute_invalid_implicit_this_argument)
284 << AttrName << IdxExpr->getSourceRange();
293 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
294 /// If not emit an error and return false. If the argument is an identifier it
295 /// will emit an error with a fixit hint and treat it as if it was a string
297 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
298 unsigned ArgNum, StringRef &Str,
299 SourceLocation *ArgLocation) {
300 // Look for identifiers. If we have one emit a hint to fix it to a literal.
301 if (Attr.isArgIdent(ArgNum)) {
302 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
303 Diag(Loc->Loc, diag::err_attribute_argument_type)
304 << Attr.getName() << AANT_ArgumentString
305 << FixItHint::CreateInsertion(Loc->Loc, "\"")
306 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
307 Str = Loc->Ident->getName();
309 *ArgLocation = Loc->Loc;
313 // Now check for an actual string literal.
314 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
315 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
317 *ArgLocation = ArgExpr->getLocStart();
319 if (!Literal || !Literal->isAscii()) {
320 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
321 << Attr.getName() << AANT_ArgumentString;
325 Str = Literal->getString();
330 /// \brief Check if passed in Decl is a field or potentially shared global var
331 /// \return true if the Decl is a field or potentially shared global variable
333 static bool mayBeSharedVariable(const Decl *D) {
334 if (isa<FieldDecl>(D))
336 if (const VarDecl *vd = dyn_cast<VarDecl>(D))
337 return vd->hasGlobalStorage() && !vd->getTLSKind();
342 /// \brief Check if the passed-in expression is of type int or bool.
343 static bool isIntOrBool(Expr *Exp) {
344 QualType QT = Exp->getType();
345 return QT->isBooleanType() || QT->isIntegerType();
349 // Check to see if the type is a smart pointer of some kind. We assume
350 // it's a smart pointer if it defines both operator-> and operator*.
351 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
352 DeclContextLookupConstResult Res1 = RT->getDecl()->lookup(
353 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
357 DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
358 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
365 /// \brief Check if passed in Decl is a pointer type.
366 /// Note that this function may produce an error message.
367 /// \return true if the Decl is a pointer type; false otherwise
368 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
369 const AttributeList &Attr) {
370 if (const ValueDecl *vd = dyn_cast<ValueDecl>(D)) {
371 QualType QT = vd->getType();
372 if (QT->isAnyPointerType())
375 if (const RecordType *RT = QT->getAs<RecordType>()) {
376 // If it's an incomplete type, it could be a smart pointer; skip it.
377 // (We don't want to force template instantiation if we can avoid it,
378 // since that would alter the order in which templates are instantiated.)
379 if (RT->isIncompleteType())
382 if (threadSafetyCheckIsSmartPointer(S, RT))
386 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
387 << Attr.getName()->getName() << QT;
389 S.Diag(Attr.getLoc(), diag::err_attribute_can_be_applied_only_to_value_decl)
395 /// \brief Checks that the passed in QualType either is of RecordType or points
396 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
397 static const RecordType *getRecordType(QualType QT) {
398 if (const RecordType *RT = QT->getAs<RecordType>())
401 // Now check if we point to record type.
402 if (const PointerType *PT = QT->getAs<PointerType>())
403 return PT->getPointeeType()->getAs<RecordType>();
409 static bool checkBaseClassIsLockableCallback(const CXXBaseSpecifier *Specifier,
410 CXXBasePath &Path, void *Unused) {
411 const RecordType *RT = Specifier->getType()->getAs<RecordType>();
412 if (RT->getDecl()->getAttr<LockableAttr>())
418 /// \brief Thread Safety Analysis: Checks that the passed in RecordType
419 /// resolves to a lockable object.
420 static void checkForLockableRecord(Sema &S, Decl *D, const AttributeList &Attr,
422 const RecordType *RT = getRecordType(Ty);
424 // Warn if could not get record type for this argument.
426 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_class)
427 << Attr.getName() << Ty.getAsString();
431 // Don't check for lockable if the class hasn't been defined yet.
432 if (RT->isIncompleteType())
435 // Allow smart pointers to be used as lockable objects.
436 // FIXME -- Check the type that the smart pointer points to.
437 if (threadSafetyCheckIsSmartPointer(S, RT))
440 // Check if the type is lockable.
441 RecordDecl *RD = RT->getDecl();
442 if (RD->getAttr<LockableAttr>())
445 // Else check if any base classes are lockable.
446 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
447 CXXBasePaths BPaths(false, false);
448 if (CRD->lookupInBases(checkBaseClassIsLockableCallback, 0, BPaths))
452 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
453 << Attr.getName() << Ty.getAsString();
456 /// \brief Thread Safety Analysis: Checks that all attribute arguments, starting
457 /// from Sidx, resolve to a lockable object.
458 /// \param Sidx The attribute argument index to start checking with.
459 /// \param ParamIdxOk Whether an argument can be indexing into a function
461 static void checkAttrArgsAreLockableObjs(Sema &S, Decl *D,
462 const AttributeList &Attr,
463 SmallVectorImpl<Expr*> &Args,
465 bool ParamIdxOk = false) {
466 for(unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
467 Expr *ArgExp = Attr.getArgAsExpr(Idx);
469 if (ArgExp->isTypeDependent()) {
470 // FIXME -- need to check this again on template instantiation
471 Args.push_back(ArgExp);
475 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
476 if (StrLit->getLength() == 0 ||
477 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
478 // Pass empty strings to the analyzer without warnings.
479 // Treat "*" as the universal lock.
480 Args.push_back(ArgExp);
484 // We allow constant strings to be used as a placeholder for expressions
485 // that are not valid C++ syntax, but warn that they are ignored.
486 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
488 Args.push_back(ArgExp);
492 QualType ArgTy = ArgExp->getType();
494 // A pointer to member expression of the form &MyClass::mu is treated
495 // specially -- we need to look at the type of the member.
496 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
497 if (UOp->getOpcode() == UO_AddrOf)
498 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
499 if (DRE->getDecl()->isCXXInstanceMember())
500 ArgTy = DRE->getDecl()->getType();
502 // First see if we can just cast to record type, or point to record type.
503 const RecordType *RT = getRecordType(ArgTy);
505 // Now check if we index into a record type function param.
506 if(!RT && ParamIdxOk) {
507 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
508 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
510 unsigned int NumParams = FD->getNumParams();
511 llvm::APInt ArgValue = IL->getValue();
512 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
513 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
514 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
515 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
516 << Attr.getName() << Idx + 1 << NumParams;
519 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
523 checkForLockableRecord(S, D, Attr, ArgTy);
525 Args.push_back(ArgExp);
529 //===----------------------------------------------------------------------===//
530 // Attribute Implementations
531 //===----------------------------------------------------------------------===//
533 // FIXME: All this manual attribute parsing code is gross. At the
534 // least add some helper functions to check most argument patterns (#
535 // and types of args).
537 enum ThreadAttributeDeclKind {
538 ThreadExpectedFieldOrGlobalVar,
539 ThreadExpectedFunctionOrMethod,
540 ThreadExpectedClassOrStruct
543 static bool checkGuardedVarAttrCommon(Sema &S, Decl *D,
544 const AttributeList &Attr) {
545 // D must be either a member field or global (potentially shared) variable.
546 if (!mayBeSharedVariable(D)) {
547 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
548 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
555 static void handleGuardedVarAttr(Sema &S, Decl *D, const AttributeList &Attr) {
556 if (!checkGuardedVarAttrCommon(S, D, Attr))
559 D->addAttr(::new (S.Context)
560 GuardedVarAttr(Attr.getRange(), S.Context,
561 Attr.getAttributeSpellingListIndex()));
564 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
565 const AttributeList &Attr) {
566 if (!checkGuardedVarAttrCommon(S, D, Attr))
569 if (!threadSafetyCheckIsPointer(S, D, Attr))
572 D->addAttr(::new (S.Context)
573 PtGuardedVarAttr(Attr.getRange(), S.Context,
574 Attr.getAttributeSpellingListIndex()));
577 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
578 const AttributeList &Attr,
580 // D must be either a member field or global (potentially shared) variable.
581 if (!mayBeSharedVariable(D)) {
582 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
583 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
587 SmallVector<Expr*, 1> Args;
588 // check that all arguments are lockable objects
589 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
590 unsigned Size = Args.size();
599 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
601 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
604 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg));
607 static void handlePtGuardedByAttr(Sema &S, Decl *D,
608 const AttributeList &Attr) {
610 if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
613 if (!threadSafetyCheckIsPointer(S, D, Attr))
616 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
620 static bool checkLockableAttrCommon(Sema &S, Decl *D,
621 const AttributeList &Attr) {
622 // FIXME: Lockable structs for C code.
623 if (!isa<RecordDecl>(D)) {
624 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
625 << Attr.getName() << ThreadExpectedClassOrStruct;
632 static void handleLockableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
633 if (!checkLockableAttrCommon(S, D, Attr))
636 D->addAttr(::new (S.Context) LockableAttr(Attr.getRange(), S.Context));
639 static void handleScopedLockableAttr(Sema &S, Decl *D,
640 const AttributeList &Attr) {
641 if (!checkLockableAttrCommon(S, D, Attr))
644 D->addAttr(::new (S.Context)
645 ScopedLockableAttr(Attr.getRange(), S.Context,
646 Attr.getAttributeSpellingListIndex()));
649 static void handleNoThreadSafetyAnalysis(Sema &S, Decl *D,
650 const AttributeList &Attr) {
651 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
652 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
653 << Attr.getName() << ThreadExpectedFunctionOrMethod;
657 D->addAttr(::new (S.Context) NoThreadSafetyAnalysisAttr(Attr.getRange(),
661 static void handleNoSanitizeAddressAttr(Sema &S, Decl *D,
662 const AttributeList &Attr) {
663 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
664 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
665 << Attr.getName() << ExpectedFunctionOrMethod;
669 D->addAttr(::new (S.Context)
670 NoSanitizeAddressAttr(Attr.getRange(), S.Context,
671 Attr.getAttributeSpellingListIndex()));
674 static void handleNoSanitizeMemory(Sema &S, Decl *D,
675 const AttributeList &Attr) {
676 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
677 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
678 << Attr.getName() << ExpectedFunctionOrMethod;
682 D->addAttr(::new (S.Context) NoSanitizeMemoryAttr(Attr.getRange(),
686 static void handleNoSanitizeThread(Sema &S, Decl *D,
687 const AttributeList &Attr) {
688 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
689 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
690 << Attr.getName() << ExpectedFunctionOrMethod;
694 D->addAttr(::new (S.Context) NoSanitizeThreadAttr(Attr.getRange(),
698 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
699 const AttributeList &Attr,
700 SmallVectorImpl<Expr *> &Args) {
701 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
704 // D must be either a member field or global (potentially shared) variable.
705 ValueDecl *VD = dyn_cast<ValueDecl>(D);
706 if (!VD || !mayBeSharedVariable(D)) {
707 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
708 << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
712 // Check that this attribute only applies to lockable types.
713 QualType QT = VD->getType();
714 if (!QT->isDependentType()) {
715 const RecordType *RT = getRecordType(QT);
716 if (!RT || !RT->getDecl()->getAttr<LockableAttr>()) {
717 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
723 // Check that all arguments are lockable objects.
724 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
731 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
732 const AttributeList &Attr) {
733 SmallVector<Expr*, 1> Args;
734 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
737 Expr **StartArg = &Args[0];
738 D->addAttr(::new (S.Context)
739 AcquiredAfterAttr(Attr.getRange(), S.Context,
740 StartArg, Args.size(),
741 Attr.getAttributeSpellingListIndex()));
744 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
745 const AttributeList &Attr) {
746 SmallVector<Expr*, 1> Args;
747 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
750 Expr **StartArg = &Args[0];
751 D->addAttr(::new (S.Context)
752 AcquiredBeforeAttr(Attr.getRange(), S.Context,
753 StartArg, Args.size(),
754 Attr.getAttributeSpellingListIndex()));
757 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
758 const AttributeList &Attr,
759 SmallVectorImpl<Expr *> &Args) {
760 // zero or more arguments ok
762 // check that the attribute is applied to a function
763 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
764 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
765 << Attr.getName() << ThreadExpectedFunctionOrMethod;
769 // check that all arguments are lockable objects
770 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
775 static void handleSharedLockFunctionAttr(Sema &S, Decl *D,
776 const AttributeList &Attr) {
777 SmallVector<Expr*, 1> Args;
778 if (!checkLockFunAttrCommon(S, D, Attr, Args))
781 unsigned Size = Args.size();
782 Expr **StartArg = Size == 0 ? 0 : &Args[0];
783 D->addAttr(::new (S.Context)
784 SharedLockFunctionAttr(Attr.getRange(), S.Context, StartArg, Size,
785 Attr.getAttributeSpellingListIndex()));
788 static void handleExclusiveLockFunctionAttr(Sema &S, Decl *D,
789 const AttributeList &Attr) {
790 SmallVector<Expr*, 1> Args;
791 if (!checkLockFunAttrCommon(S, D, Attr, Args))
794 unsigned Size = Args.size();
795 Expr **StartArg = Size == 0 ? 0 : &Args[0];
796 D->addAttr(::new (S.Context)
797 ExclusiveLockFunctionAttr(Attr.getRange(), S.Context,
799 Attr.getAttributeSpellingListIndex()));
802 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
803 const AttributeList &Attr) {
804 SmallVector<Expr*, 1> Args;
805 if (!checkLockFunAttrCommon(S, D, Attr, Args))
808 unsigned Size = Args.size();
809 Expr **StartArg = Size == 0 ? 0 : &Args[0];
810 D->addAttr(::new (S.Context)
811 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
812 Attr.getAttributeSpellingListIndex()));
815 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
816 const AttributeList &Attr) {
817 SmallVector<Expr*, 1> Args;
818 if (!checkLockFunAttrCommon(S, D, Attr, Args))
821 unsigned Size = Args.size();
822 Expr **StartArg = Size == 0 ? 0 : &Args[0];
823 D->addAttr(::new (S.Context)
824 AssertExclusiveLockAttr(Attr.getRange(), S.Context,
826 Attr.getAttributeSpellingListIndex()));
830 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
831 const AttributeList &Attr,
832 SmallVectorImpl<Expr *> &Args) {
833 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
836 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
837 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
838 << Attr.getName() << ThreadExpectedFunctionOrMethod;
842 if (!isIntOrBool(Attr.getArgAsExpr(0))) {
843 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
844 << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
848 // check that all arguments are lockable objects
849 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 1);
854 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
855 const AttributeList &Attr) {
856 SmallVector<Expr*, 2> Args;
857 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
860 D->addAttr(::new (S.Context)
861 SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
862 Attr.getArgAsExpr(0),
863 Args.data(), Args.size(),
864 Attr.getAttributeSpellingListIndex()));
867 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
868 const AttributeList &Attr) {
869 SmallVector<Expr*, 2> Args;
870 if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
873 D->addAttr(::new (S.Context)
874 ExclusiveTrylockFunctionAttr(Attr.getRange(), S.Context,
875 Attr.getArgAsExpr(0),
876 Args.data(), Args.size(),
877 Attr.getAttributeSpellingListIndex()));
880 static bool checkLocksRequiredCommon(Sema &S, Decl *D,
881 const AttributeList &Attr,
882 SmallVectorImpl<Expr *> &Args) {
883 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
886 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
887 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
888 << Attr.getName() << ThreadExpectedFunctionOrMethod;
892 // check that all arguments are lockable objects
893 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
900 static void handleExclusiveLocksRequiredAttr(Sema &S, Decl *D,
901 const AttributeList &Attr) {
902 SmallVector<Expr*, 1> Args;
903 if (!checkLocksRequiredCommon(S, D, Attr, Args))
906 Expr **StartArg = &Args[0];
907 D->addAttr(::new (S.Context)
908 ExclusiveLocksRequiredAttr(Attr.getRange(), S.Context,
909 StartArg, Args.size(),
910 Attr.getAttributeSpellingListIndex()));
913 static void handleSharedLocksRequiredAttr(Sema &S, Decl *D,
914 const AttributeList &Attr) {
915 SmallVector<Expr*, 1> Args;
916 if (!checkLocksRequiredCommon(S, D, Attr, Args))
919 Expr **StartArg = &Args[0];
920 D->addAttr(::new (S.Context)
921 SharedLocksRequiredAttr(Attr.getRange(), S.Context,
922 StartArg, Args.size(),
923 Attr.getAttributeSpellingListIndex()));
926 static void handleUnlockFunAttr(Sema &S, Decl *D,
927 const AttributeList &Attr) {
928 // zero or more arguments ok
930 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
931 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
932 << Attr.getName() << ThreadExpectedFunctionOrMethod;
936 // check that all arguments are lockable objects
937 SmallVector<Expr*, 1> Args;
938 checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
939 unsigned Size = Args.size();
940 Expr **StartArg = Size == 0 ? 0 : &Args[0];
942 D->addAttr(::new (S.Context)
943 UnlockFunctionAttr(Attr.getRange(), S.Context, StartArg, Size,
944 Attr.getAttributeSpellingListIndex()));
947 static void handleLockReturnedAttr(Sema &S, Decl *D,
948 const AttributeList &Attr) {
949 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
950 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
951 << Attr.getName() << ThreadExpectedFunctionOrMethod;
955 // check that the argument is lockable object
956 SmallVector<Expr*, 1> Args;
957 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
958 unsigned Size = Args.size();
962 D->addAttr(::new (S.Context)
963 LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
964 Attr.getAttributeSpellingListIndex()));
967 static void handleLocksExcludedAttr(Sema &S, Decl *D,
968 const AttributeList &Attr) {
969 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
972 if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
973 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
974 << Attr.getName() << ThreadExpectedFunctionOrMethod;
978 // check that all arguments are lockable objects
979 SmallVector<Expr*, 1> Args;
980 checkAttrArgsAreLockableObjs(S, D, Attr, Args);
981 unsigned Size = Args.size();
984 Expr **StartArg = &Args[0];
986 D->addAttr(::new (S.Context)
987 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
988 Attr.getAttributeSpellingListIndex()));
991 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
992 ConsumableAttr::ConsumedState DefaultState;
994 if (Attr.isArgIdent(0)) {
995 IdentifierLoc *IL = Attr.getArgAsIdent(0);
996 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
998 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
999 << Attr.getName() << IL->Ident;
1003 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1004 << Attr.getName() << AANT_ArgumentIdentifier;
1008 if (!isa<CXXRecordDecl>(D)) {
1009 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1010 Attr.getName() << ExpectedClass;
1014 D->addAttr(::new (S.Context)
1015 ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
1016 Attr.getAttributeSpellingListIndex()));
1019 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1020 const AttributeList &Attr) {
1021 ASTContext &CurrContext = S.getASTContext();
1022 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1024 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1025 if (!RD->hasAttr<ConsumableAttr>()) {
1026 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1027 RD->getNameAsString();
1037 static void handleCallableWhenAttr(Sema &S, Decl *D,
1038 const AttributeList &Attr) {
1039 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1042 if (!isa<CXXMethodDecl>(D)) {
1043 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1044 Attr.getName() << ExpectedMethod;
1048 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1051 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1052 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1053 CallableWhenAttr::ConsumedState CallableState;
1055 StringRef StateString;
1057 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1060 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1062 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1063 << Attr.getName() << StateString;
1067 States.push_back(CallableState);
1070 D->addAttr(::new (S.Context)
1071 CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1072 States.size(), Attr.getAttributeSpellingListIndex()));
1076 static void handleParamTypestateAttr(Sema &S, Decl *D,
1077 const AttributeList &Attr) {
1078 if (!checkAttributeNumArgs(S, Attr, 1)) return;
1080 if (!isa<ParmVarDecl>(D)) {
1081 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1082 Attr.getName() << ExpectedParameter;
1086 ParamTypestateAttr::ConsumedState ParamState;
1088 if (Attr.isArgIdent(0)) {
1089 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1090 StringRef StateString = Ident->Ident->getName();
1092 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1094 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1095 << Attr.getName() << StateString;
1099 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1100 Attr.getName() << AANT_ArgumentIdentifier;
1104 // FIXME: This check is currently being done in the analysis. It can be
1105 // enabled here only after the parser propagates attributes at
1106 // template specialization definition, not declaration.
1107 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1108 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1110 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1111 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1112 // ReturnType.getAsString();
1116 D->addAttr(::new (S.Context)
1117 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
1118 Attr.getAttributeSpellingListIndex()));
1122 static void handleReturnTypestateAttr(Sema &S, Decl *D,
1123 const AttributeList &Attr) {
1124 if (!checkAttributeNumArgs(S, Attr, 1)) return;
1126 if (!(isa<FunctionDecl>(D) || isa<ParmVarDecl>(D))) {
1127 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1128 Attr.getName() << ExpectedFunctionMethodOrParameter;
1132 ReturnTypestateAttr::ConsumedState ReturnState;
1134 if (Attr.isArgIdent(0)) {
1135 IdentifierLoc *IL = Attr.getArgAsIdent(0);
1136 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1138 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1139 << Attr.getName() << IL->Ident;
1143 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1144 Attr.getName() << AANT_ArgumentIdentifier;
1148 // FIXME: This check is currently being done in the analysis. It can be
1149 // enabled here only after the parser propagates attributes at
1150 // template specialization definition, not declaration.
1151 //QualType ReturnType;
1153 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1154 // ReturnType = Param->getType();
1156 //} else if (const CXXConstructorDecl *Constructor =
1157 // dyn_cast<CXXConstructorDecl>(D)) {
1158 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1162 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1165 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1167 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1168 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1169 // ReturnType.getAsString();
1173 D->addAttr(::new (S.Context)
1174 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1175 Attr.getAttributeSpellingListIndex()));
1179 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1180 if (!checkAttributeNumArgs(S, Attr, 1))
1183 if (!isa<CXXMethodDecl>(D)) {
1184 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1185 Attr.getName() << ExpectedMethod;
1189 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1192 SetTypestateAttr::ConsumedState NewState;
1193 if (Attr.isArgIdent(0)) {
1194 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1195 StringRef Param = Ident->Ident->getName();
1196 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1197 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1198 << Attr.getName() << Param;
1202 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1203 Attr.getName() << AANT_ArgumentIdentifier;
1207 D->addAttr(::new (S.Context)
1208 SetTypestateAttr(Attr.getRange(), S.Context, NewState,
1209 Attr.getAttributeSpellingListIndex()));
1212 static void handleTestTypestateAttr(Sema &S, Decl *D,
1213 const AttributeList &Attr) {
1214 if (!checkAttributeNumArgs(S, Attr, 1))
1217 if (!isa<CXXMethodDecl>(D)) {
1218 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1219 Attr.getName() << ExpectedMethod;
1223 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1226 TestTypestateAttr::ConsumedState TestState;
1227 if (Attr.isArgIdent(0)) {
1228 IdentifierLoc *Ident = Attr.getArgAsIdent(0);
1229 StringRef Param = Ident->Ident->getName();
1230 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1231 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1232 << Attr.getName() << Param;
1236 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1237 Attr.getName() << AANT_ArgumentIdentifier;
1241 D->addAttr(::new (S.Context)
1242 TestTypestateAttr(Attr.getRange(), S.Context, TestState,
1243 Attr.getAttributeSpellingListIndex()));
1246 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1247 const AttributeList &Attr) {
1248 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
1250 // __attribute__((ext_vector_type(N))) can only be applied to typedefs
1252 S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
1256 // Remember this typedef decl, we will need it later for diagnostics.
1257 S.ExtVectorDecls.push_back(TD);
1260 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1261 if (TagDecl *TD = dyn_cast<TagDecl>(D))
1262 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context));
1263 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1264 // If the alignment is less than or equal to 8 bits, the packed attribute
1266 if (!FD->getType()->isDependentType() &&
1267 !FD->getType()->isIncompleteType() &&
1268 S.Context.getTypeAlign(FD->getType()) <= 8)
1269 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1270 << Attr.getName() << FD->getType();
1272 FD->addAttr(::new (S.Context)
1273 PackedAttr(Attr.getRange(), S.Context,
1274 Attr.getAttributeSpellingListIndex()));
1276 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1279 static void handleMsStructAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1280 if (RecordDecl *RD = dyn_cast<RecordDecl>(D))
1281 RD->addAttr(::new (S.Context)
1282 MsStructAttr(Attr.getRange(), S.Context,
1283 Attr.getAttributeSpellingListIndex()));
1285 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1288 static void handleIBAction(Sema &S, Decl *D, const AttributeList &Attr) {
1289 // The IBAction attributes only apply to instance methods.
1290 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
1291 if (MD->isInstanceMethod()) {
1292 D->addAttr(::new (S.Context)
1293 IBActionAttr(Attr.getRange(), S.Context,
1294 Attr.getAttributeSpellingListIndex()));
1298 S.Diag(Attr.getLoc(), diag::warn_attribute_ibaction) << Attr.getName();
1301 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1302 // The IBOutlet/IBOutletCollection attributes only apply to instance
1303 // variables or properties of Objective-C classes. The outlet must also
1304 // have an object reference type.
1305 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1306 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1307 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1308 << Attr.getName() << VD->getType() << 0;
1312 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1313 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1314 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1315 << Attr.getName() << PD->getType() << 1;
1320 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1327 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1328 if (!checkIBOutletCommon(S, D, Attr))
1331 D->addAttr(::new (S.Context)
1332 IBOutletAttr(Attr.getRange(), S.Context,
1333 Attr.getAttributeSpellingListIndex()));
1336 static void handleIBOutletCollection(Sema &S, Decl *D,
1337 const AttributeList &Attr) {
1339 // The iboutletcollection attribute can have zero or one arguments.
1340 if (Attr.getNumArgs() > 1) {
1341 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1342 << Attr.getName() << 1;
1346 if (!checkIBOutletCommon(S, D, Attr))
1351 if (Attr.hasParsedType())
1352 PT = Attr.getTypeArg();
1354 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
1355 S.getScopeForContext(D->getDeclContext()->getParent()));
1357 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1362 TypeSourceInfo *QTLoc = 0;
1363 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1365 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
1367 // Diagnose use of non-object type in iboutletcollection attribute.
1368 // FIXME. Gnu attribute extension ignores use of builtin types in
1369 // attributes. So, __attribute__((iboutletcollection(char))) will be
1370 // treated as __attribute__((iboutletcollection())).
1371 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1372 S.Diag(Attr.getLoc(),
1373 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1374 : diag::err_iboutletcollection_type) << QT;
1378 D->addAttr(::new (S.Context)
1379 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
1380 Attr.getAttributeSpellingListIndex()));
1383 static void possibleTransparentUnionPointerType(QualType &T) {
1384 if (const RecordType *UT = T->getAsUnionType())
1385 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1386 RecordDecl *UD = UT->getDecl();
1387 for (RecordDecl::field_iterator it = UD->field_begin(),
1388 itend = UD->field_end(); it != itend; ++it) {
1389 QualType QT = it->getType();
1390 if (QT->isAnyPointerType() || QT->isBlockPointerType()) {
1398 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1399 if (!isFunctionOrMethod(D)) {
1400 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1401 << Attr.getName() << ExpectedFunctionOrMethod;
1405 if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1408 SmallVector<unsigned, 8> SizeArgs;
1409 for (unsigned i = 0; i < Attr.getNumArgs(); ++i) {
1410 Expr *Ex = Attr.getArgAsExpr(i);
1412 if (!checkFunctionOrMethodArgumentIndex(S, D, Attr.getName()->getName(),
1413 Attr.getLoc(), i + 1, Ex, Idx))
1416 // check if the function argument is of an integer type
1417 QualType T = getFunctionOrMethodArgType(D, Idx).getNonReferenceType();
1418 if (!T->isIntegerType()) {
1419 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1420 << Attr.getName() << AANT_ArgumentIntegerConstant
1421 << Ex->getSourceRange();
1424 SizeArgs.push_back(Idx);
1427 // check if the function returns a pointer
1428 if (!getFunctionType(D)->getResultType()->isAnyPointerType()) {
1429 S.Diag(Attr.getLoc(), diag::warn_ns_attribute_wrong_return_type)
1430 << Attr.getName() << 0 /*function*/<< 1 /*pointer*/ << D->getSourceRange();
1433 D->addAttr(::new (S.Context)
1434 AllocSizeAttr(Attr.getRange(), S.Context,
1435 SizeArgs.data(), SizeArgs.size(),
1436 Attr.getAttributeSpellingListIndex()));
1439 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1440 // GCC ignores the nonnull attribute on K&R style function prototypes, so we
1441 // ignore it as well
1442 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
1443 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1444 << Attr.getName() << ExpectedFunction;
1448 SmallVector<unsigned, 8> NonNullArgs;
1449 for (unsigned i = 0; i < Attr.getNumArgs(); ++i) {
1450 Expr *Ex = Attr.getArgAsExpr(i);
1452 if (!checkFunctionOrMethodArgumentIndex(S, D, Attr.getName()->getName(),
1453 Attr.getLoc(), i + 1, Ex, Idx))
1456 // Is the function argument a pointer type?
1457 QualType T = getFunctionOrMethodArgType(D, Idx).getNonReferenceType();
1458 possibleTransparentUnionPointerType(T);
1460 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1461 // FIXME: Should also highlight argument in decl.
1462 S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
1463 << "nonnull" << Ex->getSourceRange();
1467 NonNullArgs.push_back(Idx);
1470 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1471 // arguments have a nonnull attribute.
1472 if (NonNullArgs.empty()) {
1473 for (unsigned i = 0, e = getFunctionOrMethodNumArgs(D); i != e; ++i) {
1474 QualType T = getFunctionOrMethodArgType(D, i).getNonReferenceType();
1475 possibleTransparentUnionPointerType(T);
1476 if (T->isAnyPointerType() || T->isBlockPointerType())
1477 NonNullArgs.push_back(i);
1480 // No pointer arguments?
1481 if (NonNullArgs.empty()) {
1482 // Warn the trivial case only if attribute is not coming from a
1483 // macro instantiation.
1484 if (Attr.getLoc().isFileID())
1485 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1490 unsigned *start = &NonNullArgs[0];
1491 unsigned size = NonNullArgs.size();
1492 llvm::array_pod_sort(start, start + size);
1493 D->addAttr(::new (S.Context)
1494 NonNullAttr(Attr.getRange(), S.Context, start, size,
1495 Attr.getAttributeSpellingListIndex()));
1498 static const char *ownershipKindToDiagName(OwnershipAttr::OwnershipKind K) {
1500 case OwnershipAttr::Holds: return "'ownership_holds'";
1501 case OwnershipAttr::Takes: return "'ownership_takes'";
1502 case OwnershipAttr::Returns: return "'ownership_returns'";
1504 llvm_unreachable("unknown ownership");
1507 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1508 // This attribute must be applied to a function declaration. The first
1509 // argument to the attribute must be an identifier, the name of the resource,
1510 // for example: malloc. The following arguments must be argument indexes, the
1511 // arguments must be of integer type for Returns, otherwise of pointer type.
1512 // The difference between Holds and Takes is that a pointer may still be used
1513 // after being held. free() should be __attribute((ownership_takes)), whereas
1514 // a list append function may well be __attribute((ownership_holds)).
1516 if (!AL.isArgIdent(0)) {
1517 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1518 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1522 // Figure out our Kind, and check arguments while we're at it.
1523 OwnershipAttr::OwnershipKind K;
1524 switch (AL.getKind()) {
1525 case AttributeList::AT_ownership_takes:
1526 K = OwnershipAttr::Takes;
1527 if (AL.getNumArgs() < 2) {
1528 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << 2;
1532 case AttributeList::AT_ownership_holds:
1533 K = OwnershipAttr::Holds;
1534 if (AL.getNumArgs() < 2) {
1535 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << 2;
1539 case AttributeList::AT_ownership_returns:
1540 K = OwnershipAttr::Returns;
1542 if (AL.getNumArgs() > 2) {
1543 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1548 // This should never happen given how we are called.
1549 llvm_unreachable("Unknown ownership attribute");
1552 if (!isFunction(D) || !hasFunctionProto(D)) {
1553 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
1554 << AL.getName() << ExpectedFunction;
1558 StringRef Module = AL.getArgAsIdent(0)->Ident->getName();
1560 // Normalize the argument, __foo__ becomes foo.
1561 if (Module.startswith("__") && Module.endswith("__"))
1562 Module = Module.substr(2, Module.size() - 4);
1564 SmallVector<unsigned, 8> OwnershipArgs;
1565 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1566 Expr *Ex = AL.getArgAsExpr(i);
1568 if (!checkFunctionOrMethodArgumentIndex(S, D, AL.getName()->getName(),
1569 AL.getLoc(), i, Ex, Idx))
1572 // Is the function argument a pointer type?
1573 QualType T = getFunctionOrMethodArgType(D, Idx);
1574 int Err = -1; // No error
1576 case OwnershipAttr::Takes:
1577 case OwnershipAttr::Holds:
1578 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1581 case OwnershipAttr::Returns:
1582 if (!T->isIntegerType())
1587 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1588 << Ex->getSourceRange();
1592 // Check we don't have a conflict with another ownership attribute.
1593 for (specific_attr_iterator<OwnershipAttr>
1594 i = D->specific_attr_begin<OwnershipAttr>(),
1595 e = D->specific_attr_end<OwnershipAttr>(); i != e; ++i) {
1596 if ((*i)->getOwnKind() != K && (*i)->args_end() !=
1597 std::find((*i)->args_begin(), (*i)->args_end(), Idx)) {
1598 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1599 << AL.getName() << ownershipKindToDiagName((*i)->getOwnKind());
1603 OwnershipArgs.push_back(Idx);
1606 unsigned* start = OwnershipArgs.data();
1607 unsigned size = OwnershipArgs.size();
1608 llvm::array_pod_sort(start, start + size);
1610 D->addAttr(::new (S.Context)
1611 OwnershipAttr(AL.getLoc(), S.Context, K, Module, start, size,
1612 AL.getAttributeSpellingListIndex()));
1615 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1616 // Check the attribute arguments.
1617 if (Attr.getNumArgs() > 1) {
1618 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1619 << Attr.getName() << 1;
1623 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
1624 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1625 << Attr.getName() << ExpectedVariableOrFunction;
1629 NamedDecl *nd = cast<NamedDecl>(D);
1633 // static int a __attribute__((weakref ("v2")));
1634 // static int b() __attribute__((weakref ("f3")));
1636 // and ignores the attributes of
1638 // static int a __attribute__((weakref ("v2")));
1641 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1642 if (!Ctx->isFileContext()) {
1643 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
1644 nd->getNameAsString();
1648 // The GCC manual says
1650 // At present, a declaration to which `weakref' is attached can only
1655 // Without a TARGET,
1656 // given as an argument to `weakref' or to `alias', `weakref' is
1657 // equivalent to `weak'.
1659 // gcc 4.4.1 will accept
1660 // int a7 __attribute__((weakref));
1662 // int a7 __attribute__((weak));
1663 // This looks like a bug in gcc. We reject that for now. We should revisit
1664 // it if this behaviour is actually used.
1667 // static ((alias ("y"), weakref)).
1668 // Should we? How to check that weakref is before or after alias?
1670 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1671 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1672 // StringRef parameter it was given anyway.
1674 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1675 // GCC will accept anything as the argument of weakref. Should we
1676 // check for an existing decl?
1677 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1678 Attr.getAttributeSpellingListIndex()));
1680 D->addAttr(::new (S.Context)
1681 WeakRefAttr(Attr.getRange(), S.Context,
1682 Attr.getAttributeSpellingListIndex()));
1685 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1687 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1690 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1691 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1695 // FIXME: check if target symbol exists in current file
1697 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1698 Attr.getAttributeSpellingListIndex()));
1701 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1702 if (!isa<FunctionDecl>(D) && !isa<ObjCMethodDecl>(D)) {
1703 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1704 << Attr.getName() << ExpectedFunctionOrMethod;
1708 D->addAttr(::new (S.Context)
1709 MinSizeAttr(Attr.getRange(), S.Context,
1710 Attr.getAttributeSpellingListIndex()));
1713 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1714 if (!isa<FunctionDecl>(D)) {
1715 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1716 << Attr.getName() << ExpectedFunction;
1720 if (D->hasAttr<HotAttr>()) {
1721 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1722 << Attr.getName() << "hot";
1726 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1727 Attr.getAttributeSpellingListIndex()));
1730 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1731 if (!isa<FunctionDecl>(D)) {
1732 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1733 << Attr.getName() << ExpectedFunction;
1737 if (D->hasAttr<ColdAttr>()) {
1738 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1739 << Attr.getName() << "cold";
1743 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1744 Attr.getAttributeSpellingListIndex()));
1747 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1748 if (!isa<FunctionDecl>(D)) {
1749 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1750 << Attr.getName() << ExpectedFunction;
1754 D->addAttr(::new (S.Context)
1755 NakedAttr(Attr.getRange(), S.Context,
1756 Attr.getAttributeSpellingListIndex()));
1759 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
1760 const AttributeList &Attr) {
1761 if (!isa<FunctionDecl>(D)) {
1762 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1763 << Attr.getName() << ExpectedFunction;
1767 D->addAttr(::new (S.Context)
1768 AlwaysInlineAttr(Attr.getRange(), S.Context,
1769 Attr.getAttributeSpellingListIndex()));
1772 static void handleTLSModelAttr(Sema &S, Decl *D,
1773 const AttributeList &Attr) {
1775 SourceLocation LiteralLoc;
1776 // Check that it is a string.
1777 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1780 if (!isa<VarDecl>(D) || !cast<VarDecl>(D)->getTLSKind()) {
1781 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1782 << Attr.getName() << ExpectedTLSVar;
1786 // Check that the value.
1787 if (Model != "global-dynamic" && Model != "local-dynamic"
1788 && Model != "initial-exec" && Model != "local-exec") {
1789 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1793 D->addAttr(::new (S.Context)
1794 TLSModelAttr(Attr.getRange(), S.Context, Model,
1795 Attr.getAttributeSpellingListIndex()));
1798 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1799 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1800 QualType RetTy = FD->getResultType();
1801 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1802 D->addAttr(::new (S.Context)
1803 MallocAttr(Attr.getRange(), S.Context,
1804 Attr.getAttributeSpellingListIndex()));
1809 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1812 static void handleMayAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1813 D->addAttr(::new (S.Context)
1814 MayAliasAttr(Attr.getRange(), S.Context,
1815 Attr.getAttributeSpellingListIndex()));
1818 static void handleNoCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1819 if (isa<VarDecl>(D))
1820 D->addAttr(::new (S.Context)
1821 NoCommonAttr(Attr.getRange(), S.Context,
1822 Attr.getAttributeSpellingListIndex()));
1824 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1825 << Attr.getName() << ExpectedVariable;
1828 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1829 if (S.LangOpts.CPlusPlus) {
1830 S.Diag(Attr.getLoc(), diag::err_common_not_supported_cplusplus);
1834 if (isa<VarDecl>(D))
1835 D->addAttr(::new (S.Context)
1836 CommonAttr(Attr.getRange(), S.Context,
1837 Attr.getAttributeSpellingListIndex()));
1839 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1840 << Attr.getName() << ExpectedVariable;
1843 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1844 if (hasDeclarator(D)) return;
1846 if (S.CheckNoReturnAttr(attr)) return;
1848 if (!isa<ObjCMethodDecl>(D)) {
1849 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1850 << attr.getName() << ExpectedFunctionOrMethod;
1854 D->addAttr(::new (S.Context)
1855 NoReturnAttr(attr.getRange(), S.Context,
1856 attr.getAttributeSpellingListIndex()));
1859 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1860 if (!checkAttributeNumArgs(*this, attr, 0)) {
1868 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1869 const AttributeList &Attr) {
1871 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1872 // because 'analyzer_noreturn' does not impact the type.
1873 if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1874 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1875 if (VD == 0 || (!VD->getType()->isBlockPointerType()
1876 && !VD->getType()->isFunctionPointerType())) {
1877 S.Diag(Attr.getLoc(),
1878 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1879 : diag::warn_attribute_wrong_decl_type)
1880 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1885 D->addAttr(::new (S.Context)
1886 AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1887 Attr.getAttributeSpellingListIndex()));
1890 static void handleCXX11NoReturnAttr(Sema &S, Decl *D,
1891 const AttributeList &Attr) {
1892 // C++11 [dcl.attr.noreturn]p1:
1893 // The attribute may be applied to the declarator-id in a function
1895 FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1897 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1898 << Attr.getName() << ExpectedFunctionOrMethod;
1902 D->addAttr(::new (S.Context)
1903 CXX11NoReturnAttr(Attr.getRange(), S.Context,
1904 Attr.getAttributeSpellingListIndex()));
1907 // PS3 PPU-specific.
1908 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1910 Returning a Vector Class in Registers
1912 According to the PPU ABI specifications, a class with a single member of
1913 vector type is returned in memory when used as the return value of a function.
1914 This results in inefficient code when implementing vector classes. To return
1915 the value in a single vector register, add the vecreturn attribute to the
1916 class definition. This attribute is also applicable to struct types.
1922 __vector float xyzw;
1923 } __attribute__((vecreturn));
1925 Vector Add(Vector lhs, Vector rhs)
1928 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1929 return result; // This will be returned in a register
1932 if (!isa<RecordDecl>(D)) {
1933 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1934 << Attr.getName() << ExpectedClass;
1938 if (D->getAttr<VecReturnAttr>()) {
1939 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
1943 RecordDecl *record = cast<RecordDecl>(D);
1946 if (!isa<CXXRecordDecl>(record)) {
1947 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1951 if (!cast<CXXRecordDecl>(record)->isPOD()) {
1952 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1956 for (RecordDecl::field_iterator iter = record->field_begin();
1957 iter != record->field_end(); iter++) {
1958 if ((count == 1) || !iter->getType()->isVectorType()) {
1959 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1965 D->addAttr(::new (S.Context)
1966 VecReturnAttr(Attr.getRange(), S.Context,
1967 Attr.getAttributeSpellingListIndex()));
1970 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1971 const AttributeList &Attr) {
1972 if (isa<ParmVarDecl>(D)) {
1973 // [[carries_dependency]] can only be applied to a parameter if it is a
1974 // parameter of a function declaration or lambda.
1975 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1976 S.Diag(Attr.getLoc(),
1977 diag::err_carries_dependency_param_not_function_decl);
1980 } else if (!isa<FunctionDecl>(D)) {
1981 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1982 << Attr.getName() << ExpectedFunctionMethodOrParameter;
1986 D->addAttr(::new (S.Context) CarriesDependencyAttr(
1987 Attr.getRange(), S.Context,
1988 Attr.getAttributeSpellingListIndex()));
1991 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1992 if (!isa<VarDecl>(D) && !isa<ObjCIvarDecl>(D) && !isFunctionOrMethod(D) &&
1993 !isa<TypeDecl>(D) && !isa<LabelDecl>(D) && !isa<FieldDecl>(D)) {
1994 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1995 << Attr.getName() << ExpectedVariableFunctionOrLabel;
1999 D->addAttr(::new (S.Context)
2000 UnusedAttr(Attr.getRange(), S.Context,
2001 Attr.getAttributeSpellingListIndex()));
2004 static void handleReturnsTwiceAttr(Sema &S, Decl *D,
2005 const AttributeList &Attr) {
2006 if (!isa<FunctionDecl>(D)) {
2007 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2008 << Attr.getName() << ExpectedFunction;
2012 D->addAttr(::new (S.Context)
2013 ReturnsTwiceAttr(Attr.getRange(), S.Context,
2014 Attr.getAttributeSpellingListIndex()));
2017 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2018 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2019 if (VD->hasLocalStorage()) {
2020 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
2023 } else if (!isFunctionOrMethod(D)) {
2024 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2025 << Attr.getName() << ExpectedVariableOrFunction;
2029 D->addAttr(::new (S.Context)
2030 UsedAttr(Attr.getRange(), S.Context,
2031 Attr.getAttributeSpellingListIndex()));
2034 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2035 // check the attribute arguments.
2036 if (Attr.getNumArgs() > 1) {
2037 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
2041 int priority = 65535; // FIXME: Do not hardcode such constants.
2042 if (Attr.getNumArgs() > 0) {
2043 Expr *E = Attr.getArgAsExpr(0);
2044 llvm::APSInt Idx(32);
2045 if (E->isTypeDependent() || E->isValueDependent() ||
2046 !E->isIntegerConstantExpr(Idx, S.Context)) {
2047 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2048 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2049 << E->getSourceRange();
2052 priority = Idx.getZExtValue();
2055 if (!isa<FunctionDecl>(D)) {
2056 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2057 << Attr.getName() << ExpectedFunction;
2061 D->addAttr(::new (S.Context)
2062 ConstructorAttr(Attr.getRange(), S.Context, priority,
2063 Attr.getAttributeSpellingListIndex()));
2066 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2067 // check the attribute arguments.
2068 if (Attr.getNumArgs() > 1) {
2069 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
2073 int priority = 65535; // FIXME: Do not hardcode such constants.
2074 if (Attr.getNumArgs() > 0) {
2075 Expr *E = Attr.getArgAsExpr(0);
2076 llvm::APSInt Idx(32);
2077 if (E->isTypeDependent() || E->isValueDependent() ||
2078 !E->isIntegerConstantExpr(Idx, S.Context)) {
2079 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2080 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2081 << E->getSourceRange();
2084 priority = Idx.getZExtValue();
2087 if (!isa<FunctionDecl>(D)) {
2088 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2089 << Attr.getName() << ExpectedFunction;
2093 D->addAttr(::new (S.Context)
2094 DestructorAttr(Attr.getRange(), S.Context, priority,
2095 Attr.getAttributeSpellingListIndex()));
2098 template <typename AttrTy>
2099 static void handleAttrWithMessage(Sema &S, Decl *D,
2100 const AttributeList &Attr) {
2101 unsigned NumArgs = Attr.getNumArgs();
2103 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
2107 // Handle the case where the attribute has a text message.
2109 if (NumArgs == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2112 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2113 Attr.getAttributeSpellingListIndex()));
2116 static void handleArcWeakrefUnavailableAttr(Sema &S, Decl *D,
2117 const AttributeList &Attr) {
2118 D->addAttr(::new (S.Context)
2119 ArcWeakrefUnavailableAttr(Attr.getRange(), S.Context,
2120 Attr.getAttributeSpellingListIndex()));
2123 static void handleObjCRootClassAttr(Sema &S, Decl *D,
2124 const AttributeList &Attr) {
2125 if (!isa<ObjCInterfaceDecl>(D)) {
2126 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2127 << Attr.getName() << ExpectedObjectiveCInterface;
2131 D->addAttr(::new (S.Context)
2132 ObjCRootClassAttr(Attr.getRange(), S.Context,
2133 Attr.getAttributeSpellingListIndex()));
2136 static void handleObjCRequiresPropertyDefsAttr(Sema &S, Decl *D,
2137 const AttributeList &Attr) {
2138 if (!isa<ObjCInterfaceDecl>(D)) {
2139 S.Diag(Attr.getLoc(), diag::err_suppress_autosynthesis);
2143 D->addAttr(::new (S.Context)
2144 ObjCRequiresPropertyDefsAttr(Attr.getRange(), S.Context,
2145 Attr.getAttributeSpellingListIndex()));
2148 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2149 IdentifierInfo *Platform,
2150 VersionTuple Introduced,
2151 VersionTuple Deprecated,
2152 VersionTuple Obsoleted) {
2153 StringRef PlatformName
2154 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2155 if (PlatformName.empty())
2156 PlatformName = Platform->getName();
2158 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2159 // of these steps are needed).
2160 if (!Introduced.empty() && !Deprecated.empty() &&
2161 !(Introduced <= Deprecated)) {
2162 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2163 << 1 << PlatformName << Deprecated.getAsString()
2164 << 0 << Introduced.getAsString();
2168 if (!Introduced.empty() && !Obsoleted.empty() &&
2169 !(Introduced <= Obsoleted)) {
2170 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2171 << 2 << PlatformName << Obsoleted.getAsString()
2172 << 0 << Introduced.getAsString();
2176 if (!Deprecated.empty() && !Obsoleted.empty() &&
2177 !(Deprecated <= Obsoleted)) {
2178 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2179 << 2 << PlatformName << Obsoleted.getAsString()
2180 << 1 << Deprecated.getAsString();
2187 /// \brief Check whether the two versions match.
2189 /// If either version tuple is empty, then they are assumed to match. If
2190 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2191 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2192 bool BeforeIsOkay) {
2193 if (X.empty() || Y.empty())
2199 if (BeforeIsOkay && X < Y)
2205 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2206 IdentifierInfo *Platform,
2207 VersionTuple Introduced,
2208 VersionTuple Deprecated,
2209 VersionTuple Obsoleted,
2213 unsigned AttrSpellingListIndex) {
2214 VersionTuple MergedIntroduced = Introduced;
2215 VersionTuple MergedDeprecated = Deprecated;
2216 VersionTuple MergedObsoleted = Obsoleted;
2217 bool FoundAny = false;
2219 if (D->hasAttrs()) {
2220 AttrVec &Attrs = D->getAttrs();
2221 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2222 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2228 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2229 if (OldPlatform != Platform) {
2235 VersionTuple OldIntroduced = OldAA->getIntroduced();
2236 VersionTuple OldDeprecated = OldAA->getDeprecated();
2237 VersionTuple OldObsoleted = OldAA->getObsoleted();
2238 bool OldIsUnavailable = OldAA->getUnavailable();
2240 if (!versionsMatch(OldIntroduced, Introduced, Override) ||
2241 !versionsMatch(Deprecated, OldDeprecated, Override) ||
2242 !versionsMatch(Obsoleted, OldObsoleted, Override) ||
2243 !(OldIsUnavailable == IsUnavailable ||
2244 (Override && !OldIsUnavailable && IsUnavailable))) {
2247 VersionTuple FirstVersion;
2248 VersionTuple SecondVersion;
2249 if (!versionsMatch(OldIntroduced, Introduced, Override)) {
2251 FirstVersion = OldIntroduced;
2252 SecondVersion = Introduced;
2253 } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
2255 FirstVersion = Deprecated;
2256 SecondVersion = OldDeprecated;
2257 } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
2259 FirstVersion = Obsoleted;
2260 SecondVersion = OldObsoleted;
2264 Diag(OldAA->getLocation(),
2265 diag::warn_mismatched_availability_override_unavail)
2266 << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2268 Diag(OldAA->getLocation(),
2269 diag::warn_mismatched_availability_override)
2271 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2272 << FirstVersion.getAsString() << SecondVersion.getAsString();
2274 Diag(Range.getBegin(), diag::note_overridden_method);
2276 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2277 Diag(Range.getBegin(), diag::note_previous_attribute);
2280 Attrs.erase(Attrs.begin() + i);
2285 VersionTuple MergedIntroduced2 = MergedIntroduced;
2286 VersionTuple MergedDeprecated2 = MergedDeprecated;
2287 VersionTuple MergedObsoleted2 = MergedObsoleted;
2289 if (MergedIntroduced2.empty())
2290 MergedIntroduced2 = OldIntroduced;
2291 if (MergedDeprecated2.empty())
2292 MergedDeprecated2 = OldDeprecated;
2293 if (MergedObsoleted2.empty())
2294 MergedObsoleted2 = OldObsoleted;
2296 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2297 MergedIntroduced2, MergedDeprecated2,
2298 MergedObsoleted2)) {
2299 Attrs.erase(Attrs.begin() + i);
2304 MergedIntroduced = MergedIntroduced2;
2305 MergedDeprecated = MergedDeprecated2;
2306 MergedObsoleted = MergedObsoleted2;
2312 MergedIntroduced == Introduced &&
2313 MergedDeprecated == Deprecated &&
2314 MergedObsoleted == Obsoleted)
2317 // Only create a new attribute if !Override, but we want to do
2319 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2320 MergedDeprecated, MergedObsoleted) &&
2322 return ::new (Context) AvailabilityAttr(Range, Context, Platform,
2323 Introduced, Deprecated,
2324 Obsoleted, IsUnavailable, Message,
2325 AttrSpellingListIndex);
2330 static void handleAvailabilityAttr(Sema &S, Decl *D,
2331 const AttributeList &Attr) {
2332 if (!checkAttributeNumArgs(S, Attr, 1))
2334 IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2335 unsigned Index = Attr.getAttributeSpellingListIndex();
2337 IdentifierInfo *II = Platform->Ident;
2338 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2339 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2342 NamedDecl *ND = dyn_cast<NamedDecl>(D);
2344 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2348 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2349 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2350 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2351 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2353 if (const StringLiteral *SE =
2354 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2355 Str = SE->getString();
2357 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2365 D->addAttr(NewAttr);
2369 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2370 typename T::VisibilityType value,
2371 unsigned attrSpellingListIndex) {
2372 T *existingAttr = D->getAttr<T>();
2374 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2375 if (existingValue == value)
2377 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2378 S.Diag(range.getBegin(), diag::note_previous_attribute);
2381 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2384 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2385 VisibilityAttr::VisibilityType Vis,
2386 unsigned AttrSpellingListIndex) {
2387 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2388 AttrSpellingListIndex);
2391 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2392 TypeVisibilityAttr::VisibilityType Vis,
2393 unsigned AttrSpellingListIndex) {
2394 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2395 AttrSpellingListIndex);
2398 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2399 bool isTypeVisibility) {
2400 // Visibility attributes don't mean anything on a typedef.
2401 if (isa<TypedefNameDecl>(D)) {
2402 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2407 // 'type_visibility' can only go on a type or namespace.
2408 if (isTypeVisibility &&
2409 !(isa<TagDecl>(D) ||
2410 isa<ObjCInterfaceDecl>(D) ||
2411 isa<NamespaceDecl>(D))) {
2412 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2413 << Attr.getName() << ExpectedTypeOrNamespace;
2417 // Check that the argument is a string literal.
2419 SourceLocation LiteralLoc;
2420 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2423 VisibilityAttr::VisibilityType type;
2424 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2425 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2426 << Attr.getName() << TypeStr;
2430 // Complain about attempts to use protected visibility on targets
2431 // (like Darwin) that don't support it.
2432 if (type == VisibilityAttr::Protected &&
2433 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2434 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2435 type = VisibilityAttr::Default;
2438 unsigned Index = Attr.getAttributeSpellingListIndex();
2439 clang::Attr *newAttr;
2440 if (isTypeVisibility) {
2441 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2442 (TypeVisibilityAttr::VisibilityType) type,
2445 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2448 D->addAttr(newAttr);
2451 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2452 const AttributeList &Attr) {
2453 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(decl);
2455 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2460 if (!Attr.isArgIdent(0)) {
2461 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2462 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2466 IdentifierLoc *IL = Attr.getArgAsIdent(0);
2467 ObjCMethodFamilyAttr::FamilyKind F;
2468 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2469 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2474 if (F == ObjCMethodFamilyAttr::OMF_init &&
2475 !method->getResultType()->isObjCObjectPointerType()) {
2476 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2477 << method->getResultType();
2478 // Ignore the attribute.
2482 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2486 static void handleObjCExceptionAttr(Sema &S, Decl *D,
2487 const AttributeList &Attr) {
2488 ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
2490 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2491 << Attr.getName() << ExpectedObjectiveCInterface;
2495 D->addAttr(::new (S.Context)
2496 ObjCExceptionAttr(Attr.getRange(), S.Context,
2497 Attr.getAttributeSpellingListIndex()));
2500 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2501 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2502 QualType T = TD->getUnderlyingType();
2503 if (!T->isCARCBridgableType()) {
2504 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2508 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2509 QualType T = PD->getType();
2510 if (!T->isCARCBridgableType()) {
2511 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2516 // It is okay to include this attribute on properties, e.g.:
2518 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2520 // In this case it follows tradition and suppresses an error in the above
2522 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2524 D->addAttr(::new (S.Context)
2525 ObjCNSObjectAttr(Attr.getRange(), S.Context,
2526 Attr.getAttributeSpellingListIndex()));
2530 handleOverloadableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2531 if (!isa<FunctionDecl>(D)) {
2532 S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
2536 D->addAttr(::new (S.Context)
2537 OverloadableAttr(Attr.getRange(), S.Context,
2538 Attr.getAttributeSpellingListIndex()));
2541 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2542 if (!Attr.isArgIdent(0)) {
2543 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2544 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2548 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2549 BlocksAttr::BlockType type;
2550 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2551 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2552 << Attr.getName() << II;
2556 D->addAttr(::new (S.Context)
2557 BlocksAttr(Attr.getRange(), S.Context, type,
2558 Attr.getAttributeSpellingListIndex()));
2561 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2562 // check the attribute arguments.
2563 if (Attr.getNumArgs() > 2) {
2564 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
2568 unsigned sentinel = 0;
2569 if (Attr.getNumArgs() > 0) {
2570 Expr *E = Attr.getArgAsExpr(0);
2571 llvm::APSInt Idx(32);
2572 if (E->isTypeDependent() || E->isValueDependent() ||
2573 !E->isIntegerConstantExpr(Idx, S.Context)) {
2574 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2575 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2576 << E->getSourceRange();
2580 if (Idx.isSigned() && Idx.isNegative()) {
2581 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2582 << E->getSourceRange();
2586 sentinel = Idx.getZExtValue();
2589 unsigned nullPos = 0;
2590 if (Attr.getNumArgs() > 1) {
2591 Expr *E = Attr.getArgAsExpr(1);
2592 llvm::APSInt Idx(32);
2593 if (E->isTypeDependent() || E->isValueDependent() ||
2594 !E->isIntegerConstantExpr(Idx, S.Context)) {
2595 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2596 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2597 << E->getSourceRange();
2600 nullPos = Idx.getZExtValue();
2602 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2603 // FIXME: This error message could be improved, it would be nice
2604 // to say what the bounds actually are.
2605 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2606 << E->getSourceRange();
2611 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2612 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2613 if (isa<FunctionNoProtoType>(FT)) {
2614 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2618 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2619 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2622 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2623 if (!MD->isVariadic()) {
2624 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2627 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2628 if (!BD->isVariadic()) {
2629 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2632 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2633 QualType Ty = V->getType();
2634 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2635 const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(D)
2636 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2637 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2638 int m = Ty->isFunctionPointerType() ? 0 : 1;
2639 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2643 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2644 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2648 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2649 << Attr.getName() << ExpectedFunctionMethodOrBlock;
2652 D->addAttr(::new (S.Context)
2653 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2654 Attr.getAttributeSpellingListIndex()));
2657 static void handleWarnUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2658 if (RecordDecl *RD = dyn_cast<RecordDecl>(D))
2659 RD->addAttr(::new (S.Context) WarnUnusedAttr(Attr.getRange(), S.Context));
2661 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2664 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2665 if (!isFunction(D) && !isa<ObjCMethodDecl>(D) && !isa<CXXRecordDecl>(D)) {
2666 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2667 << Attr.getName() << ExpectedFunctionMethodOrClass;
2671 if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
2672 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2673 << Attr.getName() << 0;
2676 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2677 if (MD->getResultType()->isVoidType()) {
2678 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2679 << Attr.getName() << 1;
2683 D->addAttr(::new (S.Context)
2684 WarnUnusedResultAttr(Attr.getRange(), S.Context,
2685 Attr.getAttributeSpellingListIndex()));
2688 static void handleWeakAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2689 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
2690 if (isa<CXXRecordDecl>(D)) {
2691 D->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
2694 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2695 << Attr.getName() << ExpectedVariableOrFunction;
2699 NamedDecl *nd = cast<NamedDecl>(D);
2701 nd->addAttr(::new (S.Context)
2702 WeakAttr(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 static void handleWorkGroupSize(Sema &S, Decl *D,
2731 const AttributeList &Attr) {
2733 for (unsigned i = 0; i < 3; ++i) {
2734 Expr *E = Attr.getArgAsExpr(i);
2735 llvm::APSInt ArgNum(32);
2736 if (E->isTypeDependent() || E->isValueDependent() ||
2737 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
2738 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
2739 << Attr.getName() << AANT_ArgumentIntegerConstant
2740 << E->getSourceRange();
2743 WGSize[i] = (unsigned) ArgNum.getZExtValue();
2746 if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2747 && D->hasAttr<ReqdWorkGroupSizeAttr>()) {
2748 ReqdWorkGroupSizeAttr *A = D->getAttr<ReqdWorkGroupSizeAttr>();
2749 if (!(A->getXDim() == WGSize[0] &&
2750 A->getYDim() == WGSize[1] &&
2751 A->getZDim() == WGSize[2])) {
2752 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2757 if (Attr.getKind() == AttributeList::AT_WorkGroupSizeHint
2758 && D->hasAttr<WorkGroupSizeHintAttr>()) {
2759 WorkGroupSizeHintAttr *A = D->getAttr<WorkGroupSizeHintAttr>();
2760 if (!(A->getXDim() == WGSize[0] &&
2761 A->getYDim() == WGSize[1] &&
2762 A->getZDim() == WGSize[2])) {
2763 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2768 if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize)
2769 D->addAttr(::new (S.Context)
2770 ReqdWorkGroupSizeAttr(Attr.getRange(), S.Context,
2771 WGSize[0], WGSize[1], WGSize[2],
2772 Attr.getAttributeSpellingListIndex()));
2774 D->addAttr(::new (S.Context)
2775 WorkGroupSizeHintAttr(Attr.getRange(), S.Context,
2776 WGSize[0], WGSize[1], WGSize[2],
2777 Attr.getAttributeSpellingListIndex()));
2780 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2781 assert(Attr.getKind() == AttributeList::AT_VecTypeHint);
2783 if (!Attr.hasParsedType()) {
2784 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2785 << Attr.getName() << 1;
2789 TypeSourceInfo *ParmTSI = 0;
2790 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
2791 assert(ParmTSI && "no type source info for attribute argument");
2793 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2794 (ParmType->isBooleanType() ||
2795 !ParmType->isIntegralType(S.getASTContext()))) {
2796 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2801 if (Attr.getKind() == AttributeList::AT_VecTypeHint &&
2802 D->hasAttr<VecTypeHintAttr>()) {
2803 VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>();
2804 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2805 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2810 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2814 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2816 unsigned AttrSpellingListIndex) {
2817 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2818 if (ExistingAttr->getName() == Name)
2820 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2821 Diag(Range.getBegin(), diag::note_previous_attribute);
2824 return ::new (Context) SectionAttr(Range, Context, Name,
2825 AttrSpellingListIndex);
2828 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2829 // Make sure that there is a string literal as the sections's single
2832 SourceLocation LiteralLoc;
2833 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2836 // If the target wants to validate the section specifier, make it happen.
2837 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2838 if (!Error.empty()) {
2839 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2844 // This attribute cannot be applied to local variables.
2845 if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
2846 S.Diag(LiteralLoc, diag::err_attribute_section_local_variable);
2850 unsigned Index = Attr.getAttributeSpellingListIndex();
2851 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2853 D->addAttr(NewAttr);
2857 static void handleNothrowAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2858 if (NoThrowAttr *Existing = D->getAttr<NoThrowAttr>()) {
2859 if (Existing->getLocation().isInvalid())
2860 Existing->setRange(Attr.getRange());
2862 D->addAttr(::new (S.Context)
2863 NoThrowAttr(Attr.getRange(), S.Context,
2864 Attr.getAttributeSpellingListIndex()));
2868 static void handleConstAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2869 if (ConstAttr *Existing = D->getAttr<ConstAttr>()) {
2870 if (Existing->getLocation().isInvalid())
2871 Existing->setRange(Attr.getRange());
2873 D->addAttr(::new (S.Context)
2874 ConstAttr(Attr.getRange(), S.Context,
2875 Attr.getAttributeSpellingListIndex() ));
2879 static void handlePureAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2880 D->addAttr(::new (S.Context)
2881 PureAttr(Attr.getRange(), S.Context,
2882 Attr.getAttributeSpellingListIndex()));
2885 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2886 VarDecl *VD = dyn_cast<VarDecl>(D);
2887 if (!VD || !VD->hasLocalStorage()) {
2888 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2892 Expr *E = Attr.getArgAsExpr(0);
2893 SourceLocation Loc = E->getExprLoc();
2894 FunctionDecl *FD = 0;
2895 DeclarationNameInfo NI;
2897 // gcc only allows for simple identifiers. Since we support more than gcc, we
2898 // will warn the user.
2899 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2900 if (DRE->hasQualifier())
2901 S.Diag(Loc, diag::warn_cleanup_ext);
2902 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2903 NI = DRE->getNameInfo();
2905 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2909 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2910 if (ULE->hasExplicitTemplateArgs())
2911 S.Diag(Loc, diag::warn_cleanup_ext);
2912 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2913 NI = ULE->getNameInfo();
2915 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
2917 if (ULE->getType() == S.Context.OverloadTy)
2918 S.NoteAllOverloadCandidates(ULE);
2922 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2926 if (FD->getNumParams() != 1) {
2927 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2932 // We're currently more strict than GCC about what function types we accept.
2933 // If this ever proves to be a problem it should be easy to fix.
2934 QualType Ty = S.Context.getPointerType(VD->getType());
2935 QualType ParamTy = FD->getParamDecl(0)->getType();
2936 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2937 ParamTy, Ty) != Sema::Compatible) {
2938 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2939 << NI.getName() << ParamTy << Ty;
2943 D->addAttr(::new (S.Context)
2944 CleanupAttr(Attr.getRange(), S.Context, FD,
2945 Attr.getAttributeSpellingListIndex()));
2948 /// Handle __attribute__((format_arg((idx)))) attribute based on
2949 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2950 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2951 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
2952 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2953 << Attr.getName() << ExpectedFunction;
2957 Expr *IdxExpr = Attr.getArgAsExpr(0);
2959 if (!checkFunctionOrMethodArgumentIndex(S, D, Attr.getName()->getName(),
2960 Attr.getLoc(), 1, IdxExpr, ArgIdx))
2963 // make sure the format string is really a string
2964 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2966 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2967 if (not_nsstring_type &&
2968 !isCFStringType(Ty, S.Context) &&
2969 (!Ty->isPointerType() ||
2970 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2971 // FIXME: Should highlight the actual expression that has the wrong type.
2972 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2973 << (not_nsstring_type ? "a string type" : "an NSString")
2974 << IdxExpr->getSourceRange();
2977 Ty = getFunctionOrMethodResultType(D);
2978 if (!isNSStringType(Ty, S.Context) &&
2979 !isCFStringType(Ty, S.Context) &&
2980 (!Ty->isPointerType() ||
2981 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2982 // FIXME: Should highlight the actual expression that has the wrong type.
2983 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2984 << (not_nsstring_type ? "string type" : "NSString")
2985 << IdxExpr->getSourceRange();
2989 // We cannot use the ArgIdx returned from checkFunctionOrMethodArgumentIndex
2990 // because that has corrected for the implicit this parameter, and is zero-
2991 // based. The attribute expects what the user wrote explicitly.
2993 IdxExpr->EvaluateAsInt(Val, S.Context);
2995 D->addAttr(::new (S.Context)
2996 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2997 Attr.getAttributeSpellingListIndex()));
3000 enum FormatAttrKind {
3009 /// getFormatAttrKind - Map from format attribute names to supported format
3011 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3012 return llvm::StringSwitch<FormatAttrKind>(Format)
3013 // Check for formats that get handled specially.
3014 .Case("NSString", NSStringFormat)
3015 .Case("CFString", CFStringFormat)
3016 .Case("strftime", StrftimeFormat)
3018 // Otherwise, check for supported formats.
3019 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3020 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3021 .Case("kprintf", SupportedFormat) // OpenBSD.
3023 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3024 .Default(InvalidFormat);
3027 /// Handle __attribute__((init_priority(priority))) attributes based on
3028 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3029 static void handleInitPriorityAttr(Sema &S, Decl *D,
3030 const AttributeList &Attr) {
3031 if (!S.getLangOpts().CPlusPlus) {
3032 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
3036 if (!isa<VarDecl>(D) || S.getCurFunctionOrMethodDecl()) {
3037 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3041 QualType T = dyn_cast<VarDecl>(D)->getType();
3042 if (S.Context.getAsArrayType(T))
3043 T = S.Context.getBaseElementType(T);
3044 if (!T->getAs<RecordType>()) {
3045 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
3050 Expr *priorityExpr = Attr.getArgAsExpr(0);
3052 llvm::APSInt priority(32);
3053 if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
3054 !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
3055 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3056 << Attr.getName() << AANT_ArgumentIntegerConstant
3057 << priorityExpr->getSourceRange();
3061 unsigned prioritynum = priority.getZExtValue();
3062 if (prioritynum < 101 || prioritynum > 65535) {
3063 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
3064 << priorityExpr->getSourceRange();
3068 D->addAttr(::new (S.Context)
3069 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
3070 Attr.getAttributeSpellingListIndex()));
3073 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3074 IdentifierInfo *Format, int FormatIdx,
3076 unsigned AttrSpellingListIndex) {
3077 // Check whether we already have an equivalent format attribute.
3078 for (specific_attr_iterator<FormatAttr>
3079 i = D->specific_attr_begin<FormatAttr>(),
3080 e = D->specific_attr_end<FormatAttr>();
3083 if (f->getType() == Format &&
3084 f->getFormatIdx() == FormatIdx &&
3085 f->getFirstArg() == FirstArg) {
3086 // If we don't have a valid location for this attribute, adopt the
3088 if (f->getLocation().isInvalid())
3094 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3095 FirstArg, AttrSpellingListIndex);
3098 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3099 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3100 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3101 if (!Attr.isArgIdent(0)) {
3102 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3103 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3107 if (!isFunctionOrMethodOrBlock(D) || !hasFunctionProto(D)) {
3108 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3109 << Attr.getName() << ExpectedFunction;
3113 // In C++ the implicit 'this' function parameter also counts, and they are
3114 // counted from one.
3115 bool HasImplicitThisParam = isInstanceMethod(D);
3116 unsigned NumArgs = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
3117 unsigned FirstIdx = 1;
3119 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3120 StringRef Format = II->getName();
3122 // Normalize the argument, __foo__ becomes foo.
3123 if (Format.startswith("__") && Format.endswith("__")) {
3124 Format = Format.substr(2, Format.size() - 4);
3125 // If we've modified the string name, we need a new identifier for it.
3126 II = &S.Context.Idents.get(Format);
3129 // Check for supported formats.
3130 FormatAttrKind Kind = getFormatAttrKind(Format);
3132 if (Kind == IgnoredFormat)
3135 if (Kind == InvalidFormat) {
3136 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3137 << "format" << II->getName();
3141 // checks for the 2nd argument
3142 Expr *IdxExpr = Attr.getArgAsExpr(1);
3143 llvm::APSInt Idx(32);
3144 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
3145 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
3146 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3147 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
3148 << IdxExpr->getSourceRange();
3152 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
3153 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3154 << "format" << 2 << IdxExpr->getSourceRange();
3158 // FIXME: Do we need to bounds check?
3159 unsigned ArgIdx = Idx.getZExtValue() - 1;
3161 if (HasImplicitThisParam) {
3163 S.Diag(Attr.getLoc(),
3164 diag::err_format_attribute_implicit_this_format_string)
3165 << IdxExpr->getSourceRange();
3171 // make sure the format string is really a string
3172 QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
3174 if (Kind == CFStringFormat) {
3175 if (!isCFStringType(Ty, S.Context)) {
3176 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3177 << "a CFString" << IdxExpr->getSourceRange();
3180 } else if (Kind == NSStringFormat) {
3181 // FIXME: do we need to check if the type is NSString*? What are the
3183 if (!isNSStringType(Ty, S.Context)) {
3184 // FIXME: Should highlight the actual expression that has the wrong type.
3185 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3186 << "an NSString" << IdxExpr->getSourceRange();
3189 } else if (!Ty->isPointerType() ||
3190 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3191 // FIXME: Should highlight the actual expression that has the wrong type.
3192 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3193 << "a string type" << IdxExpr->getSourceRange();
3197 // check the 3rd argument
3198 Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3199 llvm::APSInt FirstArg(32);
3200 if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
3201 !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
3202 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3203 << Attr.getName() << 3 << AANT_ArgumentIntegerConstant
3204 << FirstArgExpr->getSourceRange();
3208 // check if the function is variadic if the 3rd argument non-zero
3209 if (FirstArg != 0) {
3210 if (isFunctionOrMethodVariadic(D)) {
3211 ++NumArgs; // +1 for ...
3213 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3218 // strftime requires FirstArg to be 0 because it doesn't read from any
3219 // variable the input is just the current time + the format string.
3220 if (Kind == StrftimeFormat) {
3221 if (FirstArg != 0) {
3222 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3223 << FirstArgExpr->getSourceRange();
3226 // if 0 it disables parameter checking (to use with e.g. va_list)
3227 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3228 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3229 << "format" << 3 << FirstArgExpr->getSourceRange();
3233 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3235 FirstArg.getZExtValue(),
3236 Attr.getAttributeSpellingListIndex());
3238 D->addAttr(NewAttr);
3241 static void handleTransparentUnionAttr(Sema &S, Decl *D,
3242 const AttributeList &Attr) {
3243 // Try to find the underlying union declaration.
3245 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3246 if (TD && TD->getUnderlyingType()->isUnionType())
3247 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3249 RD = dyn_cast<RecordDecl>(D);
3251 if (!RD || !RD->isUnion()) {
3252 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3253 << Attr.getName() << ExpectedUnion;
3257 if (!RD->isCompleteDefinition()) {
3258 S.Diag(Attr.getLoc(),
3259 diag::warn_transparent_union_attribute_not_definition);
3263 RecordDecl::field_iterator Field = RD->field_begin(),
3264 FieldEnd = RD->field_end();
3265 if (Field == FieldEnd) {
3266 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3270 FieldDecl *FirstField = *Field;
3271 QualType FirstType = FirstField->getType();
3272 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3273 S.Diag(FirstField->getLocation(),
3274 diag::warn_transparent_union_attribute_floating)
3275 << FirstType->isVectorType() << FirstType;
3279 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3280 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3281 for (; Field != FieldEnd; ++Field) {
3282 QualType FieldType = Field->getType();
3283 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3284 S.Context.getTypeAlign(FieldType) != FirstAlign) {
3285 // Warn if we drop the attribute.
3286 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3287 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3288 : S.Context.getTypeAlign(FieldType);
3289 S.Diag(Field->getLocation(),
3290 diag::warn_transparent_union_attribute_field_size_align)
3291 << isSize << Field->getDeclName() << FieldBits;
3292 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3293 S.Diag(FirstField->getLocation(),
3294 diag::note_transparent_union_first_field_size_align)
3295 << isSize << FirstBits;
3300 RD->addAttr(::new (S.Context)
3301 TransparentUnionAttr(Attr.getRange(), S.Context,
3302 Attr.getAttributeSpellingListIndex()));
3305 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3306 // Make sure that there is a string literal as the annotation's single
3309 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3312 // Don't duplicate annotations that are already set.
3313 for (specific_attr_iterator<AnnotateAttr>
3314 i = D->specific_attr_begin<AnnotateAttr>(),
3315 e = D->specific_attr_end<AnnotateAttr>(); i != e; ++i) {
3316 if ((*i)->getAnnotation() == Str)
3320 D->addAttr(::new (S.Context)
3321 AnnotateAttr(Attr.getRange(), S.Context, Str,
3322 Attr.getAttributeSpellingListIndex()));
3325 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3326 // check the attribute arguments.
3327 if (Attr.getNumArgs() > 1) {
3328 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3329 << Attr.getName() << 1;
3333 if (Attr.getNumArgs() == 0) {
3334 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3335 true, 0, Attr.getAttributeSpellingListIndex()));
3339 Expr *E = Attr.getArgAsExpr(0);
3340 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3341 S.Diag(Attr.getEllipsisLoc(),
3342 diag::err_pack_expansion_without_parameter_packs);
3346 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3349 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3350 Attr.isPackExpansion());
3353 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3354 unsigned SpellingListIndex, bool IsPackExpansion) {
3355 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3356 SourceLocation AttrLoc = AttrRange.getBegin();
3358 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3359 if (TmpAttr.isAlignas()) {
3360 // C++11 [dcl.align]p1:
3361 // An alignment-specifier may be applied to a variable or to a class
3362 // data member, but it shall not be applied to a bit-field, a function
3363 // parameter, the formal parameter of a catch clause, or a variable
3364 // declared with the register storage class specifier. An
3365 // alignment-specifier may also be applied to the declaration of a class
3366 // or enumeration type.
3368 // An alignment attribute shall not be specified in a declaration of
3369 // a typedef, or a bit-field, or a function, or a parameter, or an
3370 // object declared with the register storage-class specifier.
3372 if (isa<ParmVarDecl>(D)) {
3374 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3375 if (VD->getStorageClass() == SC_Register)
3377 if (VD->isExceptionVariable())
3379 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3380 if (FD->isBitField())
3382 } else if (!isa<TagDecl>(D)) {
3383 Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
3384 << (TmpAttr.isC11() ? "'_Alignas'" : "'alignas'")
3385 << (TmpAttr.isC11() ? ExpectedVariableOrField
3386 : ExpectedVariableFieldOrTag);
3389 if (DiagKind != -1) {
3390 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3391 << TmpAttr.isC11() << DiagKind;
3396 if (E->isTypeDependent() || E->isValueDependent()) {
3397 // Save dependent expressions in the AST to be instantiated.
3398 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3399 AA->setPackExpansion(IsPackExpansion);
3404 // FIXME: Cache the number on the Attr object?
3405 llvm::APSInt Alignment(32);
3407 = VerifyIntegerConstantExpression(E, &Alignment,
3408 diag::err_aligned_attribute_argument_not_int,
3409 /*AllowFold*/ false);
3410 if (ICE.isInvalid())
3413 // C++11 [dcl.align]p2:
3414 // -- if the constant expression evaluates to zero, the alignment
3415 // specifier shall have no effect
3417 // An alignment specification of zero has no effect.
3418 if (!(TmpAttr.isAlignas() && !Alignment) &&
3419 !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
3420 Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
3421 << E->getSourceRange();
3425 if (TmpAttr.isDeclspec()) {
3426 // We've already verified it's a power of 2, now let's make sure it's
3428 if (Alignment.getZExtValue() > 8192) {
3429 Diag(AttrLoc, diag::err_attribute_aligned_greater_than_8192)
3430 << E->getSourceRange();
3435 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3436 ICE.take(), SpellingListIndex);
3437 AA->setPackExpansion(IsPackExpansion);
3441 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3442 unsigned SpellingListIndex, bool IsPackExpansion) {
3443 // FIXME: Cache the number on the Attr object if non-dependent?
3444 // FIXME: Perform checking of type validity
3445 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3447 AA->setPackExpansion(IsPackExpansion);
3451 void Sema::CheckAlignasUnderalignment(Decl *D) {
3452 assert(D->hasAttrs() && "no attributes on decl");
3455 if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3458 Ty = Context.getTagDeclType(cast<TagDecl>(D));
3459 if (Ty->isDependentType() || Ty->isIncompleteType())
3462 // C++11 [dcl.align]p5, C11 6.7.5/4:
3463 // The combined effect of all alignment attributes in a declaration shall
3464 // not specify an alignment that is less strict than the alignment that
3465 // would otherwise be required for the entity being declared.
3466 AlignedAttr *AlignasAttr = 0;
3468 for (specific_attr_iterator<AlignedAttr>
3469 I = D->specific_attr_begin<AlignedAttr>(),
3470 E = D->specific_attr_end<AlignedAttr>(); I != E; ++I) {
3471 if (I->isAlignmentDependent())
3475 Align = std::max(Align, I->getAlignment(Context));
3478 if (AlignasAttr && Align) {
3479 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3480 CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty);
3481 if (NaturalAlign > RequestedAlign)
3482 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3483 << Ty << (unsigned)NaturalAlign.getQuantity();
3487 /// handleModeAttr - This attribute modifies the width of a decl with primitive
3490 /// Despite what would be logical, the mode attribute is a decl attribute, not a
3491 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3492 /// HImode, not an intermediate pointer.
3493 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3494 // This attribute isn't documented, but glibc uses it. It changes
3495 // the width of an int or unsigned int to the specified size.
3496 if (!Attr.isArgIdent(0)) {
3497 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3498 << AANT_ArgumentIdentifier;
3502 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3503 StringRef Str = Name->getName();
3505 // Normalize the attribute name, __foo__ becomes foo.
3506 if (Str.startswith("__") && Str.endswith("__"))
3507 Str = Str.substr(2, Str.size() - 4);
3509 unsigned DestWidth = 0;
3510 bool IntegerMode = true;
3511 bool ComplexMode = false;
3512 switch (Str.size()) {
3515 case 'Q': DestWidth = 8; break;
3516 case 'H': DestWidth = 16; break;
3517 case 'S': DestWidth = 32; break;
3518 case 'D': DestWidth = 64; break;
3519 case 'X': DestWidth = 96; break;
3520 case 'T': DestWidth = 128; break;
3522 if (Str[1] == 'F') {
3523 IntegerMode = false;
3524 } else if (Str[1] == 'C') {
3525 IntegerMode = false;
3527 } else if (Str[1] != 'I') {
3532 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3533 // pointer on PIC16 and other embedded platforms.
3535 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3536 else if (Str == "byte")
3537 DestWidth = S.Context.getTargetInfo().getCharWidth();
3540 if (Str == "pointer")
3541 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3544 if (Str == "unwind_word")
3545 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3550 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3551 OldTy = TD->getUnderlyingType();
3552 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3553 OldTy = VD->getType();
3555 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3556 << "mode" << Attr.getRange();
3560 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
3561 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3562 else if (IntegerMode) {
3563 if (!OldTy->isIntegralOrEnumerationType())
3564 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3565 } else if (ComplexMode) {
3566 if (!OldTy->isComplexType())
3567 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3569 if (!OldTy->isFloatingType())
3570 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3573 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3574 // and friends, at least with glibc.
3575 // FIXME: Make sure floating-point mappings are accurate
3576 // FIXME: Support XF and TF types
3578 S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
3585 NewTy = S.Context.getIntTypeForBitwidth(DestWidth,
3586 OldTy->isSignedIntegerType());
3588 NewTy = S.Context.getRealTypeForBitwidth(DestWidth);
3590 if (NewTy.isNull()) {
3591 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3596 NewTy = S.Context.getComplexType(NewTy);
3599 // Install the new type.
3600 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3601 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3603 cast<ValueDecl>(D)->setType(NewTy);
3605 D->addAttr(::new (S.Context)
3606 ModeAttr(Attr.getRange(), S.Context, Name,
3607 Attr.getAttributeSpellingListIndex()));
3610 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3611 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3612 if (!VD->hasGlobalStorage())
3613 S.Diag(Attr.getLoc(),
3614 diag::warn_attribute_requires_functions_or_static_globals)
3616 } else if (!isFunctionOrMethod(D)) {
3617 S.Diag(Attr.getLoc(),
3618 diag::warn_attribute_requires_functions_or_static_globals)
3623 D->addAttr(::new (S.Context)
3624 NoDebugAttr(Attr.getRange(), S.Context,
3625 Attr.getAttributeSpellingListIndex()));
3628 static void handleNoInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3629 if (!isa<FunctionDecl>(D)) {
3630 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3631 << Attr.getName() << ExpectedFunction;
3635 D->addAttr(::new (S.Context)
3636 NoInlineAttr(Attr.getRange(), S.Context,
3637 Attr.getAttributeSpellingListIndex()));
3640 static void handleNoInstrumentFunctionAttr(Sema &S, Decl *D,
3641 const AttributeList &Attr) {
3642 if (!isa<FunctionDecl>(D)) {
3643 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3644 << Attr.getName() << ExpectedFunction;
3648 D->addAttr(::new (S.Context)
3649 NoInstrumentFunctionAttr(Attr.getRange(), S.Context,
3650 Attr.getAttributeSpellingListIndex()));
3653 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3654 if (S.LangOpts.CUDA) {
3655 if (!isa<VarDecl>(D)) {
3656 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3657 << Attr.getName() << ExpectedVariable;
3661 D->addAttr(::new (S.Context)
3662 CUDAConstantAttr(Attr.getRange(), S.Context,
3663 Attr.getAttributeSpellingListIndex()));
3665 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
3669 static void handleDeviceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3670 if (S.LangOpts.CUDA) {
3671 // check the attribute arguments.
3672 if (Attr.getNumArgs() != 0) {
3673 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3674 << Attr.getName() << 0;
3678 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
3679 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3680 << Attr.getName() << ExpectedVariableOrFunction;
3684 D->addAttr(::new (S.Context)
3685 CUDADeviceAttr(Attr.getRange(), S.Context,
3686 Attr.getAttributeSpellingListIndex()));
3688 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
3692 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3693 if (S.LangOpts.CUDA) {
3694 if (!isa<FunctionDecl>(D)) {
3695 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3696 << Attr.getName() << ExpectedFunction;
3700 FunctionDecl *FD = cast<FunctionDecl>(D);
3701 if (!FD->getResultType()->isVoidType()) {
3702 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3703 if (FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>()) {
3704 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3706 << FixItHint::CreateReplacement(FTL.getResultLoc().getSourceRange(),
3709 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3715 D->addAttr(::new (S.Context)
3716 CUDAGlobalAttr(Attr.getRange(), S.Context,
3717 Attr.getAttributeSpellingListIndex()));
3719 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
3723 static void handleHostAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3724 if (S.LangOpts.CUDA) {
3725 if (!isa<FunctionDecl>(D)) {
3726 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3727 << Attr.getName() << ExpectedFunction;
3731 D->addAttr(::new (S.Context)
3732 CUDAHostAttr(Attr.getRange(), S.Context,
3733 Attr.getAttributeSpellingListIndex()));
3735 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
3739 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3740 if (S.LangOpts.CUDA) {
3741 if (!isa<VarDecl>(D)) {
3742 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3743 << Attr.getName() << ExpectedVariable;
3747 D->addAttr(::new (S.Context)
3748 CUDASharedAttr(Attr.getRange(), S.Context,
3749 Attr.getAttributeSpellingListIndex()));
3751 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
3755 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3756 FunctionDecl *Fn = dyn_cast<FunctionDecl>(D);
3758 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3759 << Attr.getName() << ExpectedFunction;
3763 if (!Fn->isInlineSpecified()) {
3764 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3768 D->addAttr(::new (S.Context)
3769 GNUInlineAttr(Attr.getRange(), S.Context,
3770 Attr.getAttributeSpellingListIndex()));
3773 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3774 if (hasDeclarator(D)) return;
3776 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3777 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3778 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3780 if (S.CheckCallingConvAttr(Attr, CC, FD))
3783 if (!isa<ObjCMethodDecl>(D)) {
3784 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3785 << Attr.getName() << ExpectedFunctionOrMethod;
3789 switch (Attr.getKind()) {
3790 case AttributeList::AT_FastCall:
3791 D->addAttr(::new (S.Context)
3792 FastCallAttr(Attr.getRange(), S.Context,
3793 Attr.getAttributeSpellingListIndex()));
3795 case AttributeList::AT_StdCall:
3796 D->addAttr(::new (S.Context)
3797 StdCallAttr(Attr.getRange(), S.Context,
3798 Attr.getAttributeSpellingListIndex()));
3800 case AttributeList::AT_ThisCall:
3801 D->addAttr(::new (S.Context)
3802 ThisCallAttr(Attr.getRange(), S.Context,
3803 Attr.getAttributeSpellingListIndex()));
3805 case AttributeList::AT_CDecl:
3806 D->addAttr(::new (S.Context)
3807 CDeclAttr(Attr.getRange(), S.Context,
3808 Attr.getAttributeSpellingListIndex()));
3810 case AttributeList::AT_Pascal:
3811 D->addAttr(::new (S.Context)
3812 PascalAttr(Attr.getRange(), S.Context,
3813 Attr.getAttributeSpellingListIndex()));
3815 case AttributeList::AT_MSABI:
3816 D->addAttr(::new (S.Context)
3817 MSABIAttr(Attr.getRange(), S.Context,
3818 Attr.getAttributeSpellingListIndex()));
3820 case AttributeList::AT_SysVABI:
3821 D->addAttr(::new (S.Context)
3822 SysVABIAttr(Attr.getRange(), S.Context,
3823 Attr.getAttributeSpellingListIndex()));
3825 case AttributeList::AT_Pcs: {
3826 PcsAttr::PCSType PCS;
3829 PCS = PcsAttr::AAPCS;
3832 PCS = PcsAttr::AAPCS_VFP;
3835 llvm_unreachable("unexpected calling convention in pcs attribute");
3838 D->addAttr(::new (S.Context)
3839 PcsAttr(Attr.getRange(), S.Context, PCS,
3840 Attr.getAttributeSpellingListIndex()));
3843 case AttributeList::AT_PnaclCall:
3844 D->addAttr(::new (S.Context)
3845 PnaclCallAttr(Attr.getRange(), S.Context,
3846 Attr.getAttributeSpellingListIndex()));
3848 case AttributeList::AT_IntelOclBicc:
3849 D->addAttr(::new (S.Context)
3850 IntelOclBiccAttr(Attr.getRange(), S.Context,
3851 Attr.getAttributeSpellingListIndex()));
3855 llvm_unreachable("unexpected attribute kind");
3859 static void handleOpenCLKernelAttr(Sema &S, Decl *D, const AttributeList &Attr){
3860 D->addAttr(::new (S.Context) OpenCLKernelAttr(Attr.getRange(), S.Context));
3863 static void handleOpenCLImageAccessAttr(Sema &S, Decl *D, const AttributeList &Attr){
3864 Expr *E = Attr.getArgAsExpr(0);
3865 llvm::APSInt ArgNum(32);
3866 if (E->isTypeDependent() || E->isValueDependent() ||
3867 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
3868 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3869 << Attr.getName() << AANT_ArgumentIntegerConstant
3870 << E->getSourceRange();
3874 D->addAttr(::new (S.Context) OpenCLImageAccessAttr(
3875 Attr.getRange(), S.Context, ArgNum.getZExtValue()));
3878 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3879 const FunctionDecl *FD) {
3880 if (attr.isInvalid())
3883 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3884 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3889 // TODO: diagnose uses of these conventions on the wrong target. Or, better
3890 // move to TargetAttributesSema one day.
3891 switch (attr.getKind()) {
3892 case AttributeList::AT_CDecl: CC = CC_C; break;
3893 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3894 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3895 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3896 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3897 case AttributeList::AT_MSABI:
3898 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3901 case AttributeList::AT_SysVABI:
3902 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3905 case AttributeList::AT_Pcs: {
3907 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3911 if (StrRef == "aapcs") {
3914 } else if (StrRef == "aapcs-vfp") {
3920 Diag(attr.getLoc(), diag::err_invalid_pcs);
3923 case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
3924 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3925 default: llvm_unreachable("unexpected attribute kind");
3928 const TargetInfo &TI = Context.getTargetInfo();
3929 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3930 if (A == TargetInfo::CCCR_Warning) {
3931 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3933 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3935 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3936 TargetInfo::CCMT_NonMember;
3937 CC = TI.getDefaultCallingConv(MT);
3943 static void handleRegparmAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3944 if (hasDeclarator(D)) return;
3947 if (S.CheckRegparmAttr(Attr, numParams))
3950 if (!isa<ObjCMethodDecl>(D)) {
3951 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3952 << Attr.getName() << ExpectedFunctionOrMethod;
3956 D->addAttr(::new (S.Context)
3957 RegparmAttr(Attr.getRange(), S.Context, numParams,
3958 Attr.getAttributeSpellingListIndex()));
3961 /// Checks a regparm attribute, returning true if it is ill-formed and
3962 /// otherwise setting numParams to the appropriate value.
3963 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3964 if (Attr.isInvalid())
3967 if (!checkAttributeNumArgs(*this, Attr, 1)) {
3972 Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3973 llvm::APSInt NumParams(32);
3974 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
3975 !NumParamsExpr->isIntegerConstantExpr(NumParams, Context)) {
3976 Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3977 << Attr.getName() << AANT_ArgumentIntegerConstant
3978 << NumParamsExpr->getSourceRange();
3983 if (Context.getTargetInfo().getRegParmMax() == 0) {
3984 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3985 << NumParamsExpr->getSourceRange();
3990 numParams = NumParams.getZExtValue();
3991 if (numParams > Context.getTargetInfo().getRegParmMax()) {
3992 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3993 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4001 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const AttributeList &Attr){
4002 if (S.LangOpts.CUDA) {
4003 // check the attribute arguments.
4004 if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
4005 // FIXME: 0 is not okay.
4006 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
4010 if (!isFunctionOrMethod(D)) {
4011 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
4012 << Attr.getName() << ExpectedFunctionOrMethod;
4016 Expr *MaxThreadsExpr = Attr.getArgAsExpr(0);
4017 llvm::APSInt MaxThreads(32);
4018 if (MaxThreadsExpr->isTypeDependent() ||
4019 MaxThreadsExpr->isValueDependent() ||
4020 !MaxThreadsExpr->isIntegerConstantExpr(MaxThreads, S.Context)) {
4021 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4022 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
4023 << MaxThreadsExpr->getSourceRange();
4027 llvm::APSInt MinBlocks(32);
4028 if (Attr.getNumArgs() > 1) {
4029 Expr *MinBlocksExpr = Attr.getArgAsExpr(1);
4030 if (MinBlocksExpr->isTypeDependent() ||
4031 MinBlocksExpr->isValueDependent() ||
4032 !MinBlocksExpr->isIntegerConstantExpr(MinBlocks, S.Context)) {
4033 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4034 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
4035 << MinBlocksExpr->getSourceRange();
4040 D->addAttr(::new (S.Context)
4041 CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
4042 MaxThreads.getZExtValue(),
4043 MinBlocks.getZExtValue(),
4044 Attr.getAttributeSpellingListIndex()));
4046 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "launch_bounds";
4050 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4051 const AttributeList &Attr) {
4052 if (!Attr.isArgIdent(0)) {
4053 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4054 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4058 if (!checkAttributeNumArgs(S, Attr, 3))
4061 StringRef AttrName = Attr.getName()->getName();
4062 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
4064 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
4065 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4066 << Attr.getName() << ExpectedFunctionOrMethod;
4070 uint64_t ArgumentIdx;
4071 if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
4073 Attr.getArgAsExpr(1), ArgumentIdx))
4076 uint64_t TypeTagIdx;
4077 if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
4079 Attr.getArgAsExpr(2), TypeTagIdx))
4082 bool IsPointer = (AttrName == "pointer_with_type_tag");
4084 // Ensure that buffer has a pointer type.
4085 QualType BufferTy = getFunctionOrMethodArgType(D, ArgumentIdx);
4086 if (!BufferTy->isPointerType()) {
4087 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4092 D->addAttr(::new (S.Context)
4093 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4094 ArgumentIdx, TypeTagIdx, IsPointer,
4095 Attr.getAttributeSpellingListIndex()));
4098 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4099 const AttributeList &Attr) {
4100 if (!Attr.isArgIdent(0)) {
4101 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4102 << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4106 if (!checkAttributeNumArgs(S, Attr, 1))
4109 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4110 TypeSourceInfo *MatchingCTypeLoc = 0;
4111 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
4112 assert(MatchingCTypeLoc && "no type source info for attribute argument");
4114 D->addAttr(::new (S.Context)
4115 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4117 Attr.getLayoutCompatible(),
4118 Attr.getMustBeNull(),
4119 Attr.getAttributeSpellingListIndex()));
4122 //===----------------------------------------------------------------------===//
4123 // Checker-specific attribute handlers.
4124 //===----------------------------------------------------------------------===//
4126 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4127 return type->isDependentType() ||
4128 type->isObjCObjectPointerType() ||
4129 S.Context.isObjCNSObjectType(type);
4131 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4132 return type->isDependentType() ||
4133 type->isPointerType() ||
4134 isValidSubjectOfNSAttribute(S, type);
4137 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4138 ParmVarDecl *param = dyn_cast<ParmVarDecl>(D);
4140 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4141 << Attr.getRange() << Attr.getName() << ExpectedParameter;
4146 if (Attr.getKind() == AttributeList::AT_NSConsumed) {
4147 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
4150 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
4155 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4156 << Attr.getRange() << Attr.getName() << cf;
4161 param->addAttr(::new (S.Context)
4162 CFConsumedAttr(Attr.getRange(), S.Context,
4163 Attr.getAttributeSpellingListIndex()));
4165 param->addAttr(::new (S.Context)
4166 NSConsumedAttr(Attr.getRange(), S.Context,
4167 Attr.getAttributeSpellingListIndex()));
4170 static void handleNSConsumesSelfAttr(Sema &S, Decl *D,
4171 const AttributeList &Attr) {
4172 if (!isa<ObjCMethodDecl>(D)) {
4173 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4174 << Attr.getRange() << Attr.getName() << ExpectedMethod;
4178 D->addAttr(::new (S.Context)
4179 NSConsumesSelfAttr(Attr.getRange(), S.Context,
4180 Attr.getAttributeSpellingListIndex()));
4183 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4184 const AttributeList &Attr) {
4186 QualType returnType;
4188 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4189 returnType = MD->getResultType();
4190 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4191 (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4192 return; // ignore: was handled as a type attribute
4193 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4194 returnType = PD->getType();
4195 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4196 returnType = FD->getResultType();
4198 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4199 << Attr.getRange() << Attr.getName()
4200 << ExpectedFunctionOrMethod;
4206 switch (Attr.getKind()) {
4207 default: llvm_unreachable("invalid ownership attribute");
4208 case AttributeList::AT_NSReturnsAutoreleased:
4209 case AttributeList::AT_NSReturnsRetained:
4210 case AttributeList::AT_NSReturnsNotRetained:
4211 typeOK = isValidSubjectOfNSAttribute(S, returnType);
4215 case AttributeList::AT_CFReturnsRetained:
4216 case AttributeList::AT_CFReturnsNotRetained:
4217 typeOK = isValidSubjectOfCFAttribute(S, returnType);
4223 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4224 << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
4228 switch (Attr.getKind()) {
4230 llvm_unreachable("invalid ownership attribute");
4231 case AttributeList::AT_NSReturnsAutoreleased:
4232 D->addAttr(::new (S.Context)
4233 NSReturnsAutoreleasedAttr(Attr.getRange(), S.Context,
4234 Attr.getAttributeSpellingListIndex()));
4236 case AttributeList::AT_CFReturnsNotRetained:
4237 D->addAttr(::new (S.Context)
4238 CFReturnsNotRetainedAttr(Attr.getRange(), S.Context,
4239 Attr.getAttributeSpellingListIndex()));
4241 case AttributeList::AT_NSReturnsNotRetained:
4242 D->addAttr(::new (S.Context)
4243 NSReturnsNotRetainedAttr(Attr.getRange(), S.Context,
4244 Attr.getAttributeSpellingListIndex()));
4246 case AttributeList::AT_CFReturnsRetained:
4247 D->addAttr(::new (S.Context)
4248 CFReturnsRetainedAttr(Attr.getRange(), S.Context,
4249 Attr.getAttributeSpellingListIndex()));
4251 case AttributeList::AT_NSReturnsRetained:
4252 D->addAttr(::new (S.Context)
4253 NSReturnsRetainedAttr(Attr.getRange(), S.Context,
4254 Attr.getAttributeSpellingListIndex()));
4259 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4260 const AttributeList &attr) {
4261 const int EP_ObjCMethod = 1;
4262 const int EP_ObjCProperty = 2;
4264 SourceLocation loc = attr.getLoc();
4265 QualType resultType;
4267 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
4270 ObjCPropertyDecl *property = dyn_cast<ObjCPropertyDecl>(D);
4272 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4273 << SourceRange(loc, loc) << attr.getName() << ExpectedMethodOrProperty;
4276 resultType = property->getType();
4279 // Check that the method returns a normal pointer.
4280 resultType = method->getResultType();
4282 if (!resultType->isReferenceType() &&
4283 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4284 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4286 << attr.getName() << (method ? EP_ObjCMethod : EP_ObjCProperty)
4287 << /*non-retainable pointer*/ 2;
4289 // Drop the attribute.
4293 D->addAttr(::new (S.Context)
4294 ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context,
4295 attr.getAttributeSpellingListIndex()));
4298 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4299 const AttributeList &attr) {
4300 SourceLocation loc = attr.getLoc();
4301 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
4304 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4305 << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
4308 DeclContext *DC = method->getDeclContext();
4309 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4310 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4311 << attr.getName() << 0;
4312 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4315 if (method->getMethodFamily() == OMF_dealloc) {
4316 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4317 << attr.getName() << 1;
4321 method->addAttr(::new (S.Context)
4322 ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4323 attr.getAttributeSpellingListIndex()));
4326 /// Handle cf_audited_transfer and cf_unknown_transfer.
4327 static void handleCFTransferAttr(Sema &S, Decl *D, const AttributeList &A) {
4328 if (!isa<FunctionDecl>(D)) {
4329 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4330 << A.getRange() << A.getName() << ExpectedFunction;
4334 bool IsAudited = (A.getKind() == AttributeList::AT_CFAuditedTransfer);
4336 // Check whether there's a conflicting attribute already present.
4339 Existing = D->getAttr<CFUnknownTransferAttr>();
4341 Existing = D->getAttr<CFAuditedTransferAttr>();
4344 S.Diag(D->getLocStart(), diag::err_attributes_are_not_compatible)
4346 << (IsAudited ? "cf_unknown_transfer" : "cf_audited_transfer")
4347 << A.getRange() << Existing->getRange();
4351 // All clear; add the attribute.
4353 D->addAttr(::new (S.Context)
4354 CFAuditedTransferAttr(A.getRange(), S.Context,
4355 A.getAttributeSpellingListIndex()));
4357 D->addAttr(::new (S.Context)
4358 CFUnknownTransferAttr(A.getRange(), S.Context,
4359 A.getAttributeSpellingListIndex()));
4363 static void handleNSBridgedAttr(Sema &S, Scope *Sc, Decl *D,
4364 const AttributeList &Attr) {
4365 RecordDecl *RD = dyn_cast<RecordDecl>(D);
4366 if (!RD || RD->isUnion()) {
4367 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4368 << Attr.getRange() << Attr.getName() << ExpectedStruct;
4371 IdentifierLoc *Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : 0;
4373 // In Objective-C, verify that the type names an Objective-C type.
4374 // We don't want to check this outside of ObjC because people sometimes
4375 // do crazy C declarations of Objective-C types.
4376 if (Parm && S.getLangOpts().ObjC1) {
4377 // Check for an existing type with this name.
4378 LookupResult R(S, DeclarationName(Parm->Ident), Parm->Loc,
4379 Sema::LookupOrdinaryName);
4380 if (S.LookupName(R, Sc)) {
4381 NamedDecl *Target = R.getFoundDecl();
4382 if (Target && !isa<ObjCInterfaceDecl>(Target)) {
4383 S.Diag(D->getLocStart(), diag::err_ns_bridged_not_interface);
4384 S.Diag(Target->getLocStart(), diag::note_declared_at);
4389 D->addAttr(::new (S.Context)
4390 NSBridgedAttr(Attr.getRange(), S.Context, Parm ? Parm->Ident : 0,
4391 Attr.getAttributeSpellingListIndex()));
4394 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
4395 const AttributeList &Attr) {
4396 if (!isa<RecordDecl>(D)) {
4397 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
4399 << (S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass
4400 : ExpectedStructOrUnion);
4404 if (Attr.getNumArgs() != 1) {
4405 S.Diag(D->getLocStart(), diag::err_objc_bridge_not_id);
4408 IdentifierLoc *Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : 0;
4410 S.Diag(D->getLocStart(), diag::err_objc_bridge_not_id);
4414 D->addAttr(::new (S.Context)
4415 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm ? Parm->Ident : 0,
4416 Attr.getAttributeSpellingListIndex()));
4419 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4420 const AttributeList &Attr) {
4421 if (hasDeclarator(D)) return;
4423 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4424 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4427 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4428 const AttributeList &Attr) {
4429 if (!isa<VarDecl>(D) && !isa<FieldDecl>(D)) {
4430 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4431 << Attr.getRange() << Attr.getName() << ExpectedVariable;
4435 ValueDecl *vd = cast<ValueDecl>(D);
4436 QualType type = vd->getType();
4438 if (!type->isDependentType() &&
4439 !type->isObjCLifetimeType()) {
4440 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4445 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4447 // If we have no lifetime yet, check the lifetime we're presumably
4449 if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4450 lifetime = type->getObjCARCImplicitLifetime();
4453 case Qualifiers::OCL_None:
4454 assert(type->isDependentType() &&
4455 "didn't infer lifetime for non-dependent type?");
4458 case Qualifiers::OCL_Weak: // meaningful
4459 case Qualifiers::OCL_Strong: // meaningful
4462 case Qualifiers::OCL_ExplicitNone:
4463 case Qualifiers::OCL_Autoreleasing:
4464 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4465 << (lifetime == Qualifiers::OCL_Autoreleasing);
4469 D->addAttr(::new (S.Context)
4470 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4471 Attr.getAttributeSpellingListIndex()));
4474 //===----------------------------------------------------------------------===//
4475 // Microsoft specific attribute handlers.
4476 //===----------------------------------------------------------------------===//
4478 // Check if MS extensions or some other language extensions are enabled. If
4479 // not, issue a diagnostic that the given attribute is unused.
4480 static bool checkMicrosoftExt(Sema &S, const AttributeList &Attr,
4481 bool OtherExtension = false) {
4482 if (S.LangOpts.MicrosoftExt || OtherExtension)
4484 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4488 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4489 if (!checkMicrosoftExt(S, Attr, S.LangOpts.Borland))
4493 SourceLocation LiteralLoc;
4494 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4497 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4498 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4499 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4500 StrRef = StrRef.drop_front().drop_back();
4502 // Validate GUID length.
4503 if (StrRef.size() != 36) {
4504 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4508 for (unsigned i = 0; i < 36; ++i) {
4509 if (i == 8 || i == 13 || i == 18 || i == 23) {
4510 if (StrRef[i] != '-') {
4511 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4514 } else if (!isHexDigit(StrRef[i])) {
4515 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4520 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4521 Attr.getAttributeSpellingListIndex()));
4524 static void handleInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4525 if (!checkMicrosoftExt(S, Attr))
4528 AttributeList::Kind Kind = Attr.getKind();
4529 if (Kind == AttributeList::AT_SingleInheritance)
4532 SingleInheritanceAttr(Attr.getRange(), S.Context,
4533 Attr.getAttributeSpellingListIndex()));
4534 else if (Kind == AttributeList::AT_MultipleInheritance)
4537 MultipleInheritanceAttr(Attr.getRange(), S.Context,
4538 Attr.getAttributeSpellingListIndex()));
4539 else if (Kind == AttributeList::AT_VirtualInheritance)
4542 VirtualInheritanceAttr(Attr.getRange(), S.Context,
4543 Attr.getAttributeSpellingListIndex()));
4546 static void handlePortabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4547 if (!checkMicrosoftExt(S, Attr))
4550 AttributeList::Kind Kind = Attr.getKind();
4551 if (Kind == AttributeList::AT_Win64)
4553 ::new (S.Context) Win64Attr(Attr.getRange(), S.Context,
4554 Attr.getAttributeSpellingListIndex()));
4557 static void handleForceInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4558 if (!checkMicrosoftExt(S, Attr))
4560 D->addAttr(::new (S.Context)
4561 ForceInlineAttr(Attr.getRange(), S.Context,
4562 Attr.getAttributeSpellingListIndex()));
4565 static void handleSelectAnyAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4566 if (!checkMicrosoftExt(S, Attr))
4568 // Check linkage after possibly merging declaratinos. See
4569 // checkAttributesAfterMerging().
4570 D->addAttr(::new (S.Context)
4571 SelectAnyAttr(Attr.getRange(), S.Context,
4572 Attr.getAttributeSpellingListIndex()));
4575 /// Handles semantic checking for features that are common to all attributes,
4576 /// such as checking whether a parameter was properly specified, or the correct
4577 /// number of arguments were passed, etc.
4578 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4579 const AttributeList &Attr) {
4580 // Several attributes carry different semantics than the parsing requires, so
4581 // those are opted out of the common handling.
4583 // We also bail on unknown and ignored attributes because those are handled
4584 // as part of the target-specific handling logic.
4585 if (Attr.hasCustomParsing() ||
4586 Attr.getKind() == AttributeList::UnknownAttribute ||
4587 Attr.getKind() == AttributeList::IgnoredAttribute)
4590 // If there are no optional arguments, then checking for the argument count
4592 if (Attr.getMinArgs() == Attr.getMaxArgs() &&
4593 !checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4598 //===----------------------------------------------------------------------===//
4599 // Top Level Sema Entry Points
4600 //===----------------------------------------------------------------------===//
4602 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4603 /// the attribute applies to decls. If the attribute is a type attribute, just
4604 /// silently ignore it if a GNU attribute.
4605 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4606 const AttributeList &Attr,
4607 bool IncludeCXX11Attributes) {
4608 if (Attr.isInvalid())
4611 // Ignore C++11 attributes on declarator chunks: they appertain to the type
4613 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4616 if (handleCommonAttributeFeatures(S, scope, D, Attr))
4619 switch (Attr.getKind()) {
4620 case AttributeList::AT_IBAction: handleIBAction(S, D, Attr); break;
4621 case AttributeList::AT_IBOutlet: handleIBOutlet(S, D, Attr); break;
4622 case AttributeList::AT_IBOutletCollection:
4623 handleIBOutletCollection(S, D, Attr); break;
4624 case AttributeList::AT_AddressSpace:
4625 case AttributeList::AT_ObjCGC:
4626 case AttributeList::AT_VectorSize:
4627 case AttributeList::AT_NeonVectorType:
4628 case AttributeList::AT_NeonPolyVectorType:
4629 case AttributeList::AT_Ptr32:
4630 case AttributeList::AT_Ptr64:
4631 case AttributeList::AT_SPtr:
4632 case AttributeList::AT_UPtr:
4633 // Ignore these, these are type attributes, handled by
4634 // ProcessTypeAttributes.
4636 case AttributeList::AT_Alias: handleAliasAttr (S, D, Attr); break;
4637 case AttributeList::AT_Aligned: handleAlignedAttr (S, D, Attr); break;
4638 case AttributeList::AT_AllocSize: handleAllocSizeAttr (S, D, Attr); break;
4639 case AttributeList::AT_AlwaysInline:
4640 handleAlwaysInlineAttr (S, D, Attr); break;
4641 case AttributeList::AT_AnalyzerNoReturn:
4642 handleAnalyzerNoReturnAttr (S, D, Attr); break;
4643 case AttributeList::AT_TLSModel: handleTLSModelAttr (S, D, Attr); break;
4644 case AttributeList::AT_Annotate: handleAnnotateAttr (S, D, Attr); break;
4645 case AttributeList::AT_Availability:handleAvailabilityAttr(S, D, Attr); break;
4646 case AttributeList::AT_CarriesDependency:
4647 handleDependencyAttr(S, scope, D, Attr);
4649 case AttributeList::AT_Common: handleCommonAttr (S, D, Attr); break;
4650 case AttributeList::AT_CUDAConstant:handleConstantAttr (S, D, Attr); break;
4651 case AttributeList::AT_Constructor: handleConstructorAttr (S, D, Attr); break;
4652 case AttributeList::AT_CXX11NoReturn:
4653 handleCXX11NoReturnAttr(S, D, Attr);
4655 case AttributeList::AT_Deprecated:
4656 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4658 case AttributeList::AT_Destructor: handleDestructorAttr (S, D, Attr); break;
4659 case AttributeList::AT_ExtVectorType:
4660 handleExtVectorTypeAttr(S, scope, D, Attr);
4662 case AttributeList::AT_MinSize:
4663 handleMinSizeAttr(S, D, Attr);
4665 case AttributeList::AT_Format: handleFormatAttr (S, D, Attr); break;
4666 case AttributeList::AT_FormatArg: handleFormatArgAttr (S, D, Attr); break;
4667 case AttributeList::AT_CUDAGlobal: handleGlobalAttr (S, D, Attr); break;
4668 case AttributeList::AT_CUDADevice: handleDeviceAttr (S, D, Attr); break;
4669 case AttributeList::AT_CUDAHost: handleHostAttr (S, D, Attr); break;
4670 case AttributeList::AT_GNUInline: handleGNUInlineAttr (S, D, Attr); break;
4671 case AttributeList::AT_CUDALaunchBounds:
4672 handleLaunchBoundsAttr(S, D, Attr);
4674 case AttributeList::AT_Malloc: handleMallocAttr (S, D, Attr); break;
4675 case AttributeList::AT_MayAlias: handleMayAliasAttr (S, D, Attr); break;
4676 case AttributeList::AT_Mode: handleModeAttr (S, D, Attr); break;
4677 case AttributeList::AT_NoCommon: handleNoCommonAttr (S, D, Attr); break;
4678 case AttributeList::AT_NonNull: handleNonNullAttr (S, D, Attr); break;
4679 case AttributeList::AT_Overloadable:handleOverloadableAttr(S, D, Attr); break;
4680 case AttributeList::AT_ownership_returns:
4681 case AttributeList::AT_ownership_takes:
4682 case AttributeList::AT_ownership_holds:
4683 handleOwnershipAttr (S, D, Attr); break;
4684 case AttributeList::AT_Cold: handleColdAttr (S, D, Attr); break;
4685 case AttributeList::AT_Hot: handleHotAttr (S, D, Attr); break;
4686 case AttributeList::AT_Naked: handleNakedAttr (S, D, Attr); break;
4687 case AttributeList::AT_NoReturn: handleNoReturnAttr (S, D, Attr); break;
4688 case AttributeList::AT_NoThrow: handleNothrowAttr (S, D, Attr); break;
4689 case AttributeList::AT_CUDAShared: handleSharedAttr (S, D, Attr); break;
4690 case AttributeList::AT_VecReturn: handleVecReturnAttr (S, D, Attr); break;
4692 case AttributeList::AT_ObjCOwnership:
4693 handleObjCOwnershipAttr(S, D, Attr); break;
4694 case AttributeList::AT_ObjCPreciseLifetime:
4695 handleObjCPreciseLifetimeAttr(S, D, Attr); break;
4697 case AttributeList::AT_ObjCReturnsInnerPointer:
4698 handleObjCReturnsInnerPointerAttr(S, D, Attr); break;
4700 case AttributeList::AT_ObjCRequiresSuper:
4701 handleObjCRequiresSuperAttr(S, D, Attr); break;
4703 case AttributeList::AT_NSBridged:
4704 handleNSBridgedAttr(S, scope, D, Attr); break;
4706 case AttributeList::AT_ObjCBridge:
4707 handleObjCBridgeAttr(S, scope, D, Attr); break;
4709 case AttributeList::AT_CFAuditedTransfer:
4710 case AttributeList::AT_CFUnknownTransfer:
4711 handleCFTransferAttr(S, D, Attr); break;
4713 // Checker-specific.
4714 case AttributeList::AT_CFConsumed:
4715 case AttributeList::AT_NSConsumed: handleNSConsumedAttr (S, D, Attr); break;
4716 case AttributeList::AT_NSConsumesSelf:
4717 handleNSConsumesSelfAttr(S, D, Attr); break;
4719 case AttributeList::AT_NSReturnsAutoreleased:
4720 case AttributeList::AT_NSReturnsNotRetained:
4721 case AttributeList::AT_CFReturnsNotRetained:
4722 case AttributeList::AT_NSReturnsRetained:
4723 case AttributeList::AT_CFReturnsRetained:
4724 handleNSReturnsRetainedAttr(S, D, Attr); break;
4726 case AttributeList::AT_WorkGroupSizeHint:
4727 case AttributeList::AT_ReqdWorkGroupSize:
4728 handleWorkGroupSize(S, D, Attr); break;
4730 case AttributeList::AT_VecTypeHint:
4731 handleVecTypeHint(S, D, Attr); break;
4733 case AttributeList::AT_InitPriority:
4734 handleInitPriorityAttr(S, D, Attr); break;
4736 case AttributeList::AT_Packed: handlePackedAttr (S, D, Attr); break;
4737 case AttributeList::AT_Section: handleSectionAttr (S, D, Attr); break;
4738 case AttributeList::AT_Unavailable:
4739 handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4741 case AttributeList::AT_ArcWeakrefUnavailable:
4742 handleArcWeakrefUnavailableAttr (S, D, Attr);
4744 case AttributeList::AT_ObjCRootClass:
4745 handleObjCRootClassAttr(S, D, Attr);
4747 case AttributeList::AT_ObjCRequiresPropertyDefs:
4748 handleObjCRequiresPropertyDefsAttr (S, D, Attr);
4750 case AttributeList::AT_Unused: handleUnusedAttr (S, D, Attr); break;
4751 case AttributeList::AT_ReturnsTwice:
4752 handleReturnsTwiceAttr(S, D, Attr);
4754 case AttributeList::AT_Used: handleUsedAttr (S, D, Attr); break;
4755 case AttributeList::AT_Visibility:
4756 handleVisibilityAttr(S, D, Attr, false);
4758 case AttributeList::AT_TypeVisibility:
4759 handleVisibilityAttr(S, D, Attr, true);
4761 case AttributeList::AT_WarnUnused:
4762 handleWarnUnusedAttr(S, D, Attr);
4764 case AttributeList::AT_WarnUnusedResult: handleWarnUnusedResult(S, D, Attr);
4766 case AttributeList::AT_Weak: handleWeakAttr (S, D, Attr); break;
4767 case AttributeList::AT_WeakRef: handleWeakRefAttr (S, D, Attr); break;
4768 case AttributeList::AT_WeakImport: handleWeakImportAttr (S, D, Attr); break;
4769 case AttributeList::AT_TransparentUnion:
4770 handleTransparentUnionAttr(S, D, Attr);
4772 case AttributeList::AT_ObjCException:
4773 handleObjCExceptionAttr(S, D, Attr);
4775 case AttributeList::AT_ObjCMethodFamily:
4776 handleObjCMethodFamilyAttr(S, D, Attr);
4778 case AttributeList::AT_ObjCNSObject:handleObjCNSObject (S, D, Attr); break;
4779 case AttributeList::AT_Blocks: handleBlocksAttr (S, D, Attr); break;
4780 case AttributeList::AT_Sentinel: handleSentinelAttr (S, D, Attr); break;
4781 case AttributeList::AT_Const: handleConstAttr (S, D, Attr); break;
4782 case AttributeList::AT_Pure: handlePureAttr (S, D, Attr); break;
4783 case AttributeList::AT_Cleanup: handleCleanupAttr (S, D, Attr); break;
4784 case AttributeList::AT_NoDebug: handleNoDebugAttr (S, D, Attr); break;
4785 case AttributeList::AT_NoInline: handleNoInlineAttr (S, D, Attr); break;
4786 case AttributeList::AT_Regparm: handleRegparmAttr (S, D, Attr); break;
4787 case AttributeList::IgnoredAttribute:
4790 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg.
4791 handleNoInstrumentFunctionAttr(S, D, Attr);
4793 case AttributeList::AT_StdCall:
4794 case AttributeList::AT_CDecl:
4795 case AttributeList::AT_FastCall:
4796 case AttributeList::AT_ThisCall:
4797 case AttributeList::AT_Pascal:
4798 case AttributeList::AT_MSABI:
4799 case AttributeList::AT_SysVABI:
4800 case AttributeList::AT_Pcs:
4801 case AttributeList::AT_PnaclCall:
4802 case AttributeList::AT_IntelOclBicc:
4803 handleCallConvAttr(S, D, Attr);
4805 case AttributeList::AT_OpenCLKernel:
4806 handleOpenCLKernelAttr(S, D, Attr);
4808 case AttributeList::AT_OpenCLImageAccess:
4809 handleOpenCLImageAccessAttr(S, D, Attr);
4812 // Microsoft attributes:
4813 case AttributeList::AT_MsStruct:
4814 handleMsStructAttr(S, D, Attr);
4816 case AttributeList::AT_Uuid:
4817 handleUuidAttr(S, D, Attr);
4819 case AttributeList::AT_SingleInheritance:
4820 case AttributeList::AT_MultipleInheritance:
4821 case AttributeList::AT_VirtualInheritance:
4822 handleInheritanceAttr(S, D, Attr);
4824 case AttributeList::AT_Win64:
4825 handlePortabilityAttr(S, D, Attr);
4827 case AttributeList::AT_ForceInline:
4828 handleForceInlineAttr(S, D, Attr);
4830 case AttributeList::AT_SelectAny:
4831 handleSelectAnyAttr(S, D, Attr);
4834 // Thread safety attributes:
4835 case AttributeList::AT_AssertExclusiveLock:
4836 handleAssertExclusiveLockAttr(S, D, Attr);
4838 case AttributeList::AT_AssertSharedLock:
4839 handleAssertSharedLockAttr(S, D, Attr);
4841 case AttributeList::AT_GuardedVar:
4842 handleGuardedVarAttr(S, D, Attr);
4844 case AttributeList::AT_PtGuardedVar:
4845 handlePtGuardedVarAttr(S, D, Attr);
4847 case AttributeList::AT_ScopedLockable:
4848 handleScopedLockableAttr(S, D, Attr);
4850 case AttributeList::AT_NoSanitizeAddress:
4851 handleNoSanitizeAddressAttr(S, D, Attr);
4853 case AttributeList::AT_NoThreadSafetyAnalysis:
4854 handleNoThreadSafetyAnalysis(S, D, Attr);
4856 case AttributeList::AT_NoSanitizeThread:
4857 handleNoSanitizeThread(S, D, Attr);
4859 case AttributeList::AT_NoSanitizeMemory:
4860 handleNoSanitizeMemory(S, D, Attr);
4862 case AttributeList::AT_Lockable:
4863 handleLockableAttr(S, D, Attr);
4865 case AttributeList::AT_GuardedBy:
4866 handleGuardedByAttr(S, D, Attr);
4868 case AttributeList::AT_PtGuardedBy:
4869 handlePtGuardedByAttr(S, D, Attr);
4871 case AttributeList::AT_ExclusiveLockFunction:
4872 handleExclusiveLockFunctionAttr(S, D, Attr);
4874 case AttributeList::AT_ExclusiveLocksRequired:
4875 handleExclusiveLocksRequiredAttr(S, D, Attr);
4877 case AttributeList::AT_ExclusiveTrylockFunction:
4878 handleExclusiveTrylockFunctionAttr(S, D, Attr);
4880 case AttributeList::AT_LockReturned:
4881 handleLockReturnedAttr(S, D, Attr);
4883 case AttributeList::AT_LocksExcluded:
4884 handleLocksExcludedAttr(S, D, Attr);
4886 case AttributeList::AT_SharedLockFunction:
4887 handleSharedLockFunctionAttr(S, D, Attr);
4889 case AttributeList::AT_SharedLocksRequired:
4890 handleSharedLocksRequiredAttr(S, D, Attr);
4892 case AttributeList::AT_SharedTrylockFunction:
4893 handleSharedTrylockFunctionAttr(S, D, Attr);
4895 case AttributeList::AT_UnlockFunction:
4896 handleUnlockFunAttr(S, D, Attr);
4898 case AttributeList::AT_AcquiredBefore:
4899 handleAcquiredBeforeAttr(S, D, Attr);
4901 case AttributeList::AT_AcquiredAfter:
4902 handleAcquiredAfterAttr(S, D, Attr);
4905 // Consumed analysis attributes.
4906 case AttributeList::AT_Consumable:
4907 handleConsumableAttr(S, D, Attr);
4909 case AttributeList::AT_CallableWhen:
4910 handleCallableWhenAttr(S, D, Attr);
4912 case AttributeList::AT_ParamTypestate:
4913 handleParamTypestateAttr(S, D, Attr);
4915 case AttributeList::AT_ReturnTypestate:
4916 handleReturnTypestateAttr(S, D, Attr);
4918 case AttributeList::AT_SetTypestate:
4919 handleSetTypestateAttr(S, D, Attr);
4921 case AttributeList::AT_TestTypestate:
4922 handleTestTypestateAttr(S, D, Attr);
4925 // Type safety attributes.
4926 case AttributeList::AT_ArgumentWithTypeTag:
4927 handleArgumentWithTypeTagAttr(S, D, Attr);
4929 case AttributeList::AT_TypeTagForDatatype:
4930 handleTypeTagForDatatypeAttr(S, D, Attr);
4934 // Ask target about the attribute.
4935 const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
4936 if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
4937 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() ?
4938 diag::warn_unhandled_ms_attribute_ignored :
4939 diag::warn_unknown_attribute_ignored) << Attr.getName();
4944 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4945 /// attribute list to the specified decl, ignoring any type attributes.
4946 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4947 const AttributeList *AttrList,
4948 bool IncludeCXX11Attributes) {
4949 for (const AttributeList* l = AttrList; l; l = l->getNext())
4950 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
4953 // static int a9 __attribute__((weakref));
4954 // but that looks really pointless. We reject it.
4955 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4956 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
4957 cast<NamedDecl>(D)->getNameAsString();
4958 D->dropAttr<WeakRefAttr>();
4963 // Annotation attributes are the only attributes allowed after an access
4965 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4966 const AttributeList *AttrList) {
4967 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4968 if (l->getKind() == AttributeList::AT_Annotate) {
4969 handleAnnotateAttr(*this, ASDecl, *l);
4971 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4979 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
4980 /// contains any decl attributes that we should warn about.
4981 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4982 for ( ; A; A = A->getNext()) {
4983 // Only warn if the attribute is an unignored, non-type attribute.
4984 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
4985 if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4987 if (A->getKind() == AttributeList::UnknownAttribute) {
4988 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4989 << A->getName() << A->getRange();
4991 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4992 << A->getName() << A->getRange();
4997 /// checkUnusedDeclAttributes - Given a declarator which is not being
4998 /// used to build a declaration, complain about any decl attributes
4999 /// which might be lying around on it.
5000 void Sema::checkUnusedDeclAttributes(Declarator &D) {
5001 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
5002 ::checkUnusedDeclAttributes(*this, D.getAttributes());
5003 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
5004 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
5007 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
5008 /// \#pragma weak needs a non-definition decl and source may not have one.
5009 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
5010 SourceLocation Loc) {
5011 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
5012 NamedDecl *NewD = 0;
5013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5014 FunctionDecl *NewFD;
5015 // FIXME: Missing call to CheckFunctionDeclaration().
5017 // FIXME: Is the qualifier info correct?
5018 // FIXME: Is the DeclContext correct?
5019 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
5020 Loc, Loc, DeclarationName(II),
5021 FD->getType(), FD->getTypeSourceInfo(),
5022 SC_None, false/*isInlineSpecified*/,
5024 false/*isConstexprSpecified*/);
5027 if (FD->getQualifier())
5028 NewFD->setQualifierInfo(FD->getQualifierLoc());
5030 // Fake up parameter variables; they are declared as if this were
5032 QualType FDTy = FD->getType();
5033 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
5034 SmallVector<ParmVarDecl*, 16> Params;
5035 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
5036 AE = FT->arg_type_end(); AI != AE; ++AI) {
5037 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, *AI);
5038 Param->setScopeInfo(0, Params.size());
5039 Params.push_back(Param);
5041 NewFD->setParams(Params);
5043 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
5044 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
5045 VD->getInnerLocStart(), VD->getLocation(), II,
5046 VD->getType(), VD->getTypeSourceInfo(),
5047 VD->getStorageClass());
5048 if (VD->getQualifier()) {
5049 VarDecl *NewVD = cast<VarDecl>(NewD);
5050 NewVD->setQualifierInfo(VD->getQualifierLoc());
5056 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
5057 /// applied to it, possibly with an alias.
5058 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
5059 if (W.getUsed()) return; // only do this once
5061 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
5062 IdentifierInfo *NDId = ND->getIdentifier();
5063 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
5064 NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
5066 NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
5067 WeakTopLevelDecl.push_back(NewD);
5068 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
5069 // to insert Decl at TU scope, sorry.
5070 DeclContext *SavedContext = CurContext;
5071 CurContext = Context.getTranslationUnitDecl();
5072 PushOnScopeChains(NewD, S);
5073 CurContext = SavedContext;
5074 } else { // just add weak to existing
5075 ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
5079 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
5080 // It's valid to "forward-declare" #pragma weak, in which case we
5082 LoadExternalWeakUndeclaredIdentifiers();
5083 if (!WeakUndeclaredIdentifiers.empty()) {
5084 NamedDecl *ND = NULL;
5085 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5086 if (VD->isExternC())
5088 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5089 if (FD->isExternC())
5092 if (IdentifierInfo *Id = ND->getIdentifier()) {
5093 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
5094 = WeakUndeclaredIdentifiers.find(Id);
5095 if (I != WeakUndeclaredIdentifiers.end()) {
5096 WeakInfo W = I->second;
5097 DeclApplyPragmaWeak(S, ND, W);
5098 WeakUndeclaredIdentifiers[Id] = W;
5105 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
5106 /// it, apply them to D. This is a bit tricky because PD can have attributes
5107 /// specified in many different places, and we need to find and apply them all.
5108 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
5109 // Apply decl attributes from the DeclSpec if present.
5110 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
5111 ProcessDeclAttributeList(S, D, Attrs);
5113 // Walk the declarator structure, applying decl attributes that were in a type
5114 // position to the decl itself. This handles cases like:
5115 // int *__attr__(x)** D;
5116 // when X is a decl attribute.
5117 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5118 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5119 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
5121 // Finally, apply any attributes on the decl itself.
5122 if (const AttributeList *Attrs = PD.getAttributes())
5123 ProcessDeclAttributeList(S, D, Attrs);
5126 /// Is the given declaration allowed to use a forbidden type?
5127 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
5128 // Private ivars are always okay. Unfortunately, people don't
5129 // always properly make their ivars private, even in system headers.
5130 // Plus we need to make fields okay, too.
5131 // Function declarations in sys headers will be marked unavailable.
5132 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5133 !isa<FunctionDecl>(decl))
5136 // Require it to be declared in a system header.
5137 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
5140 /// Handle a delayed forbidden-type diagnostic.
5141 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5143 if (decl && isForbiddenTypeAllowed(S, decl)) {
5144 decl->addAttr(new (S.Context) UnavailableAttr(diag.Loc, S.Context,
5145 "this system declaration uses an unsupported type"));
5148 if (S.getLangOpts().ObjCAutoRefCount)
5149 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5150 // FIXME: we may want to suppress diagnostics for all
5151 // kind of forbidden type messages on unavailable functions.
5152 if (FD->hasAttr<UnavailableAttr>() &&
5153 diag.getForbiddenTypeDiagnostic() ==
5154 diag::err_arc_array_param_no_ownership) {
5155 diag.Triggered = true;
5160 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5161 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5162 diag.Triggered = true;
5165 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5166 assert(DelayedDiagnostics.getCurrentPool());
5167 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5168 DelayedDiagnostics.popWithoutEmitting(state);
5170 // When delaying diagnostics to run in the context of a parsed
5171 // declaration, we only want to actually emit anything if parsing
5175 // We emit all the active diagnostics in this pool or any of its
5176 // parents. In general, we'll get one pool for the decl spec
5177 // and a child pool for each declarator; in a decl group like:
5178 // deprecated_typedef foo, *bar, baz();
5179 // only the declarator pops will be passed decls. This is correct;
5180 // we really do need to consider delayed diagnostics from the decl spec
5181 // for each of the different declarations.
5182 const DelayedDiagnosticPool *pool = &poppedPool;
5184 for (DelayedDiagnosticPool::pool_iterator
5185 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5186 // This const_cast is a bit lame. Really, Triggered should be mutable.
5187 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5191 switch (diag.Kind) {
5192 case DelayedDiagnostic::Deprecation:
5193 // Don't bother giving deprecation diagnostics if the decl is invalid.
5194 if (!decl->isInvalidDecl())
5195 HandleDelayedDeprecationCheck(diag, decl);
5198 case DelayedDiagnostic::Access:
5199 HandleDelayedAccessCheck(diag, decl);
5202 case DelayedDiagnostic::ForbiddenType:
5203 handleDelayedForbiddenType(*this, diag, decl);
5207 } while ((pool = pool->getParent()));
5210 /// Given a set of delayed diagnostics, re-emit them as if they had
5211 /// been delayed in the current context instead of in the given pool.
5212 /// Essentially, this just moves them to the current pool.
5213 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5214 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5215 assert(curPool && "re-emitting in undelayed context not supported");
5216 curPool->steal(pool);
5219 static bool isDeclDeprecated(Decl *D) {
5221 if (D->isDeprecated())
5223 // A category implicitly has the availability of the interface.
5224 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5225 return CatD->getClassInterface()->isDeprecated();
5226 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5231 DoEmitDeprecationWarning(Sema &S, const NamedDecl *D, StringRef Message,
5233 const ObjCInterfaceDecl *UnknownObjCClass,
5234 const ObjCPropertyDecl *ObjCPropery) {
5235 DeclarationName Name = D->getDeclName();
5236 if (!Message.empty()) {
5237 S.Diag(Loc, diag::warn_deprecated_message) << Name << Message;
5238 S.Diag(D->getLocation(),
5239 isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
5240 : diag::note_previous_decl) << Name;
5242 S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
5243 << ObjCPropery->getDeclName() << 0;
5244 } else if (!UnknownObjCClass) {
5245 S.Diag(Loc, diag::warn_deprecated) << D->getDeclName();
5246 S.Diag(D->getLocation(),
5247 isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
5248 : diag::note_previous_decl) << Name;
5250 S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
5251 << ObjCPropery->getDeclName() << 0;
5253 S.Diag(Loc, diag::warn_deprecated_fwdclass_message) << Name;
5254 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5258 void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
5260 if (isDeclDeprecated(Ctx))
5263 DD.Triggered = true;
5264 DoEmitDeprecationWarning(*this, DD.getDeprecationDecl(),
5265 DD.getDeprecationMessage(), DD.Loc,
5266 DD.getUnknownObjCClass(),
5267 DD.getObjCProperty());
5270 void Sema::EmitDeprecationWarning(NamedDecl *D, StringRef Message,
5272 const ObjCInterfaceDecl *UnknownObjCClass,
5273 const ObjCPropertyDecl *ObjCProperty) {
5274 // Delay if we're currently parsing a declaration.
5275 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
5276 DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D,
5283 // Otherwise, don't warn if our current context is deprecated.
5284 if (isDeclDeprecated(cast<Decl>(getCurLexicalContext())))
5286 DoEmitDeprecationWarning(*this, D, Message, Loc, UnknownObjCClass, ObjCProperty);