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/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/DelayedDiagnostic.h"
23 #include "llvm/ADT/StringExtras.h"
24 using namespace clang;
27 /// These constants match the enumerated choices of
28 /// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
32 ExpectedVariableOrFunction,
33 ExpectedFunctionOrMethod,
35 ExpectedParameterOrMethod,
36 ExpectedFunctionMethodOrBlock,
37 ExpectedClassOrVirtualMethod,
38 ExpectedFunctionMethodOrParameter,
40 ExpectedVirtualMethod,
44 ExpectedVariableFunctionOrLabel
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 static const FunctionType *getFunctionType(const Decl *d,
52 bool blocksToo = true) {
54 if (const ValueDecl *decl = dyn_cast<ValueDecl>(d))
56 else if (const FieldDecl *decl = dyn_cast<FieldDecl>(d))
58 else if (const TypedefNameDecl* decl = dyn_cast<TypedefNameDecl>(d))
59 Ty = decl->getUnderlyingType();
63 if (Ty->isFunctionPointerType())
64 Ty = Ty->getAs<PointerType>()->getPointeeType();
65 else if (blocksToo && Ty->isBlockPointerType())
66 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
68 return Ty->getAs<FunctionType>();
71 // FIXME: We should provide an abstraction around a method or function
72 // to provide the following bits of information.
74 /// isFunction - Return true if the given decl has function
75 /// type (function or function-typed variable).
76 static bool isFunction(const Decl *d) {
77 return getFunctionType(d, false) != NULL;
80 /// isFunctionOrMethod - Return true if the given decl has function
81 /// type (function or function-typed variable) or an Objective-C
83 static bool isFunctionOrMethod(const Decl *d) {
84 return isFunction(d)|| isa<ObjCMethodDecl>(d);
87 /// isFunctionOrMethodOrBlock - Return true if the given decl has function
88 /// type (function or function-typed variable) or an Objective-C
89 /// method or a block.
90 static bool isFunctionOrMethodOrBlock(const Decl *d) {
91 if (isFunctionOrMethod(d))
93 // check for block is more involved.
94 if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
95 QualType Ty = V->getType();
96 return Ty->isBlockPointerType();
98 return isa<BlockDecl>(d);
101 /// Return true if the given decl has a declarator that should have
102 /// been processed by Sema::GetTypeForDeclarator.
103 static bool hasDeclarator(const Decl *d) {
104 // In some sense, TypedefNameDecl really *ought* to be a DeclaratorDecl.
105 return isa<DeclaratorDecl>(d) || isa<BlockDecl>(d) || isa<TypedefNameDecl>(d);
108 /// hasFunctionProto - Return true if the given decl has a argument
109 /// information. This decl should have already passed
110 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
111 static bool hasFunctionProto(const Decl *d) {
112 if (const FunctionType *FnTy = getFunctionType(d))
113 return isa<FunctionProtoType>(FnTy);
115 assert(isa<ObjCMethodDecl>(d) || isa<BlockDecl>(d));
120 /// getFunctionOrMethodNumArgs - Return number of function or method
121 /// arguments. It is an error to call this on a K&R function (use
122 /// hasFunctionProto first).
123 static unsigned getFunctionOrMethodNumArgs(const Decl *d) {
124 if (const FunctionType *FnTy = getFunctionType(d))
125 return cast<FunctionProtoType>(FnTy)->getNumArgs();
126 if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
127 return BD->getNumParams();
128 return cast<ObjCMethodDecl>(d)->param_size();
131 static QualType getFunctionOrMethodArgType(const Decl *d, unsigned Idx) {
132 if (const FunctionType *FnTy = getFunctionType(d))
133 return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
134 if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
135 return BD->getParamDecl(Idx)->getType();
137 return cast<ObjCMethodDecl>(d)->param_begin()[Idx]->getType();
140 static QualType getFunctionOrMethodResultType(const Decl *d) {
141 if (const FunctionType *FnTy = getFunctionType(d))
142 return cast<FunctionProtoType>(FnTy)->getResultType();
143 return cast<ObjCMethodDecl>(d)->getResultType();
146 static bool isFunctionOrMethodVariadic(const Decl *d) {
147 if (const FunctionType *FnTy = getFunctionType(d)) {
148 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
149 return proto->isVariadic();
150 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
151 return BD->isVariadic();
153 return cast<ObjCMethodDecl>(d)->isVariadic();
157 static bool isInstanceMethod(const Decl *d) {
158 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(d))
159 return MethodDecl->isInstance();
163 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
164 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
168 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
172 IdentifierInfo* ClsName = Cls->getIdentifier();
174 // FIXME: Should we walk the chain of classes?
175 return ClsName == &Ctx.Idents.get("NSString") ||
176 ClsName == &Ctx.Idents.get("NSMutableString");
179 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
180 const PointerType *PT = T->getAs<PointerType>();
184 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
188 const RecordDecl *RD = RT->getDecl();
189 if (RD->getTagKind() != TTK_Struct)
192 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
195 //===----------------------------------------------------------------------===//
196 // Attribute Implementations
197 //===----------------------------------------------------------------------===//
199 // FIXME: All this manual attribute parsing code is gross. At the
200 // least add some helper functions to check most argument patterns (#
201 // and types of args).
203 static void HandleExtVectorTypeAttr(Scope *scope, Decl *d,
204 const AttributeList &Attr, Sema &S) {
205 TypedefNameDecl *tDecl = dyn_cast<TypedefNameDecl>(d);
207 S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
211 QualType curType = tDecl->getUnderlyingType();
215 // Special case where the argument is a template id.
216 if (Attr.getParameterName()) {
219 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
220 sizeExpr = S.ActOnIdExpression(scope, SS, id, false, false).takeAs<Expr>();
222 // check the attribute arguments.
223 if (Attr.getNumArgs() != 1) {
224 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
227 sizeExpr = Attr.getArg(0);
230 // Instantiate/Install the vector type, and let Sema build the type for us.
231 // This will run the reguired checks.
232 QualType T = S.BuildExtVectorType(curType, sizeExpr, Attr.getLoc());
234 // FIXME: preserve the old source info.
235 tDecl->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(T));
237 // Remember this typedef decl, we will need it later for diagnostics.
238 S.ExtVectorDecls.push_back(tDecl);
242 static void HandlePackedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
243 // check the attribute arguments.
244 if (Attr.getNumArgs() > 0) {
245 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
249 if (TagDecl *TD = dyn_cast<TagDecl>(d))
250 TD->addAttr(::new (S.Context) PackedAttr(Attr.getLoc(), S.Context));
251 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
252 // If the alignment is less than or equal to 8 bits, the packed attribute
254 if (!FD->getType()->isIncompleteType() &&
255 S.Context.getTypeAlign(FD->getType()) <= 8)
256 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
257 << Attr.getName() << FD->getType();
259 FD->addAttr(::new (S.Context) PackedAttr(Attr.getLoc(), S.Context));
261 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
264 static void HandleMsStructAttr(Decl *d, const AttributeList &Attr, Sema &S) {
265 if (TagDecl *TD = dyn_cast<TagDecl>(d))
266 TD->addAttr(::new (S.Context) MsStructAttr(Attr.getLoc(), S.Context));
268 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
271 static void HandleIBAction(Decl *d, const AttributeList &Attr, Sema &S) {
272 // check the attribute arguments.
273 if (Attr.getNumArgs() > 0) {
274 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
278 // The IBAction attributes only apply to instance methods.
279 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
280 if (MD->isInstanceMethod()) {
281 d->addAttr(::new (S.Context) IBActionAttr(Attr.getLoc(), S.Context));
285 S.Diag(Attr.getLoc(), diag::warn_attribute_ibaction) << Attr.getName();
288 static void HandleIBOutlet(Decl *d, const AttributeList &Attr, Sema &S) {
289 // check the attribute arguments.
290 if (Attr.getNumArgs() > 0) {
291 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
295 // The IBOutlet attributes only apply to instance variables of
296 // Objective-C classes.
297 if (isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d)) {
298 d->addAttr(::new (S.Context) IBOutletAttr(Attr.getLoc(), S.Context));
302 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
305 static void HandleIBOutletCollection(Decl *d, const AttributeList &Attr,
308 // The iboutletcollection attribute can have zero or one arguments.
309 if (Attr.getParameterName() && Attr.getNumArgs() > 0) {
310 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
314 // The IBOutletCollection attributes only apply to instance variables of
315 // Objective-C classes.
316 if (!(isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d))) {
317 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
320 if (const ValueDecl *VD = dyn_cast<ValueDecl>(d))
321 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
322 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_object_type)
323 << VD->getType() << 0;
326 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(d))
327 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
328 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_object_type)
329 << PD->getType() << 1;
333 IdentifierInfo *II = Attr.getParameterName();
335 II = &S.Context.Idents.get("id");
337 ParsedType TypeRep = S.getTypeName(*II, Attr.getLoc(),
338 S.getScopeForContext(d->getDeclContext()->getParent()));
340 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
343 QualType QT = TypeRep.get();
344 // Diagnose use of non-object type in iboutletcollection attribute.
345 // FIXME. Gnu attribute extension ignores use of builtin types in
346 // attributes. So, __attribute__((iboutletcollection(char))) will be
347 // treated as __attribute__((iboutletcollection())).
348 if (!QT->isObjCIdType() && !QT->isObjCClassType() &&
349 !QT->isObjCObjectType()) {
350 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
353 d->addAttr(::new (S.Context) IBOutletCollectionAttr(Attr.getLoc(), S.Context,
357 static void HandleNonNullAttr(Decl *d, const AttributeList &Attr, Sema &S) {
358 // GCC ignores the nonnull attribute on K&R style function prototypes, so we
360 if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
361 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
362 << Attr.getName() << ExpectedFunction;
366 // In C++ the implicit 'this' function parameter also counts, and they are
368 bool HasImplicitThisParam = isInstanceMethod(d);
369 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
371 // The nonnull attribute only applies to pointers.
372 llvm::SmallVector<unsigned, 10> NonNullArgs;
374 for (AttributeList::arg_iterator I=Attr.arg_begin(),
375 E=Attr.arg_end(); I!=E; ++I) {
378 // The argument must be an integer constant expression.
380 llvm::APSInt ArgNum(32);
381 if (Ex->isTypeDependent() || Ex->isValueDependent() ||
382 !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
383 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
384 << "nonnull" << Ex->getSourceRange();
388 unsigned x = (unsigned) ArgNum.getZExtValue();
390 if (x < 1 || x > NumArgs) {
391 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
392 << "nonnull" << I.getArgNum() << Ex->getSourceRange();
397 if (HasImplicitThisParam) {
399 S.Diag(Attr.getLoc(),
400 diag::err_attribute_invalid_implicit_this_argument)
401 << "nonnull" << Ex->getSourceRange();
407 // Is the function argument a pointer type?
408 QualType T = getFunctionOrMethodArgType(d, x).getNonReferenceType();
409 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
410 // FIXME: Should also highlight argument in decl.
411 S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
412 << "nonnull" << Ex->getSourceRange();
416 NonNullArgs.push_back(x);
419 // If no arguments were specified to __attribute__((nonnull)) then all pointer
420 // arguments have a nonnull attribute.
421 if (NonNullArgs.empty()) {
422 for (unsigned I = 0, E = getFunctionOrMethodNumArgs(d); I != E; ++I) {
423 QualType T = getFunctionOrMethodArgType(d, I).getNonReferenceType();
424 if (T->isAnyPointerType() || T->isBlockPointerType())
425 NonNullArgs.push_back(I);
426 else if (const RecordType *UT = T->getAsUnionType()) {
427 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
428 RecordDecl *UD = UT->getDecl();
429 for (RecordDecl::field_iterator it = UD->field_begin(),
430 itend = UD->field_end(); it != itend; ++it) {
432 if (T->isAnyPointerType() || T->isBlockPointerType()) {
433 NonNullArgs.push_back(I);
441 // No pointer arguments?
442 if (NonNullArgs.empty()) {
443 // Warn the trivial case only if attribute is not coming from a
444 // macro instantiation.
445 if (Attr.getLoc().isFileID())
446 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
451 unsigned* start = &NonNullArgs[0];
452 unsigned size = NonNullArgs.size();
453 llvm::array_pod_sort(start, start + size);
454 d->addAttr(::new (S.Context) NonNullAttr(Attr.getLoc(), S.Context, start,
458 static void HandleOwnershipAttr(Decl *d, const AttributeList &AL, Sema &S) {
459 // This attribute must be applied to a function declaration.
460 // The first argument to the attribute must be a string,
461 // the name of the resource, for example "malloc".
462 // The following arguments must be argument indexes, the arguments must be
463 // of integer type for Returns, otherwise of pointer type.
464 // The difference between Holds and Takes is that a pointer may still be used
465 // after being held. free() should be __attribute((ownership_takes)), whereas
466 // a list append function may well be __attribute((ownership_holds)).
468 if (!AL.getParameterName()) {
469 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_not_string)
470 << AL.getName()->getName() << 1;
473 // Figure out our Kind, and check arguments while we're at it.
474 OwnershipAttr::OwnershipKind K;
475 switch (AL.getKind()) {
476 case AttributeList::AT_ownership_takes:
477 K = OwnershipAttr::Takes;
478 if (AL.getNumArgs() < 1) {
479 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
483 case AttributeList::AT_ownership_holds:
484 K = OwnershipAttr::Holds;
485 if (AL.getNumArgs() < 1) {
486 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
490 case AttributeList::AT_ownership_returns:
491 K = OwnershipAttr::Returns;
492 if (AL.getNumArgs() > 1) {
493 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
494 << AL.getNumArgs() + 1;
499 // This should never happen given how we are called.
500 llvm_unreachable("Unknown ownership attribute");
503 if (!isFunction(d) || !hasFunctionProto(d)) {
504 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
505 << AL.getName() << ExpectedFunction;
509 // In C++ the implicit 'this' function parameter also counts, and they are
511 bool HasImplicitThisParam = isInstanceMethod(d);
512 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
514 llvm::StringRef Module = AL.getParameterName()->getName();
516 // Normalize the argument, __foo__ becomes foo.
517 if (Module.startswith("__") && Module.endswith("__"))
518 Module = Module.substr(2, Module.size() - 4);
520 llvm::SmallVector<unsigned, 10> OwnershipArgs;
522 for (AttributeList::arg_iterator I = AL.arg_begin(), E = AL.arg_end(); I != E;
526 llvm::APSInt ArgNum(32);
527 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
528 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
529 S.Diag(AL.getLoc(), diag::err_attribute_argument_not_int)
530 << AL.getName()->getName() << IdxExpr->getSourceRange();
534 unsigned x = (unsigned) ArgNum.getZExtValue();
536 if (x > NumArgs || x < 1) {
537 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
538 << AL.getName()->getName() << x << IdxExpr->getSourceRange();
542 if (HasImplicitThisParam) {
544 S.Diag(AL.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
545 << "ownership" << IdxExpr->getSourceRange();
552 case OwnershipAttr::Takes:
553 case OwnershipAttr::Holds: {
554 // Is the function argument a pointer type?
555 QualType T = getFunctionOrMethodArgType(d, x);
556 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
557 // FIXME: Should also highlight argument in decl.
558 S.Diag(AL.getLoc(), diag::err_ownership_type)
559 << ((K==OwnershipAttr::Takes)?"ownership_takes":"ownership_holds")
561 << IdxExpr->getSourceRange();
566 case OwnershipAttr::Returns: {
567 if (AL.getNumArgs() > 1) {
568 // Is the function argument an integer type?
569 Expr *IdxExpr = AL.getArg(0);
570 llvm::APSInt ArgNum(32);
571 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
572 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
573 S.Diag(AL.getLoc(), diag::err_ownership_type)
574 << "ownership_returns" << "integer"
575 << IdxExpr->getSourceRange();
582 llvm_unreachable("Unknown ownership attribute");
585 // Check we don't have a conflict with another ownership attribute.
586 for (specific_attr_iterator<OwnershipAttr>
587 i = d->specific_attr_begin<OwnershipAttr>(),
588 e = d->specific_attr_end<OwnershipAttr>();
590 if ((*i)->getOwnKind() != K) {
591 for (const unsigned *I = (*i)->args_begin(), *E = (*i)->args_end();
594 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
595 << AL.getName()->getName() << "ownership_*";
600 OwnershipArgs.push_back(x);
603 unsigned* start = OwnershipArgs.data();
604 unsigned size = OwnershipArgs.size();
605 llvm::array_pod_sort(start, start + size);
607 if (K != OwnershipAttr::Returns && OwnershipArgs.empty()) {
608 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
612 d->addAttr(::new (S.Context) OwnershipAttr(AL.getLoc(), S.Context, K, Module,
616 /// Whether this declaration has internal linkage for the purposes of
617 /// things that want to complain about things not have internal linkage.
618 static bool hasEffectivelyInternalLinkage(NamedDecl *D) {
619 switch (D->getLinkage()) {
621 case InternalLinkage:
624 // Template instantiations that go from external to unique-external
625 // shouldn't get diagnosed.
626 case UniqueExternalLinkage:
629 case ExternalLinkage:
632 llvm_unreachable("unknown linkage kind!");
636 static void HandleWeakRefAttr(Decl *d, const AttributeList &Attr, Sema &S) {
637 // Check the attribute arguments.
638 if (Attr.getNumArgs() > 1) {
639 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
643 if (!isa<VarDecl>(d) && !isa<FunctionDecl>(d)) {
644 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
645 << Attr.getName() << ExpectedVariableOrFunction;
649 NamedDecl *nd = cast<NamedDecl>(d);
653 // static int a __attribute__((weakref ("v2")));
654 // static int b() __attribute__((weakref ("f3")));
656 // and ignores the attributes of
658 // static int a __attribute__((weakref ("v2")));
661 const DeclContext *Ctx = d->getDeclContext()->getRedeclContext();
662 if (!Ctx->isFileContext()) {
663 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
664 nd->getNameAsString();
668 // The GCC manual says
670 // At present, a declaration to which `weakref' is attached can only
676 // given as an argument to `weakref' or to `alias', `weakref' is
677 // equivalent to `weak'.
679 // gcc 4.4.1 will accept
680 // int a7 __attribute__((weakref));
682 // int a7 __attribute__((weak));
683 // This looks like a bug in gcc. We reject that for now. We should revisit
684 // it if this behaviour is actually used.
686 if (!hasEffectivelyInternalLinkage(nd)) {
687 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_static);
692 // static ((alias ("y"), weakref)).
693 // Should we? How to check that weakref is before or after alias?
695 if (Attr.getNumArgs() == 1) {
696 Expr *Arg = Attr.getArg(0);
697 Arg = Arg->IgnoreParenCasts();
698 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
700 if (Str == 0 || Str->isWide()) {
701 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
705 // GCC will accept anything as the argument of weakref. Should we
706 // check for an existing decl?
707 d->addAttr(::new (S.Context) AliasAttr(Attr.getLoc(), S.Context,
711 d->addAttr(::new (S.Context) WeakRefAttr(Attr.getLoc(), S.Context));
714 static void HandleAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
715 // check the attribute arguments.
716 if (Attr.getNumArgs() != 1) {
717 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
721 Expr *Arg = Attr.getArg(0);
722 Arg = Arg->IgnoreParenCasts();
723 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
725 if (Str == 0 || Str->isWide()) {
726 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
731 if (S.Context.Target.getTriple().isOSDarwin()) {
732 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
736 // FIXME: check if target symbol exists in current file
738 d->addAttr(::new (S.Context) AliasAttr(Attr.getLoc(), S.Context,
742 static void HandleNakedAttr(Decl *d, const AttributeList &Attr,
744 // Check the attribute arguments.
745 if (Attr.getNumArgs() != 0) {
746 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
750 if (!isa<FunctionDecl>(d)) {
751 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
752 << Attr.getName() << ExpectedFunction;
756 d->addAttr(::new (S.Context) NakedAttr(Attr.getLoc(), S.Context));
759 static void HandleAlwaysInlineAttr(Decl *d, const AttributeList &Attr,
761 // Check the attribute arguments.
762 if (Attr.hasParameterOrArguments()) {
763 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
767 if (!isa<FunctionDecl>(d)) {
768 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
769 << Attr.getName() << ExpectedFunction;
773 d->addAttr(::new (S.Context) AlwaysInlineAttr(Attr.getLoc(), S.Context));
776 static void HandleMallocAttr(Decl *d, const AttributeList &Attr, Sema &S) {
777 // Check the attribute arguments.
778 if (Attr.hasParameterOrArguments()) {
779 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
783 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
784 QualType RetTy = FD->getResultType();
785 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
786 d->addAttr(::new (S.Context) MallocAttr(Attr.getLoc(), S.Context));
791 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
794 static void HandleMayAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
795 // check the attribute arguments.
796 if (Attr.getNumArgs() != 0) {
797 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
801 d->addAttr(::new (S.Context) MayAliasAttr(Attr.getLoc(), S.Context));
804 static void HandleNoCommonAttr(Decl *d, const AttributeList &Attr, Sema &S) {
805 assert(Attr.isInvalid() == false);
807 d->addAttr(::new (S.Context) NoCommonAttr(Attr.getLoc(), S.Context));
809 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
810 << Attr.getName() << ExpectedVariable;
813 static void HandleCommonAttr(Decl *d, const AttributeList &Attr, Sema &S) {
814 assert(Attr.isInvalid() == false);
816 d->addAttr(::new (S.Context) CommonAttr(Attr.getLoc(), S.Context));
818 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
819 << Attr.getName() << ExpectedVariable;
822 static void HandleNoReturnAttr(Decl *d, const AttributeList &attr, Sema &S) {
823 if (hasDeclarator(d)) return;
825 if (S.CheckNoReturnAttr(attr)) return;
827 if (!isa<ObjCMethodDecl>(d)) {
828 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
829 << attr.getName() << ExpectedFunctionOrMethod;
833 d->addAttr(::new (S.Context) NoReturnAttr(attr.getLoc(), S.Context));
836 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
837 if (attr.hasParameterOrArguments()) {
838 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
846 static void HandleAnalyzerNoReturnAttr(Decl *d, const AttributeList &Attr,
849 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
850 // because 'analyzer_noreturn' does not impact the type.
852 if (Attr.getNumArgs() != 0) {
853 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
857 if (!isFunctionOrMethod(d) && !isa<BlockDecl>(d)) {
858 ValueDecl *VD = dyn_cast<ValueDecl>(d);
859 if (VD == 0 || (!VD->getType()->isBlockPointerType()
860 && !VD->getType()->isFunctionPointerType())) {
861 S.Diag(Attr.getLoc(),
862 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
863 : diag::warn_attribute_wrong_decl_type)
864 << Attr.getName() << ExpectedFunctionMethodOrBlock;
869 d->addAttr(::new (S.Context) AnalyzerNoReturnAttr(Attr.getLoc(), S.Context));
873 static void HandleVecReturnAttr(Decl *d, const AttributeList &Attr,
876 Returning a Vector Class in Registers
878 According to the PPU ABI specifications, a class with a single member of
879 vector type is returned in memory when used as the return value of a function.
880 This results in inefficient code when implementing vector classes. To return
881 the value in a single vector register, add the vecreturn attribute to the
882 class definition. This attribute is also applicable to struct types.
889 } __attribute__((vecreturn));
891 Vector Add(Vector lhs, Vector rhs)
894 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
895 return result; // This will be returned in a register
898 if (!isa<RecordDecl>(d)) {
899 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
900 << Attr.getName() << ExpectedClass;
904 if (d->getAttr<VecReturnAttr>()) {
905 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
909 RecordDecl *record = cast<RecordDecl>(d);
912 if (!isa<CXXRecordDecl>(record)) {
913 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
917 if (!cast<CXXRecordDecl>(record)->isPOD()) {
918 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
922 for (RecordDecl::field_iterator iter = record->field_begin();
923 iter != record->field_end(); iter++) {
924 if ((count == 1) || !iter->getType()->isVectorType()) {
925 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
931 d->addAttr(::new (S.Context) VecReturnAttr(Attr.getLoc(), S.Context));
934 static void HandleDependencyAttr(Decl *d, const AttributeList &Attr, Sema &S) {
935 if (!isFunctionOrMethod(d) && !isa<ParmVarDecl>(d)) {
936 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
937 << Attr.getName() << ExpectedFunctionMethodOrParameter;
940 // FIXME: Actually store the attribute on the declaration
943 static void HandleUnusedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
944 // check the attribute arguments.
945 if (Attr.hasParameterOrArguments()) {
946 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
950 if (!isa<VarDecl>(d) && !isa<ObjCIvarDecl>(d) && !isFunctionOrMethod(d) &&
951 !isa<TypeDecl>(d) && !isa<LabelDecl>(d)) {
952 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
953 << Attr.getName() << ExpectedVariableFunctionOrLabel;
957 d->addAttr(::new (S.Context) UnusedAttr(Attr.getLoc(), S.Context));
960 static void HandleUsedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
961 // check the attribute arguments.
962 if (Attr.hasParameterOrArguments()) {
963 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
967 if (const VarDecl *VD = dyn_cast<VarDecl>(d)) {
968 if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
969 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
972 } else if (!isFunctionOrMethod(d)) {
973 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
974 << Attr.getName() << ExpectedVariableOrFunction;
978 d->addAttr(::new (S.Context) UsedAttr(Attr.getLoc(), S.Context));
981 static void HandleConstructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
982 // check the attribute arguments.
983 if (Attr.getNumArgs() > 1) {
984 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
988 int priority = 65535; // FIXME: Do not hardcode such constants.
989 if (Attr.getNumArgs() > 0) {
990 Expr *E = Attr.getArg(0);
991 llvm::APSInt Idx(32);
992 if (E->isTypeDependent() || E->isValueDependent() ||
993 !E->isIntegerConstantExpr(Idx, S.Context)) {
994 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
995 << "constructor" << 1 << E->getSourceRange();
998 priority = Idx.getZExtValue();
1001 if (!isa<FunctionDecl>(d)) {
1002 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1003 << Attr.getName() << ExpectedFunction;
1007 d->addAttr(::new (S.Context) ConstructorAttr(Attr.getLoc(), S.Context,
1011 static void HandleDestructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1012 // check the attribute arguments.
1013 if (Attr.getNumArgs() > 1) {
1014 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1018 int priority = 65535; // FIXME: Do not hardcode such constants.
1019 if (Attr.getNumArgs() > 0) {
1020 Expr *E = Attr.getArg(0);
1021 llvm::APSInt Idx(32);
1022 if (E->isTypeDependent() || E->isValueDependent() ||
1023 !E->isIntegerConstantExpr(Idx, S.Context)) {
1024 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1025 << "destructor" << 1 << E->getSourceRange();
1028 priority = Idx.getZExtValue();
1031 if (!isa<FunctionDecl>(d)) {
1032 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1033 << Attr.getName() << ExpectedFunction;
1037 d->addAttr(::new (S.Context) DestructorAttr(Attr.getLoc(), S.Context,
1041 static void HandleDeprecatedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1042 unsigned NumArgs = Attr.getNumArgs();
1044 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1048 // Handle the case where deprecated attribute has a text message.
1049 llvm::StringRef Str;
1051 StringLiteral *SE = dyn_cast<StringLiteral>(Attr.getArg(0));
1053 S.Diag(Attr.getArg(0)->getLocStart(), diag::err_attribute_not_string)
1057 Str = SE->getString();
1060 d->addAttr(::new (S.Context) DeprecatedAttr(Attr.getLoc(), S.Context, Str));
1063 static void HandleUnavailableAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1064 unsigned NumArgs = Attr.getNumArgs();
1066 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1070 // Handle the case where unavailable attribute has a text message.
1071 llvm::StringRef Str;
1073 StringLiteral *SE = dyn_cast<StringLiteral>(Attr.getArg(0));
1075 S.Diag(Attr.getArg(0)->getLocStart(),
1076 diag::err_attribute_not_string) << "unavailable";
1079 Str = SE->getString();
1081 d->addAttr(::new (S.Context) UnavailableAttr(Attr.getLoc(), S.Context, Str));
1084 static void HandleAvailabilityAttr(Decl *d, const AttributeList &Attr,
1086 IdentifierInfo *Platform = Attr.getParameterName();
1087 SourceLocation PlatformLoc = Attr.getParameterLoc();
1089 llvm::StringRef PlatformName
1090 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
1091 if (PlatformName.empty()) {
1092 S.Diag(PlatformLoc, diag::warn_availability_unknown_platform)
1095 PlatformName = Platform->getName();
1098 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
1099 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
1100 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
1101 bool IsUnavailable = Attr.getUnavailableLoc().isValid();
1103 // Ensure that Introduced < Deprecated < Obsoleted (although not all
1104 // of these steps are needed).
1105 if (Introduced.isValid() && Deprecated.isValid() &&
1106 !(Introduced.Version < Deprecated.Version)) {
1107 S.Diag(Introduced.KeywordLoc, diag::warn_availability_version_ordering)
1108 << 1 << PlatformName << Deprecated.Version.getAsString()
1109 << 0 << Introduced.Version.getAsString();
1113 if (Introduced.isValid() && Obsoleted.isValid() &&
1114 !(Introduced.Version < Obsoleted.Version)) {
1115 S.Diag(Introduced.KeywordLoc, diag::warn_availability_version_ordering)
1116 << 2 << PlatformName << Obsoleted.Version.getAsString()
1117 << 0 << Introduced.Version.getAsString();
1121 if (Deprecated.isValid() && Obsoleted.isValid() &&
1122 !(Deprecated.Version < Obsoleted.Version)) {
1123 S.Diag(Deprecated.KeywordLoc, diag::warn_availability_version_ordering)
1124 << 2 << PlatformName << Obsoleted.Version.getAsString()
1125 << 1 << Deprecated.Version.getAsString();
1129 d->addAttr(::new (S.Context) AvailabilityAttr(Attr.getLoc(), S.Context,
1137 static void HandleVisibilityAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1138 // check the attribute arguments.
1139 if (Attr.getNumArgs() != 1) {
1140 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1144 Expr *Arg = Attr.getArg(0);
1145 Arg = Arg->IgnoreParenCasts();
1146 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1148 if (Str == 0 || Str->isWide()) {
1149 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1150 << "visibility" << 1;
1154 llvm::StringRef TypeStr = Str->getString();
1155 VisibilityAttr::VisibilityType type;
1157 if (TypeStr == "default")
1158 type = VisibilityAttr::Default;
1159 else if (TypeStr == "hidden")
1160 type = VisibilityAttr::Hidden;
1161 else if (TypeStr == "internal")
1162 type = VisibilityAttr::Hidden; // FIXME
1163 else if (TypeStr == "protected")
1164 type = VisibilityAttr::Protected;
1166 S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
1170 d->addAttr(::new (S.Context) VisibilityAttr(Attr.getLoc(), S.Context, type));
1173 static void HandleObjCMethodFamilyAttr(Decl *decl, const AttributeList &attr,
1175 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(decl);
1177 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
1182 if (attr.getNumArgs() != 0 || !attr.getParameterName()) {
1183 if (!attr.getParameterName() && attr.getNumArgs() == 1) {
1184 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
1185 << "objc_method_family" << 1;
1187 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1193 llvm::StringRef param = attr.getParameterName()->getName();
1194 ObjCMethodFamilyAttr::FamilyKind family;
1195 if (param == "none")
1196 family = ObjCMethodFamilyAttr::OMF_None;
1197 else if (param == "alloc")
1198 family = ObjCMethodFamilyAttr::OMF_alloc;
1199 else if (param == "copy")
1200 family = ObjCMethodFamilyAttr::OMF_copy;
1201 else if (param == "init")
1202 family = ObjCMethodFamilyAttr::OMF_init;
1203 else if (param == "mutableCopy")
1204 family = ObjCMethodFamilyAttr::OMF_mutableCopy;
1205 else if (param == "new")
1206 family = ObjCMethodFamilyAttr::OMF_new;
1208 // Just warn and ignore it. This is future-proof against new
1209 // families being used in system headers.
1210 S.Diag(attr.getParameterLoc(), diag::warn_unknown_method_family);
1214 decl->addAttr(new (S.Context) ObjCMethodFamilyAttr(attr.getLoc(),
1215 S.Context, family));
1218 static void HandleObjCExceptionAttr(Decl *D, const AttributeList &Attr,
1220 if (Attr.getNumArgs() != 0) {
1221 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1225 ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
1227 S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
1231 D->addAttr(::new (S.Context) ObjCExceptionAttr(Attr.getLoc(), S.Context));
1234 static void HandleObjCNSObject(Decl *D, const AttributeList &Attr, Sema &S) {
1235 if (Attr.getNumArgs() != 0) {
1236 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1239 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1240 QualType T = TD->getUnderlyingType();
1241 if (!T->isPointerType() ||
1242 !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
1243 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
1247 D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getLoc(), S.Context));
1251 HandleOverloadableAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1252 if (Attr.getNumArgs() != 0) {
1253 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1257 if (!isa<FunctionDecl>(D)) {
1258 S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
1262 D->addAttr(::new (S.Context) OverloadableAttr(Attr.getLoc(), S.Context));
1265 static void HandleBlocksAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1266 if (!Attr.getParameterName()) {
1267 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1272 if (Attr.getNumArgs() != 0) {
1273 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1277 BlocksAttr::BlockType type;
1278 if (Attr.getParameterName()->isStr("byref"))
1279 type = BlocksAttr::ByRef;
1281 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1282 << "blocks" << Attr.getParameterName();
1286 d->addAttr(::new (S.Context) BlocksAttr(Attr.getLoc(), S.Context, type));
1289 static void HandleSentinelAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1290 // check the attribute arguments.
1291 if (Attr.getNumArgs() > 2) {
1292 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
1297 if (Attr.getNumArgs() > 0) {
1298 Expr *E = Attr.getArg(0);
1299 llvm::APSInt Idx(32);
1300 if (E->isTypeDependent() || E->isValueDependent() ||
1301 !E->isIntegerConstantExpr(Idx, S.Context)) {
1302 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1303 << "sentinel" << 1 << E->getSourceRange();
1306 sentinel = Idx.getZExtValue();
1309 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
1310 << E->getSourceRange();
1316 if (Attr.getNumArgs() > 1) {
1317 Expr *E = Attr.getArg(1);
1318 llvm::APSInt Idx(32);
1319 if (E->isTypeDependent() || E->isValueDependent() ||
1320 !E->isIntegerConstantExpr(Idx, S.Context)) {
1321 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1322 << "sentinel" << 2 << E->getSourceRange();
1325 nullPos = Idx.getZExtValue();
1327 if (nullPos > 1 || nullPos < 0) {
1328 // FIXME: This error message could be improved, it would be nice
1329 // to say what the bounds actually are.
1330 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
1331 << E->getSourceRange();
1336 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
1337 const FunctionType *FT = FD->getType()->getAs<FunctionType>();
1338 assert(FT && "FunctionDecl has non-function type?");
1340 if (isa<FunctionNoProtoType>(FT)) {
1341 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
1345 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1346 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1349 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d)) {
1350 if (!MD->isVariadic()) {
1351 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1354 } else if (isa<BlockDecl>(d)) {
1355 // Note! BlockDecl is typeless. Variadic diagnostics will be issued by the
1358 } else if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
1359 QualType Ty = V->getType();
1360 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
1361 const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(d)
1362 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
1363 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1364 int m = Ty->isFunctionPointerType() ? 0 : 1;
1365 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
1369 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1370 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1374 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1375 << Attr.getName() << ExpectedFunctionMethodOrBlock;
1378 d->addAttr(::new (S.Context) SentinelAttr(Attr.getLoc(), S.Context, sentinel,
1382 static void HandleWarnUnusedResult(Decl *D, const AttributeList &Attr, Sema &S) {
1383 // check the attribute arguments.
1384 if (Attr.getNumArgs() != 0) {
1385 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1389 if (!isFunction(D) && !isa<ObjCMethodDecl>(D)) {
1390 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1391 << Attr.getName() << ExpectedFunctionOrMethod;
1395 if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
1396 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1397 << Attr.getName() << 0;
1400 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
1401 if (MD->getResultType()->isVoidType()) {
1402 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1403 << Attr.getName() << 1;
1407 D->addAttr(::new (S.Context) WarnUnusedResultAttr(Attr.getLoc(), S.Context));
1410 static void HandleWeakAttr(Decl *d, const AttributeList &attr, Sema &S) {
1411 // check the attribute arguments.
1412 if (attr.hasParameterOrArguments()) {
1413 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1417 if (!isa<VarDecl>(d) && !isa<FunctionDecl>(d)) {
1418 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1419 << attr.getName() << ExpectedVariableOrFunction;
1423 NamedDecl *nd = cast<NamedDecl>(d);
1425 // 'weak' only applies to declarations with external linkage.
1426 if (hasEffectivelyInternalLinkage(nd)) {
1427 S.Diag(attr.getLoc(), diag::err_attribute_weak_static);
1431 nd->addAttr(::new (S.Context) WeakAttr(attr.getLoc(), S.Context));
1434 static void HandleWeakImportAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1435 // check the attribute arguments.
1436 if (Attr.getNumArgs() != 0) {
1437 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1441 // weak_import only applies to variable & function declarations.
1443 if (!D->canBeWeakImported(isDef)) {
1445 S.Diag(Attr.getLoc(),
1446 diag::warn_attribute_weak_import_invalid_on_definition)
1447 << "weak_import" << 2 /*variable and function*/;
1448 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
1449 (S.Context.Target.getTriple().isOSDarwin() &&
1450 isa<ObjCInterfaceDecl>(D))) {
1451 // Nothing to warn about here.
1453 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1454 << Attr.getName() << ExpectedVariableOrFunction;
1459 D->addAttr(::new (S.Context) WeakImportAttr(Attr.getLoc(), S.Context));
1462 static void HandleReqdWorkGroupSize(Decl *D, const AttributeList &Attr,
1464 // Attribute has 3 arguments.
1465 if (Attr.getNumArgs() != 3) {
1466 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1471 for (unsigned i = 0; i < 3; ++i) {
1472 Expr *E = Attr.getArg(i);
1473 llvm::APSInt ArgNum(32);
1474 if (E->isTypeDependent() || E->isValueDependent() ||
1475 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
1476 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1477 << "reqd_work_group_size" << E->getSourceRange();
1480 WGSize[i] = (unsigned) ArgNum.getZExtValue();
1482 D->addAttr(::new (S.Context) ReqdWorkGroupSizeAttr(Attr.getLoc(), S.Context,
1483 WGSize[0], WGSize[1],
1487 static void HandleSectionAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1488 // Attribute has no arguments.
1489 if (Attr.getNumArgs() != 1) {
1490 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1494 // Make sure that there is a string literal as the sections's single
1496 Expr *ArgExpr = Attr.getArg(0);
1497 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1499 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
1503 // If the target wants to validate the section specifier, make it happen.
1504 std::string Error = S.Context.Target.isValidSectionSpecifier(SE->getString());
1505 if (!Error.empty()) {
1506 S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
1511 // This attribute cannot be applied to local variables.
1512 if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
1513 S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
1517 D->addAttr(::new (S.Context) SectionAttr(Attr.getLoc(), S.Context,
1522 static void HandleNothrowAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1523 // check the attribute arguments.
1524 if (Attr.hasParameterOrArguments()) {
1525 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1529 d->addAttr(::new (S.Context) NoThrowAttr(Attr.getLoc(), S.Context));
1532 static void HandleConstAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1533 // check the attribute arguments.
1534 if (Attr.hasParameterOrArguments()) {
1535 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1539 d->addAttr(::new (S.Context) ConstAttr(Attr.getLoc(), S.Context));
1542 static void HandlePureAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1543 // check the attribute arguments.
1544 if (Attr.getNumArgs() != 0) {
1545 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1549 d->addAttr(::new (S.Context) PureAttr(Attr.getLoc(), S.Context));
1552 static void HandleCleanupAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1553 if (!Attr.getParameterName()) {
1554 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1558 if (Attr.getNumArgs() != 0) {
1559 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1563 VarDecl *VD = dyn_cast<VarDecl>(d);
1565 if (!VD || !VD->hasLocalStorage()) {
1566 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
1570 // Look up the function
1571 // FIXME: Lookup probably isn't looking in the right place
1572 NamedDecl *CleanupDecl
1573 = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
1574 Attr.getParameterLoc(), Sema::LookupOrdinaryName);
1576 S.Diag(Attr.getParameterLoc(), diag::err_attribute_cleanup_arg_not_found) <<
1577 Attr.getParameterName();
1581 FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
1583 S.Diag(Attr.getParameterLoc(),
1584 diag::err_attribute_cleanup_arg_not_function)
1585 << Attr.getParameterName();
1589 if (FD->getNumParams() != 1) {
1590 S.Diag(Attr.getParameterLoc(),
1591 diag::err_attribute_cleanup_func_must_take_one_arg)
1592 << Attr.getParameterName();
1596 // We're currently more strict than GCC about what function types we accept.
1597 // If this ever proves to be a problem it should be easy to fix.
1598 QualType Ty = S.Context.getPointerType(VD->getType());
1599 QualType ParamTy = FD->getParamDecl(0)->getType();
1600 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
1601 ParamTy, Ty) != Sema::Compatible) {
1602 S.Diag(Attr.getParameterLoc(),
1603 diag::err_attribute_cleanup_func_arg_incompatible_type) <<
1604 Attr.getParameterName() << ParamTy << Ty;
1608 d->addAttr(::new (S.Context) CleanupAttr(Attr.getLoc(), S.Context, FD));
1609 S.MarkDeclarationReferenced(Attr.getParameterLoc(), FD);
1612 /// Handle __attribute__((format_arg((idx)))) attribute based on
1613 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1614 static void HandleFormatArgAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1615 if (Attr.getNumArgs() != 1) {
1616 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1619 if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
1620 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1621 << Attr.getName() << ExpectedFunction;
1625 // In C++ the implicit 'this' function parameter also counts, and they are
1626 // counted from one.
1627 bool HasImplicitThisParam = isInstanceMethod(d);
1628 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
1629 unsigned FirstIdx = 1;
1631 // checks for the 2nd argument
1632 Expr *IdxExpr = Attr.getArg(0);
1633 llvm::APSInt Idx(32);
1634 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1635 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1636 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1637 << "format" << 2 << IdxExpr->getSourceRange();
1641 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1642 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1643 << "format" << 2 << IdxExpr->getSourceRange();
1647 unsigned ArgIdx = Idx.getZExtValue() - 1;
1649 if (HasImplicitThisParam) {
1651 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
1652 << "format_arg" << IdxExpr->getSourceRange();
1658 // make sure the format string is really a string
1659 QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1661 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
1662 if (not_nsstring_type &&
1663 !isCFStringType(Ty, S.Context) &&
1664 (!Ty->isPointerType() ||
1665 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1666 // FIXME: Should highlight the actual expression that has the wrong type.
1667 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1668 << (not_nsstring_type ? "a string type" : "an NSString")
1669 << IdxExpr->getSourceRange();
1672 Ty = getFunctionOrMethodResultType(d);
1673 if (!isNSStringType(Ty, S.Context) &&
1674 !isCFStringType(Ty, S.Context) &&
1675 (!Ty->isPointerType() ||
1676 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1677 // FIXME: Should highlight the actual expression that has the wrong type.
1678 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
1679 << (not_nsstring_type ? "string type" : "NSString")
1680 << IdxExpr->getSourceRange();
1684 d->addAttr(::new (S.Context) FormatArgAttr(Attr.getLoc(), S.Context,
1685 Idx.getZExtValue()));
1688 enum FormatAttrKind {
1697 /// getFormatAttrKind - Map from format attribute names to supported format
1699 static FormatAttrKind getFormatAttrKind(llvm::StringRef Format) {
1700 // Check for formats that get handled specially.
1701 if (Format == "NSString")
1702 return NSStringFormat;
1703 if (Format == "CFString")
1704 return CFStringFormat;
1705 if (Format == "strftime")
1706 return StrftimeFormat;
1708 // Otherwise, check for supported formats.
1709 if (Format == "scanf" || Format == "printf" || Format == "printf0" ||
1710 Format == "strfmon" || Format == "cmn_err" || Format == "strftime" ||
1711 Format == "NSString" || Format == "CFString" || Format == "vcmn_err" ||
1712 Format == "zcmn_err" ||
1713 Format == "kprintf") // OpenBSD.
1714 return SupportedFormat;
1716 if (Format == "gcc_diag" || Format == "gcc_cdiag" ||
1717 Format == "gcc_cxxdiag" || Format == "gcc_tdiag")
1718 return IgnoredFormat;
1720 return InvalidFormat;
1723 /// Handle __attribute__((init_priority(priority))) attributes based on
1724 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
1725 static void HandleInitPriorityAttr(Decl *d, const AttributeList &Attr,
1727 if (!S.getLangOptions().CPlusPlus) {
1728 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1732 if (!isa<VarDecl>(d) || S.getCurFunctionOrMethodDecl()) {
1733 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
1737 QualType T = dyn_cast<VarDecl>(d)->getType();
1738 if (S.Context.getAsArrayType(T))
1739 T = S.Context.getBaseElementType(T);
1740 if (!T->getAs<RecordType>()) {
1741 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
1746 if (Attr.getNumArgs() != 1) {
1747 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1751 Expr *priorityExpr = Attr.getArg(0);
1753 llvm::APSInt priority(32);
1754 if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
1755 !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
1756 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1757 << "init_priority" << priorityExpr->getSourceRange();
1761 unsigned prioritynum = priority.getZExtValue();
1762 if (prioritynum < 101 || prioritynum > 65535) {
1763 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
1764 << priorityExpr->getSourceRange();
1768 d->addAttr(::new (S.Context) InitPriorityAttr(Attr.getLoc(), S.Context,
1772 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
1773 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1774 static void HandleFormatAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1776 if (!Attr.getParameterName()) {
1777 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1782 if (Attr.getNumArgs() != 2) {
1783 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
1787 if (!isFunctionOrMethodOrBlock(d) || !hasFunctionProto(d)) {
1788 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1789 << Attr.getName() << ExpectedFunction;
1793 // In C++ the implicit 'this' function parameter also counts, and they are
1794 // counted from one.
1795 bool HasImplicitThisParam = isInstanceMethod(d);
1796 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
1797 unsigned FirstIdx = 1;
1799 llvm::StringRef Format = Attr.getParameterName()->getName();
1801 // Normalize the argument, __foo__ becomes foo.
1802 if (Format.startswith("__") && Format.endswith("__"))
1803 Format = Format.substr(2, Format.size() - 4);
1805 // Check for supported formats.
1806 FormatAttrKind Kind = getFormatAttrKind(Format);
1808 if (Kind == IgnoredFormat)
1811 if (Kind == InvalidFormat) {
1812 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1813 << "format" << Attr.getParameterName()->getName();
1817 // checks for the 2nd argument
1818 Expr *IdxExpr = Attr.getArg(0);
1819 llvm::APSInt Idx(32);
1820 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1821 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1822 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1823 << "format" << 2 << IdxExpr->getSourceRange();
1827 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1828 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1829 << "format" << 2 << IdxExpr->getSourceRange();
1833 // FIXME: Do we need to bounds check?
1834 unsigned ArgIdx = Idx.getZExtValue() - 1;
1836 if (HasImplicitThisParam) {
1838 S.Diag(Attr.getLoc(),
1839 diag::err_format_attribute_implicit_this_format_string)
1840 << IdxExpr->getSourceRange();
1846 // make sure the format string is really a string
1847 QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1849 if (Kind == CFStringFormat) {
1850 if (!isCFStringType(Ty, S.Context)) {
1851 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1852 << "a CFString" << IdxExpr->getSourceRange();
1855 } else if (Kind == NSStringFormat) {
1856 // FIXME: do we need to check if the type is NSString*? What are the
1858 if (!isNSStringType(Ty, S.Context)) {
1859 // FIXME: Should highlight the actual expression that has the wrong type.
1860 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1861 << "an NSString" << IdxExpr->getSourceRange();
1864 } else if (!Ty->isPointerType() ||
1865 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
1866 // FIXME: Should highlight the actual expression that has the wrong type.
1867 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1868 << "a string type" << IdxExpr->getSourceRange();
1872 // check the 3rd argument
1873 Expr *FirstArgExpr = Attr.getArg(1);
1874 llvm::APSInt FirstArg(32);
1875 if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
1876 !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
1877 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1878 << "format" << 3 << FirstArgExpr->getSourceRange();
1882 // check if the function is variadic if the 3rd argument non-zero
1883 if (FirstArg != 0) {
1884 if (isFunctionOrMethodVariadic(d)) {
1885 ++NumArgs; // +1 for ...
1887 S.Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
1892 // strftime requires FirstArg to be 0 because it doesn't read from any
1893 // variable the input is just the current time + the format string.
1894 if (Kind == StrftimeFormat) {
1895 if (FirstArg != 0) {
1896 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
1897 << FirstArgExpr->getSourceRange();
1900 // if 0 it disables parameter checking (to use with e.g. va_list)
1901 } else if (FirstArg != 0 && FirstArg != NumArgs) {
1902 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1903 << "format" << 3 << FirstArgExpr->getSourceRange();
1907 d->addAttr(::new (S.Context) FormatAttr(Attr.getLoc(), S.Context, Format,
1909 FirstArg.getZExtValue()));
1912 static void HandleTransparentUnionAttr(Decl *d, const AttributeList &Attr,
1914 // check the attribute arguments.
1915 if (Attr.getNumArgs() != 0) {
1916 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1920 // Try to find the underlying union declaration.
1922 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(d);
1923 if (TD && TD->getUnderlyingType()->isUnionType())
1924 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
1926 RD = dyn_cast<RecordDecl>(d);
1928 if (!RD || !RD->isUnion()) {
1929 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1930 << Attr.getName() << ExpectedUnion;
1934 if (!RD->isDefinition()) {
1935 S.Diag(Attr.getLoc(),
1936 diag::warn_transparent_union_attribute_not_definition);
1940 RecordDecl::field_iterator Field = RD->field_begin(),
1941 FieldEnd = RD->field_end();
1942 if (Field == FieldEnd) {
1943 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
1947 FieldDecl *FirstField = *Field;
1948 QualType FirstType = FirstField->getType();
1949 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
1950 S.Diag(FirstField->getLocation(),
1951 diag::warn_transparent_union_attribute_floating)
1952 << FirstType->isVectorType() << FirstType;
1956 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
1957 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
1958 for (; Field != FieldEnd; ++Field) {
1959 QualType FieldType = Field->getType();
1960 if (S.Context.getTypeSize(FieldType) != FirstSize ||
1961 S.Context.getTypeAlign(FieldType) != FirstAlign) {
1962 // Warn if we drop the attribute.
1963 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
1964 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
1965 : S.Context.getTypeAlign(FieldType);
1966 S.Diag(Field->getLocation(),
1967 diag::warn_transparent_union_attribute_field_size_align)
1968 << isSize << Field->getDeclName() << FieldBits;
1969 unsigned FirstBits = isSize? FirstSize : FirstAlign;
1970 S.Diag(FirstField->getLocation(),
1971 diag::note_transparent_union_first_field_size_align)
1972 << isSize << FirstBits;
1977 RD->addAttr(::new (S.Context) TransparentUnionAttr(Attr.getLoc(), S.Context));
1980 static void HandleAnnotateAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1981 // check the attribute arguments.
1982 if (Attr.getNumArgs() != 1) {
1983 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1986 Expr *ArgExpr = Attr.getArg(0);
1987 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1989 // Make sure that there is a string literal as the annotation's single
1992 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
1995 d->addAttr(::new (S.Context) AnnotateAttr(Attr.getLoc(), S.Context,
1999 static void HandleAlignedAttr(Decl *D, const AttributeList &Attr, Sema &S) {
2000 // check the attribute arguments.
2001 if (Attr.getNumArgs() > 1) {
2002 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2006 //FIXME: The C++0x version of this attribute has more limited applicabilty
2007 // than GNU's, and should error out when it is used to specify a
2008 // weaker alignment, rather than being silently ignored.
2010 if (Attr.getNumArgs() == 0) {
2011 D->addAttr(::new (S.Context) AlignedAttr(Attr.getLoc(), S.Context, true, 0));
2015 S.AddAlignedAttr(Attr.getLoc(), D, Attr.getArg(0));
2018 void Sema::AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E) {
2019 if (E->isTypeDependent() || E->isValueDependent()) {
2020 // Save dependent expressions in the AST to be instantiated.
2021 D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, true, E));
2025 // FIXME: Cache the number on the Attr object?
2026 llvm::APSInt Alignment(32);
2027 if (!E->isIntegerConstantExpr(Alignment, Context)) {
2028 Diag(AttrLoc, diag::err_attribute_argument_not_int)
2029 << "aligned" << E->getSourceRange();
2032 if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
2033 Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
2034 << E->getSourceRange();
2038 D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, true, E));
2041 void Sema::AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *TS) {
2042 // FIXME: Cache the number on the Attr object if non-dependent?
2043 // FIXME: Perform checking of type validity
2044 D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, false, TS));
2048 /// HandleModeAttr - This attribute modifies the width of a decl with primitive
2051 /// Despite what would be logical, the mode attribute is a decl attribute, not a
2052 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
2053 /// HImode, not an intermediate pointer.
2054 static void HandleModeAttr(Decl *D, const AttributeList &Attr, Sema &S) {
2055 // This attribute isn't documented, but glibc uses it. It changes
2056 // the width of an int or unsigned int to the specified size.
2058 // Check that there aren't any arguments
2059 if (Attr.getNumArgs() != 0) {
2060 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2064 IdentifierInfo *Name = Attr.getParameterName();
2066 S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
2070 llvm::StringRef Str = Attr.getParameterName()->getName();
2072 // Normalize the attribute name, __foo__ becomes foo.
2073 if (Str.startswith("__") && Str.endswith("__"))
2074 Str = Str.substr(2, Str.size() - 4);
2076 unsigned DestWidth = 0;
2077 bool IntegerMode = true;
2078 bool ComplexMode = false;
2079 switch (Str.size()) {
2082 case 'Q': DestWidth = 8; break;
2083 case 'H': DestWidth = 16; break;
2084 case 'S': DestWidth = 32; break;
2085 case 'D': DestWidth = 64; break;
2086 case 'X': DestWidth = 96; break;
2087 case 'T': DestWidth = 128; break;
2089 if (Str[1] == 'F') {
2090 IntegerMode = false;
2091 } else if (Str[1] == 'C') {
2092 IntegerMode = false;
2094 } else if (Str[1] != 'I') {
2099 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
2100 // pointer on PIC16 and other embedded platforms.
2102 DestWidth = S.Context.Target.getPointerWidth(0);
2103 else if (Str == "byte")
2104 DestWidth = S.Context.Target.getCharWidth();
2107 if (Str == "pointer")
2108 DestWidth = S.Context.Target.getPointerWidth(0);
2113 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
2114 OldTy = TD->getUnderlyingType();
2115 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
2116 OldTy = VD->getType();
2118 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
2119 << "mode" << SourceRange(Attr.getLoc(), Attr.getLoc());
2123 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
2124 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
2125 else if (IntegerMode) {
2126 if (!OldTy->isIntegralOrEnumerationType())
2127 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2128 } else if (ComplexMode) {
2129 if (!OldTy->isComplexType())
2130 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2132 if (!OldTy->isFloatingType())
2133 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
2136 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
2137 // and friends, at least with glibc.
2138 // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
2139 // width on unusual platforms.
2140 // FIXME: Make sure floating-point mappings are accurate
2141 // FIXME: Support XF and TF types
2143 switch (DestWidth) {
2145 S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
2148 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2152 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2155 if (OldTy->isSignedIntegerType())
2156 NewTy = S.Context.SignedCharTy;
2158 NewTy = S.Context.UnsignedCharTy;
2162 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2165 if (OldTy->isSignedIntegerType())
2166 NewTy = S.Context.ShortTy;
2168 NewTy = S.Context.UnsignedShortTy;
2172 NewTy = S.Context.FloatTy;
2173 else if (OldTy->isSignedIntegerType())
2174 NewTy = S.Context.IntTy;
2176 NewTy = S.Context.UnsignedIntTy;
2180 NewTy = S.Context.DoubleTy;
2181 else if (OldTy->isSignedIntegerType())
2182 if (S.Context.Target.getLongWidth() == 64)
2183 NewTy = S.Context.LongTy;
2185 NewTy = S.Context.LongLongTy;
2187 if (S.Context.Target.getLongWidth() == 64)
2188 NewTy = S.Context.UnsignedLongTy;
2190 NewTy = S.Context.UnsignedLongLongTy;
2193 NewTy = S.Context.LongDoubleTy;
2197 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2200 if (OldTy->isSignedIntegerType())
2201 NewTy = S.Context.Int128Ty;
2203 NewTy = S.Context.UnsignedInt128Ty;
2208 NewTy = S.Context.getComplexType(NewTy);
2211 // Install the new type.
2212 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2213 // FIXME: preserve existing source info.
2214 TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
2216 cast<ValueDecl>(D)->setType(NewTy);
2219 static void HandleNoDebugAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2220 // check the attribute arguments.
2221 if (Attr.getNumArgs() > 0) {
2222 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2226 if (!isFunctionOrMethod(d)) {
2227 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2228 << Attr.getName() << ExpectedFunction;
2232 d->addAttr(::new (S.Context) NoDebugAttr(Attr.getLoc(), S.Context));
2235 static void HandleNoInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2236 // check the attribute arguments.
2237 if (Attr.getNumArgs() != 0) {
2238 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2242 if (!isa<FunctionDecl>(d)) {
2243 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2244 << Attr.getName() << ExpectedFunction;
2248 d->addAttr(::new (S.Context) NoInlineAttr(Attr.getLoc(), S.Context));
2251 static void HandleNoInstrumentFunctionAttr(Decl *d, const AttributeList &Attr,
2253 // check the attribute arguments.
2254 if (Attr.getNumArgs() != 0) {
2255 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2259 if (!isa<FunctionDecl>(d)) {
2260 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2261 << Attr.getName() << ExpectedFunction;
2265 d->addAttr(::new (S.Context) NoInstrumentFunctionAttr(Attr.getLoc(),
2269 static void HandleConstantAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2270 if (S.LangOpts.CUDA) {
2271 // check the attribute arguments.
2272 if (Attr.hasParameterOrArguments()) {
2273 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2277 if (!isa<VarDecl>(d)) {
2278 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2279 << Attr.getName() << ExpectedVariable;
2283 d->addAttr(::new (S.Context) CUDAConstantAttr(Attr.getLoc(), S.Context));
2285 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
2289 static void HandleDeviceAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2290 if (S.LangOpts.CUDA) {
2291 // check the attribute arguments.
2292 if (Attr.getNumArgs() != 0) {
2293 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2297 if (!isa<FunctionDecl>(d) && !isa<VarDecl>(d)) {
2298 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2299 << Attr.getName() << ExpectedVariableOrFunction;
2303 d->addAttr(::new (S.Context) CUDADeviceAttr(Attr.getLoc(), S.Context));
2305 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
2309 static void HandleGlobalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2310 if (S.LangOpts.CUDA) {
2311 // check the attribute arguments.
2312 if (Attr.getNumArgs() != 0) {
2313 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2317 if (!isa<FunctionDecl>(d)) {
2318 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2319 << Attr.getName() << ExpectedFunction;
2323 FunctionDecl *FD = cast<FunctionDecl>(d);
2324 if (!FD->getResultType()->isVoidType()) {
2325 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
2326 if (FunctionTypeLoc* FTL = dyn_cast<FunctionTypeLoc>(&TL)) {
2327 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
2329 << FixItHint::CreateReplacement(FTL->getResultLoc().getSourceRange(),
2332 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
2338 d->addAttr(::new (S.Context) CUDAGlobalAttr(Attr.getLoc(), S.Context));
2340 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
2344 static void HandleHostAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2345 if (S.LangOpts.CUDA) {
2346 // check the attribute arguments.
2347 if (Attr.getNumArgs() != 0) {
2348 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2352 if (!isa<FunctionDecl>(d)) {
2353 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2354 << Attr.getName() << ExpectedFunction;
2358 d->addAttr(::new (S.Context) CUDAHostAttr(Attr.getLoc(), S.Context));
2360 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
2364 static void HandleSharedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2365 if (S.LangOpts.CUDA) {
2366 // check the attribute arguments.
2367 if (Attr.getNumArgs() != 0) {
2368 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2372 if (!isa<VarDecl>(d)) {
2373 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2374 << Attr.getName() << ExpectedVariable;
2378 d->addAttr(::new (S.Context) CUDASharedAttr(Attr.getLoc(), S.Context));
2380 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
2384 static void HandleGNUInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2385 // check the attribute arguments.
2386 if (Attr.getNumArgs() != 0) {
2387 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2391 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2393 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2394 << Attr.getName() << ExpectedFunction;
2398 if (!Fn->isInlineSpecified()) {
2399 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
2403 d->addAttr(::new (S.Context) GNUInlineAttr(Attr.getLoc(), S.Context));
2406 static void HandleCallConvAttr(Decl *d, const AttributeList &attr, Sema &S) {
2407 if (hasDeclarator(d)) return;
2409 // Diagnostic is emitted elsewhere: here we store the (valid) attr
2410 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
2412 if (S.CheckCallingConvAttr(attr, CC))
2415 if (!isa<ObjCMethodDecl>(d)) {
2416 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2417 << attr.getName() << ExpectedFunctionOrMethod;
2421 switch (attr.getKind()) {
2422 case AttributeList::AT_fastcall:
2423 d->addAttr(::new (S.Context) FastCallAttr(attr.getLoc(), S.Context));
2425 case AttributeList::AT_stdcall:
2426 d->addAttr(::new (S.Context) StdCallAttr(attr.getLoc(), S.Context));
2428 case AttributeList::AT_thiscall:
2429 d->addAttr(::new (S.Context) ThisCallAttr(attr.getLoc(), S.Context));
2431 case AttributeList::AT_cdecl:
2432 d->addAttr(::new (S.Context) CDeclAttr(attr.getLoc(), S.Context));
2434 case AttributeList::AT_pascal:
2435 d->addAttr(::new (S.Context) PascalAttr(attr.getLoc(), S.Context));
2437 case AttributeList::AT_pcs: {
2438 Expr *Arg = attr.getArg(0);
2439 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2440 if (Str == 0 || Str->isWide()) {
2441 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
2447 llvm::StringRef StrRef = Str->getString();
2448 PcsAttr::PCSType PCS;
2449 if (StrRef == "aapcs")
2450 PCS = PcsAttr::AAPCS;
2451 else if (StrRef == "aapcs-vfp")
2452 PCS = PcsAttr::AAPCS_VFP;
2454 S.Diag(attr.getLoc(), diag::err_invalid_pcs);
2459 d->addAttr(::new (S.Context) PcsAttr(attr.getLoc(), S.Context, PCS));
2462 llvm_unreachable("unexpected attribute kind");
2467 static void HandleOpenCLKernelAttr(Decl *d, const AttributeList &Attr, Sema &S){
2468 assert(Attr.isInvalid() == false);
2469 d->addAttr(::new (S.Context) OpenCLKernelAttr(Attr.getLoc(), S.Context));
2472 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC) {
2473 if (attr.isInvalid())
2476 if ((attr.getNumArgs() != 0 &&
2477 !(attr.getKind() == AttributeList::AT_pcs && attr.getNumArgs() == 1)) ||
2478 attr.getParameterName()) {
2479 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2484 // TODO: diagnose uses of these conventions on the wrong target. Or, better
2485 // move to TargetAttributesSema one day.
2486 switch (attr.getKind()) {
2487 case AttributeList::AT_cdecl: CC = CC_C; break;
2488 case AttributeList::AT_fastcall: CC = CC_X86FastCall; break;
2489 case AttributeList::AT_stdcall: CC = CC_X86StdCall; break;
2490 case AttributeList::AT_thiscall: CC = CC_X86ThisCall; break;
2491 case AttributeList::AT_pascal: CC = CC_X86Pascal; break;
2492 case AttributeList::AT_pcs: {
2493 Expr *Arg = attr.getArg(0);
2494 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2495 if (Str == 0 || Str->isWide()) {
2496 Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
2502 llvm::StringRef StrRef = Str->getString();
2503 if (StrRef == "aapcs") {
2506 } else if (StrRef == "aapcs-vfp") {
2512 default: llvm_unreachable("unexpected attribute kind"); return true;
2518 static void HandleRegparmAttr(Decl *d, const AttributeList &attr, Sema &S) {
2519 if (hasDeclarator(d)) return;
2522 if (S.CheckRegparmAttr(attr, numParams))
2525 if (!isa<ObjCMethodDecl>(d)) {
2526 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2527 << attr.getName() << ExpectedFunctionOrMethod;
2531 d->addAttr(::new (S.Context) RegparmAttr(attr.getLoc(), S.Context, numParams));
2534 /// Checks a regparm attribute, returning true if it is ill-formed and
2535 /// otherwise setting numParams to the appropriate value.
2536 bool Sema::CheckRegparmAttr(const AttributeList &attr, unsigned &numParams) {
2537 if (attr.isInvalid())
2540 if (attr.getNumArgs() != 1) {
2541 Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2546 Expr *NumParamsExpr = attr.getArg(0);
2547 llvm::APSInt NumParams(32);
2548 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
2549 !NumParamsExpr->isIntegerConstantExpr(NumParams, Context)) {
2550 Diag(attr.getLoc(), diag::err_attribute_argument_not_int)
2551 << "regparm" << NumParamsExpr->getSourceRange();
2556 if (Context.Target.getRegParmMax() == 0) {
2557 Diag(attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
2558 << NumParamsExpr->getSourceRange();
2563 numParams = NumParams.getZExtValue();
2564 if (numParams > Context.Target.getRegParmMax()) {
2565 Diag(attr.getLoc(), diag::err_attribute_regparm_invalid_number)
2566 << Context.Target.getRegParmMax() << NumParamsExpr->getSourceRange();
2574 static void HandleLaunchBoundsAttr(Decl *d, const AttributeList &Attr, Sema &S){
2575 if (S.LangOpts.CUDA) {
2576 // check the attribute arguments.
2577 if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
2578 // FIXME: 0 is not okay.
2579 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
2583 if (!isFunctionOrMethod(d)) {
2584 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2585 << Attr.getName() << ExpectedFunctionOrMethod;
2589 Expr *MaxThreadsExpr = Attr.getArg(0);
2590 llvm::APSInt MaxThreads(32);
2591 if (MaxThreadsExpr->isTypeDependent() ||
2592 MaxThreadsExpr->isValueDependent() ||
2593 !MaxThreadsExpr->isIntegerConstantExpr(MaxThreads, S.Context)) {
2594 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2595 << "launch_bounds" << 1 << MaxThreadsExpr->getSourceRange();
2599 llvm::APSInt MinBlocks(32);
2600 if (Attr.getNumArgs() > 1) {
2601 Expr *MinBlocksExpr = Attr.getArg(1);
2602 if (MinBlocksExpr->isTypeDependent() ||
2603 MinBlocksExpr->isValueDependent() ||
2604 !MinBlocksExpr->isIntegerConstantExpr(MinBlocks, S.Context)) {
2605 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
2606 << "launch_bounds" << 2 << MinBlocksExpr->getSourceRange();
2611 d->addAttr(::new (S.Context) CUDALaunchBoundsAttr(Attr.getLoc(), S.Context,
2612 MaxThreads.getZExtValue(),
2613 MinBlocks.getZExtValue()));
2615 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "launch_bounds";
2619 //===----------------------------------------------------------------------===//
2620 // Checker-specific attribute handlers.
2621 //===----------------------------------------------------------------------===//
2623 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
2624 return type->isObjCObjectPointerType() || S.Context.isObjCNSObjectType(type);
2626 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
2627 return type->isPointerType() || isValidSubjectOfNSAttribute(S, type);
2630 static void HandleNSConsumedAttr(Decl *d, const AttributeList &attr, Sema &S) {
2631 ParmVarDecl *param = dyn_cast<ParmVarDecl>(d);
2633 S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
2634 << SourceRange(attr.getLoc()) << attr.getName() << ExpectedParameter;
2639 if (attr.getKind() == AttributeList::AT_ns_consumed) {
2640 typeOK = isValidSubjectOfNSAttribute(S, param->getType());
2643 typeOK = isValidSubjectOfCFAttribute(S, param->getType());
2648 S.Diag(d->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
2649 << SourceRange(attr.getLoc()) << attr.getName() << cf;
2654 param->addAttr(::new (S.Context) CFConsumedAttr(attr.getLoc(), S.Context));
2656 param->addAttr(::new (S.Context) NSConsumedAttr(attr.getLoc(), S.Context));
2659 static void HandleNSConsumesSelfAttr(Decl *d, const AttributeList &attr,
2661 if (!isa<ObjCMethodDecl>(d)) {
2662 S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
2663 << SourceRange(attr.getLoc()) << attr.getName() << ExpectedMethod;
2667 d->addAttr(::new (S.Context) NSConsumesSelfAttr(attr.getLoc(), S.Context));
2670 static void HandleNSReturnsRetainedAttr(Decl *d, const AttributeList &attr,
2673 QualType returnType;
2675 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
2676 returnType = MD->getResultType();
2677 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d))
2678 returnType = FD->getResultType();
2680 S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
2681 << SourceRange(attr.getLoc()) << attr.getName()
2682 << ExpectedFunctionOrMethod;
2688 switch (attr.getKind()) {
2689 default: llvm_unreachable("invalid ownership attribute"); return;
2690 case AttributeList::AT_ns_returns_autoreleased:
2691 case AttributeList::AT_ns_returns_retained:
2692 case AttributeList::AT_ns_returns_not_retained:
2693 typeOK = isValidSubjectOfNSAttribute(S, returnType);
2697 case AttributeList::AT_cf_returns_retained:
2698 case AttributeList::AT_cf_returns_not_retained:
2699 typeOK = isValidSubjectOfCFAttribute(S, returnType);
2705 S.Diag(d->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
2706 << SourceRange(attr.getLoc())
2707 << attr.getName() << isa<ObjCMethodDecl>(d) << cf;
2711 switch (attr.getKind()) {
2713 assert(0 && "invalid ownership attribute");
2715 case AttributeList::AT_ns_returns_autoreleased:
2716 d->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(attr.getLoc(),
2719 case AttributeList::AT_cf_returns_not_retained:
2720 d->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(attr.getLoc(),
2723 case AttributeList::AT_ns_returns_not_retained:
2724 d->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(attr.getLoc(),
2727 case AttributeList::AT_cf_returns_retained:
2728 d->addAttr(::new (S.Context) CFReturnsRetainedAttr(attr.getLoc(),
2731 case AttributeList::AT_ns_returns_retained:
2732 d->addAttr(::new (S.Context) NSReturnsRetainedAttr(attr.getLoc(),
2738 static bool isKnownDeclSpecAttr(const AttributeList &Attr) {
2739 return Attr.getKind() == AttributeList::AT_dllimport ||
2740 Attr.getKind() == AttributeList::AT_dllexport ||
2741 Attr.getKind() == AttributeList::AT_uuid;
2744 //===----------------------------------------------------------------------===//
2745 // Microsoft specific attribute handlers.
2746 //===----------------------------------------------------------------------===//
2748 static void HandleUuidAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2749 if (S.LangOpts.Microsoft || S.LangOpts.Borland) {
2750 // check the attribute arguments.
2751 if (Attr.getNumArgs() != 1) {
2752 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2755 Expr *Arg = Attr.getArg(0);
2756 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
2757 if (Str == 0 || Str->isWide()) {
2758 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
2763 llvm::StringRef StrRef = Str->getString();
2765 bool IsCurly = StrRef.size() > 1 && StrRef.front() == '{' &&
2766 StrRef.back() == '}';
2768 // Validate GUID length.
2769 if (IsCurly && StrRef.size() != 38) {
2770 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
2773 if (!IsCurly && StrRef.size() != 36) {
2774 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
2778 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
2779 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"
2780 llvm::StringRef::iterator I = StrRef.begin();
2781 if (IsCurly) // Skip the optional '{'
2784 for (int i = 0; i < 36; ++i) {
2785 if (i == 8 || i == 13 || i == 18 || i == 23) {
2787 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
2790 } else if (!isxdigit(*I)) {
2791 S.Diag(Attr.getLoc(), diag::err_attribute_uuid_malformed_guid);
2797 d->addAttr(::new (S.Context) UuidAttr(Attr.getLoc(), S.Context,
2800 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "uuid";
2803 //===----------------------------------------------------------------------===//
2804 // Top Level Sema Entry Points
2805 //===----------------------------------------------------------------------===//
2807 static void ProcessNonInheritableDeclAttr(Scope *scope, Decl *D,
2808 const AttributeList &Attr, Sema &S) {
2809 switch (Attr.getKind()) {
2810 case AttributeList::AT_device: HandleDeviceAttr (D, Attr, S); break;
2811 case AttributeList::AT_host: HandleHostAttr (D, Attr, S); break;
2812 case AttributeList::AT_overloadable:HandleOverloadableAttr(D, Attr, S); break;
2818 static void ProcessInheritableDeclAttr(Scope *scope, Decl *D,
2819 const AttributeList &Attr, Sema &S) {
2820 switch (Attr.getKind()) {
2821 case AttributeList::AT_IBAction: HandleIBAction(D, Attr, S); break;
2822 case AttributeList::AT_IBOutlet: HandleIBOutlet(D, Attr, S); break;
2823 case AttributeList::AT_IBOutletCollection:
2824 HandleIBOutletCollection(D, Attr, S); break;
2825 case AttributeList::AT_address_space:
2826 case AttributeList::AT_opencl_image_access:
2827 case AttributeList::AT_objc_gc:
2828 case AttributeList::AT_vector_size:
2829 case AttributeList::AT_neon_vector_type:
2830 case AttributeList::AT_neon_polyvector_type:
2831 // Ignore these, these are type attributes, handled by
2832 // ProcessTypeAttributes.
2834 case AttributeList::AT_device:
2835 case AttributeList::AT_host:
2836 case AttributeList::AT_overloadable:
2837 // Ignore, this is a non-inheritable attribute, handled
2838 // by ProcessNonInheritableDeclAttr.
2840 case AttributeList::AT_alias: HandleAliasAttr (D, Attr, S); break;
2841 case AttributeList::AT_aligned: HandleAlignedAttr (D, Attr, S); break;
2842 case AttributeList::AT_always_inline:
2843 HandleAlwaysInlineAttr (D, Attr, S); break;
2844 case AttributeList::AT_analyzer_noreturn:
2845 HandleAnalyzerNoReturnAttr (D, Attr, S); break;
2846 case AttributeList::AT_annotate: HandleAnnotateAttr (D, Attr, S); break;
2847 case AttributeList::AT_availability:HandleAvailabilityAttr(D, Attr, S); break;
2848 case AttributeList::AT_carries_dependency:
2849 HandleDependencyAttr (D, Attr, S); break;
2850 case AttributeList::AT_common: HandleCommonAttr (D, Attr, S); break;
2851 case AttributeList::AT_constant: HandleConstantAttr (D, Attr, S); break;
2852 case AttributeList::AT_constructor: HandleConstructorAttr (D, Attr, S); break;
2853 case AttributeList::AT_deprecated: HandleDeprecatedAttr (D, Attr, S); break;
2854 case AttributeList::AT_destructor: HandleDestructorAttr (D, Attr, S); break;
2855 case AttributeList::AT_ext_vector_type:
2856 HandleExtVectorTypeAttr(scope, D, Attr, S);
2858 case AttributeList::AT_format: HandleFormatAttr (D, Attr, S); break;
2859 case AttributeList::AT_format_arg: HandleFormatArgAttr (D, Attr, S); break;
2860 case AttributeList::AT_global: HandleGlobalAttr (D, Attr, S); break;
2861 case AttributeList::AT_gnu_inline: HandleGNUInlineAttr (D, Attr, S); break;
2862 case AttributeList::AT_launch_bounds:
2863 HandleLaunchBoundsAttr(D, Attr, S);
2865 case AttributeList::AT_mode: HandleModeAttr (D, Attr, S); break;
2866 case AttributeList::AT_malloc: HandleMallocAttr (D, Attr, S); break;
2867 case AttributeList::AT_may_alias: HandleMayAliasAttr (D, Attr, S); break;
2868 case AttributeList::AT_nocommon: HandleNoCommonAttr (D, Attr, S); break;
2869 case AttributeList::AT_nonnull: HandleNonNullAttr (D, Attr, S); break;
2870 case AttributeList::AT_ownership_returns:
2871 case AttributeList::AT_ownership_takes:
2872 case AttributeList::AT_ownership_holds:
2873 HandleOwnershipAttr (D, Attr, S); break;
2874 case AttributeList::AT_naked: HandleNakedAttr (D, Attr, S); break;
2875 case AttributeList::AT_noreturn: HandleNoReturnAttr (D, Attr, S); break;
2876 case AttributeList::AT_nothrow: HandleNothrowAttr (D, Attr, S); break;
2877 case AttributeList::AT_shared: HandleSharedAttr (D, Attr, S); break;
2878 case AttributeList::AT_vecreturn: HandleVecReturnAttr (D, Attr, S); break;
2880 // Checker-specific.
2881 case AttributeList::AT_cf_consumed:
2882 case AttributeList::AT_ns_consumed: HandleNSConsumedAttr (D, Attr, S); break;
2883 case AttributeList::AT_ns_consumes_self:
2884 HandleNSConsumesSelfAttr(D, Attr, S); break;
2886 case AttributeList::AT_ns_returns_autoreleased:
2887 case AttributeList::AT_ns_returns_not_retained:
2888 case AttributeList::AT_cf_returns_not_retained:
2889 case AttributeList::AT_ns_returns_retained:
2890 case AttributeList::AT_cf_returns_retained:
2891 HandleNSReturnsRetainedAttr(D, Attr, S); break;
2893 case AttributeList::AT_reqd_wg_size:
2894 HandleReqdWorkGroupSize(D, Attr, S); break;
2896 case AttributeList::AT_init_priority:
2897 HandleInitPriorityAttr(D, Attr, S); break;
2899 case AttributeList::AT_packed: HandlePackedAttr (D, Attr, S); break;
2900 case AttributeList::AT_MsStruct: HandleMsStructAttr (D, Attr, S); break;
2901 case AttributeList::AT_section: HandleSectionAttr (D, Attr, S); break;
2902 case AttributeList::AT_unavailable: HandleUnavailableAttr (D, Attr, S); break;
2903 case AttributeList::AT_unused: HandleUnusedAttr (D, Attr, S); break;
2904 case AttributeList::AT_used: HandleUsedAttr (D, Attr, S); break;
2905 case AttributeList::AT_visibility: HandleVisibilityAttr (D, Attr, S); break;
2906 case AttributeList::AT_warn_unused_result: HandleWarnUnusedResult(D,Attr,S);
2908 case AttributeList::AT_weak: HandleWeakAttr (D, Attr, S); break;
2909 case AttributeList::AT_weakref: HandleWeakRefAttr (D, Attr, S); break;
2910 case AttributeList::AT_weak_import: HandleWeakImportAttr (D, Attr, S); break;
2911 case AttributeList::AT_transparent_union:
2912 HandleTransparentUnionAttr(D, Attr, S);
2914 case AttributeList::AT_objc_exception:
2915 HandleObjCExceptionAttr(D, Attr, S);
2917 case AttributeList::AT_objc_method_family:
2918 HandleObjCMethodFamilyAttr(D, Attr, S);
2920 case AttributeList::AT_nsobject: HandleObjCNSObject (D, Attr, S); break;
2921 case AttributeList::AT_blocks: HandleBlocksAttr (D, Attr, S); break;
2922 case AttributeList::AT_sentinel: HandleSentinelAttr (D, Attr, S); break;
2923 case AttributeList::AT_const: HandleConstAttr (D, Attr, S); break;
2924 case AttributeList::AT_pure: HandlePureAttr (D, Attr, S); break;
2925 case AttributeList::AT_cleanup: HandleCleanupAttr (D, Attr, S); break;
2926 case AttributeList::AT_nodebug: HandleNoDebugAttr (D, Attr, S); break;
2927 case AttributeList::AT_noinline: HandleNoInlineAttr (D, Attr, S); break;
2928 case AttributeList::AT_regparm: HandleRegparmAttr (D, Attr, S); break;
2929 case AttributeList::IgnoredAttribute:
2932 case AttributeList::AT_no_instrument_function: // Interacts with -pg.
2933 HandleNoInstrumentFunctionAttr(D, Attr, S);
2935 case AttributeList::AT_stdcall:
2936 case AttributeList::AT_cdecl:
2937 case AttributeList::AT_fastcall:
2938 case AttributeList::AT_thiscall:
2939 case AttributeList::AT_pascal:
2940 case AttributeList::AT_pcs:
2941 HandleCallConvAttr(D, Attr, S);
2943 case AttributeList::AT_opencl_kernel_function:
2944 HandleOpenCLKernelAttr(D, Attr, S);
2946 case AttributeList::AT_uuid:
2947 HandleUuidAttr(D, Attr, S);
2950 // Ask target about the attribute.
2951 const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
2952 if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
2953 S.Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored)
2959 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
2960 /// the attribute applies to decls. If the attribute is a type attribute, just
2961 /// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
2962 /// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
2963 static void ProcessDeclAttribute(Scope *scope, Decl *D,
2964 const AttributeList &Attr, Sema &S,
2965 bool NonInheritable, bool Inheritable) {
2966 if (Attr.isInvalid())
2969 if (Attr.isDeclspecAttribute() && !isKnownDeclSpecAttr(Attr))
2970 // FIXME: Try to deal with other __declspec attributes!
2974 ProcessNonInheritableDeclAttr(scope, D, Attr, S);
2977 ProcessInheritableDeclAttr(scope, D, Attr, S);
2980 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
2981 /// attribute list to the specified decl, ignoring any type attributes.
2982 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
2983 const AttributeList *AttrList,
2984 bool NonInheritable, bool Inheritable) {
2985 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
2986 ProcessDeclAttribute(S, D, *l, *this, NonInheritable, Inheritable);
2990 // static int a9 __attribute__((weakref));
2991 // but that looks really pointless. We reject it.
2992 if (Inheritable && D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
2993 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
2994 dyn_cast<NamedDecl>(D)->getNameAsString();
2999 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
3000 /// #pragma weak needs a non-definition decl and source may not have one
3001 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II) {
3002 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
3003 NamedDecl *NewD = 0;
3004 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3005 NewD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
3006 FD->getInnerLocStart(),
3007 FD->getLocation(), DeclarationName(II),
3008 FD->getType(), FD->getTypeSourceInfo());
3009 if (FD->getQualifier()) {
3010 FunctionDecl *NewFD = cast<FunctionDecl>(NewD);
3011 NewFD->setQualifierInfo(FD->getQualifierLoc());
3013 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
3014 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
3015 VD->getInnerLocStart(), VD->getLocation(), II,
3016 VD->getType(), VD->getTypeSourceInfo(),
3017 VD->getStorageClass(),
3018 VD->getStorageClassAsWritten());
3019 if (VD->getQualifier()) {
3020 VarDecl *NewVD = cast<VarDecl>(NewD);
3021 NewVD->setQualifierInfo(VD->getQualifierLoc());
3027 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak
3028 /// applied to it, possibly with an alias.
3029 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
3030 if (W.getUsed()) return; // only do this once
3032 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
3033 IdentifierInfo *NDId = ND->getIdentifier();
3034 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias());
3035 NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
3037 NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
3038 WeakTopLevelDecl.push_back(NewD);
3039 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
3040 // to insert Decl at TU scope, sorry.
3041 DeclContext *SavedContext = CurContext;
3042 CurContext = Context.getTranslationUnitDecl();
3043 PushOnScopeChains(NewD, S);
3044 CurContext = SavedContext;
3045 } else { // just add weak to existing
3046 ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
3050 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
3051 /// it, apply them to D. This is a bit tricky because PD can have attributes
3052 /// specified in many different places, and we need to find and apply them all.
3053 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD,
3054 bool NonInheritable, bool Inheritable) {
3055 // It's valid to "forward-declare" #pragma weak, in which case we
3057 if (Inheritable && !WeakUndeclaredIdentifiers.empty()) {
3058 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
3059 if (IdentifierInfo *Id = ND->getIdentifier()) {
3060 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
3061 = WeakUndeclaredIdentifiers.find(Id);
3062 if (I != WeakUndeclaredIdentifiers.end() && ND->hasLinkage()) {
3063 WeakInfo W = I->second;
3064 DeclApplyPragmaWeak(S, ND, W);
3065 WeakUndeclaredIdentifiers[Id] = W;
3071 // Apply decl attributes from the DeclSpec if present.
3072 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
3073 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
3075 // Walk the declarator structure, applying decl attributes that were in a type
3076 // position to the decl itself. This handles cases like:
3077 // int *__attr__(x)** D;
3078 // when X is a decl attribute.
3079 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
3080 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
3081 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
3083 // Finally, apply any attributes on the decl itself.
3084 if (const AttributeList *Attrs = PD.getAttributes())
3085 ProcessDeclAttributeList(S, D, Attrs, NonInheritable, Inheritable);
3088 // This duplicates a vector push_back but hides the need to know the
3089 // size of the type.
3090 void Sema::DelayedDiagnostics::add(const DelayedDiagnostic &diag) {
3091 assert(StackSize <= StackCapacity);
3093 // Grow the stack if necessary.
3094 if (StackSize == StackCapacity) {
3095 unsigned newCapacity = 2 * StackCapacity + 2;
3096 char *newBuffer = new char[newCapacity * sizeof(DelayedDiagnostic)];
3097 const char *oldBuffer = (const char*) Stack;
3100 memcpy(newBuffer, oldBuffer, StackCapacity * sizeof(DelayedDiagnostic));
3103 Stack = reinterpret_cast<sema::DelayedDiagnostic*>(newBuffer);
3104 StackCapacity = newCapacity;
3107 assert(StackSize < StackCapacity);
3108 new (&Stack[StackSize++]) DelayedDiagnostic(diag);
3111 void Sema::DelayedDiagnostics::popParsingDecl(Sema &S, ParsingDeclState state,
3113 DelayedDiagnostics &DD = S.DelayedDiagnostics;
3115 // Check the invariants.
3116 assert(DD.StackSize >= state.SavedStackSize);
3117 assert(state.SavedStackSize >= DD.ActiveStackBase);
3118 assert(DD.ParsingDepth > 0);
3120 // Drop the parsing depth.
3123 // If there are no active diagnostics, we're done.
3124 if (DD.StackSize == DD.ActiveStackBase)
3127 // We only want to actually emit delayed diagnostics when we
3128 // successfully parsed a decl.
3130 // We emit all the active diagnostics, not just those starting
3131 // from the saved state. The idea is this: we get one push for a
3132 // decl spec and another for each declarator; in a decl group like:
3133 // deprecated_typedef foo, *bar, baz();
3134 // only the declarator pops will be passed decls. This is correct;
3135 // we really do need to consider delayed diagnostics from the decl spec
3136 // for each of the different declarations.
3137 for (unsigned i = DD.ActiveStackBase, e = DD.StackSize; i != e; ++i) {
3138 DelayedDiagnostic &diag = DD.Stack[i];
3142 switch (diag.Kind) {
3143 case DelayedDiagnostic::Deprecation:
3144 S.HandleDelayedDeprecationCheck(diag, decl);
3147 case DelayedDiagnostic::Access:
3148 S.HandleDelayedAccessCheck(diag, decl);
3154 // Destroy all the delayed diagnostics we're about to pop off.
3155 for (unsigned i = state.SavedStackSize, e = DD.StackSize; i != e; ++i)
3156 DD.Stack[i].Destroy();
3158 DD.StackSize = state.SavedStackSize;
3161 static bool isDeclDeprecated(Decl *D) {
3163 if (D->isDeprecated())
3165 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
3169 void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
3171 if (isDeclDeprecated(Ctx))
3174 DD.Triggered = true;
3175 if (!DD.getDeprecationMessage().empty())
3176 Diag(DD.Loc, diag::warn_deprecated_message)
3177 << DD.getDeprecationDecl()->getDeclName()
3178 << DD.getDeprecationMessage();
3180 Diag(DD.Loc, diag::warn_deprecated)
3181 << DD.getDeprecationDecl()->getDeclName();
3184 void Sema::EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message,
3186 const ObjCInterfaceDecl *UnknownObjCClass) {
3187 // Delay if we're currently parsing a declaration.
3188 if (DelayedDiagnostics.shouldDelayDiagnostics()) {
3189 DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D, Message));
3193 // Otherwise, don't warn if our current context is deprecated.
3194 if (isDeclDeprecated(cast<Decl>(CurContext)))
3196 if (!Message.empty())
3197 Diag(Loc, diag::warn_deprecated_message) << D->getDeclName()
3200 if (!UnknownObjCClass)
3201 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
3203 Diag(Loc, diag::warn_deprecated_fwdclass_message) << D->getDeclName();
3204 Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);