Remove a fixme which was fixed in a previous commit.
[clang.git] / lib / Sema / SemaDeclAttr.cpp
blob3c4bd8ffc45a9ce42a73fe5e9b3f17b135ace88b
1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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;
25 using namespace sema;
27 //===----------------------------------------------------------------------===//
28 // Helper functions
29 //===----------------------------------------------------------------------===//
31 static const FunctionType *getFunctionType(const Decl *d,
32 bool blocksToo = true) {
33 QualType Ty;
34 if (const ValueDecl *decl = dyn_cast<ValueDecl>(d))
35 Ty = decl->getType();
36 else if (const FieldDecl *decl = dyn_cast<FieldDecl>(d))
37 Ty = decl->getType();
38 else if (const TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
39 Ty = decl->getUnderlyingType();
40 else
41 return 0;
43 if (Ty->isFunctionPointerType())
44 Ty = Ty->getAs<PointerType>()->getPointeeType();
45 else if (blocksToo && Ty->isBlockPointerType())
46 Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
48 return Ty->getAs<FunctionType>();
51 // FIXME: We should provide an abstraction around a method or function
52 // to provide the following bits of information.
54 /// isFunction - Return true if the given decl has function
55 /// type (function or function-typed variable).
56 static bool isFunction(const Decl *d) {
57 return getFunctionType(d, false) != NULL;
60 /// isFunctionOrMethod - Return true if the given decl has function
61 /// type (function or function-typed variable) or an Objective-C
62 /// method.
63 static bool isFunctionOrMethod(const Decl *d) {
64 return isFunction(d)|| isa<ObjCMethodDecl>(d);
67 /// isFunctionOrMethodOrBlock - Return true if the given decl has function
68 /// type (function or function-typed variable) or an Objective-C
69 /// method or a block.
70 static bool isFunctionOrMethodOrBlock(const Decl *d) {
71 if (isFunctionOrMethod(d))
72 return true;
73 // check for block is more involved.
74 if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
75 QualType Ty = V->getType();
76 return Ty->isBlockPointerType();
78 return isa<BlockDecl>(d);
81 /// hasFunctionProto - Return true if the given decl has a argument
82 /// information. This decl should have already passed
83 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
84 static bool hasFunctionProto(const Decl *d) {
85 if (const FunctionType *FnTy = getFunctionType(d))
86 return isa<FunctionProtoType>(FnTy);
87 else {
88 assert(isa<ObjCMethodDecl>(d) || isa<BlockDecl>(d));
89 return true;
93 /// getFunctionOrMethodNumArgs - Return number of function or method
94 /// arguments. It is an error to call this on a K&R function (use
95 /// hasFunctionProto first).
96 static unsigned getFunctionOrMethodNumArgs(const Decl *d) {
97 if (const FunctionType *FnTy = getFunctionType(d))
98 return cast<FunctionProtoType>(FnTy)->getNumArgs();
99 if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
100 return BD->getNumParams();
101 return cast<ObjCMethodDecl>(d)->param_size();
104 static QualType getFunctionOrMethodArgType(const Decl *d, unsigned Idx) {
105 if (const FunctionType *FnTy = getFunctionType(d))
106 return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
107 if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
108 return BD->getParamDecl(Idx)->getType();
110 return cast<ObjCMethodDecl>(d)->param_begin()[Idx]->getType();
113 static QualType getFunctionOrMethodResultType(const Decl *d) {
114 if (const FunctionType *FnTy = getFunctionType(d))
115 return cast<FunctionProtoType>(FnTy)->getResultType();
116 return cast<ObjCMethodDecl>(d)->getResultType();
119 static bool isFunctionOrMethodVariadic(const Decl *d) {
120 if (const FunctionType *FnTy = getFunctionType(d)) {
121 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
122 return proto->isVariadic();
123 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
124 return BD->isVariadic();
125 else {
126 return cast<ObjCMethodDecl>(d)->isVariadic();
130 static bool isInstanceMethod(const Decl *d) {
131 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(d))
132 return MethodDecl->isInstance();
133 return false;
136 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
137 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
138 if (!PT)
139 return false;
141 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
142 if (!Cls)
143 return false;
145 IdentifierInfo* ClsName = Cls->getIdentifier();
147 // FIXME: Should we walk the chain of classes?
148 return ClsName == &Ctx.Idents.get("NSString") ||
149 ClsName == &Ctx.Idents.get("NSMutableString");
152 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
153 const PointerType *PT = T->getAs<PointerType>();
154 if (!PT)
155 return false;
157 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
158 if (!RT)
159 return false;
161 const RecordDecl *RD = RT->getDecl();
162 if (RD->getTagKind() != TTK_Struct)
163 return false;
165 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
168 //===----------------------------------------------------------------------===//
169 // Attribute Implementations
170 //===----------------------------------------------------------------------===//
172 // FIXME: All this manual attribute parsing code is gross. At the
173 // least add some helper functions to check most argument patterns (#
174 // and types of args).
176 static void HandleExtVectorTypeAttr(Scope *scope, Decl *d,
177 const AttributeList &Attr, Sema &S) {
178 TypedefDecl *tDecl = dyn_cast<TypedefDecl>(d);
179 if (tDecl == 0) {
180 S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
181 return;
184 QualType curType = tDecl->getUnderlyingType();
186 Expr *sizeExpr;
188 // Special case where the argument is a template id.
189 if (Attr.getParameterName()) {
190 CXXScopeSpec SS;
191 UnqualifiedId id;
192 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
193 sizeExpr = S.ActOnIdExpression(scope, SS, id, false, false).takeAs<Expr>();
194 } else {
195 // check the attribute arguments.
196 if (Attr.getNumArgs() != 1) {
197 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
198 return;
200 sizeExpr = Attr.getArg(0);
203 // Instantiate/Install the vector type, and let Sema build the type for us.
204 // This will run the reguired checks.
205 QualType T = S.BuildExtVectorType(curType, sizeExpr, Attr.getLoc());
206 if (!T.isNull()) {
207 // FIXME: preserve the old source info.
208 tDecl->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(T));
210 // Remember this typedef decl, we will need it later for diagnostics.
211 S.ExtVectorDecls.push_back(tDecl);
215 static void HandlePackedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
216 // check the attribute arguments.
217 if (Attr.getNumArgs() > 0) {
218 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
219 return;
222 if (TagDecl *TD = dyn_cast<TagDecl>(d))
223 TD->addAttr(::new (S.Context) PackedAttr(Attr.getLoc(), S.Context));
224 else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
225 // If the alignment is less than or equal to 8 bits, the packed attribute
226 // has no effect.
227 if (!FD->getType()->isIncompleteType() &&
228 S.Context.getTypeAlign(FD->getType()) <= 8)
229 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
230 << Attr.getName() << FD->getType();
231 else
232 FD->addAttr(::new (S.Context) PackedAttr(Attr.getLoc(), S.Context));
233 } else
234 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
237 static void HandleIBAction(Decl *d, const AttributeList &Attr, Sema &S) {
238 // check the attribute arguments.
239 if (Attr.getNumArgs() > 0) {
240 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
241 return;
244 // The IBAction attributes only apply to instance methods.
245 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
246 if (MD->isInstanceMethod()) {
247 d->addAttr(::new (S.Context) IBActionAttr(Attr.getLoc(), S.Context));
248 return;
251 S.Diag(Attr.getLoc(), diag::err_attribute_ibaction) << Attr.getName();
254 static void HandleIBOutlet(Decl *d, const AttributeList &Attr, Sema &S) {
255 // check the attribute arguments.
256 if (Attr.getNumArgs() > 0) {
257 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
258 return;
261 // The IBOutlet attributes only apply to instance variables of
262 // Objective-C classes.
263 if (isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d)) {
264 d->addAttr(::new (S.Context) IBOutletAttr(Attr.getLoc(), S.Context));
265 return;
268 S.Diag(Attr.getLoc(), diag::err_attribute_iboutlet) << Attr.getName();
271 static void HandleIBOutletCollection(Decl *d, const AttributeList &Attr,
272 Sema &S) {
274 // The iboutletcollection attribute can have zero or one arguments.
275 if (Attr.getParameterName() && Attr.getNumArgs() > 0) {
276 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
277 return;
280 // The IBOutletCollection attributes only apply to instance variables of
281 // Objective-C classes.
282 if (!(isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d))) {
283 S.Diag(Attr.getLoc(), diag::err_attribute_iboutlet) << Attr.getName();
284 return;
286 if (const ValueDecl *VD = dyn_cast<ValueDecl>(d))
287 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
288 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_object_type)
289 << VD->getType() << 0;
290 return;
292 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(d))
293 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
294 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_object_type)
295 << PD->getType() << 1;
296 return;
299 IdentifierInfo *II = Attr.getParameterName();
300 if (!II)
301 II = &S.Context.Idents.get("id");
303 ParsedType TypeRep = S.getTypeName(*II, Attr.getLoc(),
304 S.getScopeForContext(d->getDeclContext()->getParent()));
305 if (!TypeRep) {
306 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
307 return;
309 QualType QT = TypeRep.get();
310 // Diagnose use of non-object type in iboutletcollection attribute.
311 // FIXME. Gnu attribute extension ignores use of builtin types in
312 // attributes. So, __attribute__((iboutletcollection(char))) will be
313 // treated as __attribute__((iboutletcollection())).
314 if (!QT->isObjCIdType() && !QT->isObjCClassType() &&
315 !QT->isObjCObjectType()) {
316 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
317 return;
319 d->addAttr(::new (S.Context) IBOutletCollectionAttr(Attr.getLoc(), S.Context,
320 QT));
323 static void HandleNonNullAttr(Decl *d, const AttributeList &Attr, Sema &S) {
324 // GCC ignores the nonnull attribute on K&R style function prototypes, so we
325 // ignore it as well
326 if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
327 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
328 << Attr.getName() << 0 /*function*/;
329 return;
332 // In C++ the implicit 'this' function parameter also counts, and they are
333 // counted from one.
334 bool HasImplicitThisParam = isInstanceMethod(d);
335 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
337 // The nonnull attribute only applies to pointers.
338 llvm::SmallVector<unsigned, 10> NonNullArgs;
340 for (AttributeList::arg_iterator I=Attr.arg_begin(),
341 E=Attr.arg_end(); I!=E; ++I) {
344 // The argument must be an integer constant expression.
345 Expr *Ex = *I;
346 llvm::APSInt ArgNum(32);
347 if (Ex->isTypeDependent() || Ex->isValueDependent() ||
348 !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
349 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
350 << "nonnull" << Ex->getSourceRange();
351 return;
354 unsigned x = (unsigned) ArgNum.getZExtValue();
356 if (x < 1 || x > NumArgs) {
357 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
358 << "nonnull" << I.getArgNum() << Ex->getSourceRange();
359 return;
362 --x;
363 if (HasImplicitThisParam) {
364 if (x == 0) {
365 S.Diag(Attr.getLoc(),
366 diag::err_attribute_invalid_implicit_this_argument)
367 << "nonnull" << Ex->getSourceRange();
368 return;
370 --x;
373 // Is the function argument a pointer type?
374 QualType T = getFunctionOrMethodArgType(d, x);
375 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
376 // FIXME: Should also highlight argument in decl.
377 S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
378 << "nonnull" << Ex->getSourceRange();
379 continue;
382 NonNullArgs.push_back(x);
385 // If no arguments were specified to __attribute__((nonnull)) then all pointer
386 // arguments have a nonnull attribute.
387 if (NonNullArgs.empty()) {
388 for (unsigned I = 0, E = getFunctionOrMethodNumArgs(d); I != E; ++I) {
389 QualType T = getFunctionOrMethodArgType(d, I);
390 if (T->isAnyPointerType() || T->isBlockPointerType())
391 NonNullArgs.push_back(I);
392 else if (const RecordType *UT = T->getAsUnionType()) {
393 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
394 RecordDecl *UD = UT->getDecl();
395 for (RecordDecl::field_iterator it = UD->field_begin(),
396 itend = UD->field_end(); it != itend; ++it) {
397 T = it->getType();
398 if (T->isAnyPointerType() || T->isBlockPointerType()) {
399 NonNullArgs.push_back(I);
400 break;
407 // No pointer arguments?
408 if (NonNullArgs.empty()) {
409 // Warn the trivial case only if attribute is not coming from a
410 // macro instantiation.
411 if (Attr.getLoc().isFileID())
412 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
413 return;
417 unsigned* start = &NonNullArgs[0];
418 unsigned size = NonNullArgs.size();
419 llvm::array_pod_sort(start, start + size);
420 d->addAttr(::new (S.Context) NonNullAttr(Attr.getLoc(), S.Context, start,
421 size));
424 static void HandleOwnershipAttr(Decl *d, const AttributeList &AL, Sema &S) {
425 // This attribute must be applied to a function declaration.
426 // The first argument to the attribute must be a string,
427 // the name of the resource, for example "malloc".
428 // The following arguments must be argument indexes, the arguments must be
429 // of integer type for Returns, otherwise of pointer type.
430 // The difference between Holds and Takes is that a pointer may still be used
431 // after being held. free() should be __attribute((ownership_takes)), whereas
432 // a list append function may well be __attribute((ownership_holds)).
434 if (!AL.getParameterName()) {
435 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_not_string)
436 << AL.getName()->getName() << 1;
437 return;
439 // Figure out our Kind, and check arguments while we're at it.
440 OwnershipAttr::OwnershipKind K;
441 switch (AL.getKind()) {
442 case AttributeList::AT_ownership_takes:
443 K = OwnershipAttr::Takes;
444 if (AL.getNumArgs() < 1) {
445 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
446 return;
448 break;
449 case AttributeList::AT_ownership_holds:
450 K = OwnershipAttr::Holds;
451 if (AL.getNumArgs() < 1) {
452 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
453 return;
455 break;
456 case AttributeList::AT_ownership_returns:
457 K = OwnershipAttr::Returns;
458 if (AL.getNumArgs() > 1) {
459 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
460 << AL.getNumArgs() + 1;
461 return;
463 break;
464 default:
465 // This should never happen given how we are called.
466 llvm_unreachable("Unknown ownership attribute");
469 if (!isFunction(d) || !hasFunctionProto(d)) {
470 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL.getName()
471 << 0 /*function*/;
472 return;
475 // In C++ the implicit 'this' function parameter also counts, and they are
476 // counted from one.
477 bool HasImplicitThisParam = isInstanceMethod(d);
478 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
480 llvm::StringRef Module = AL.getParameterName()->getName();
482 // Normalize the argument, __foo__ becomes foo.
483 if (Module.startswith("__") && Module.endswith("__"))
484 Module = Module.substr(2, Module.size() - 4);
486 llvm::SmallVector<unsigned, 10> OwnershipArgs;
488 for (AttributeList::arg_iterator I = AL.arg_begin(), E = AL.arg_end(); I != E;
489 ++I) {
491 Expr *IdxExpr = *I;
492 llvm::APSInt ArgNum(32);
493 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
494 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
495 S.Diag(AL.getLoc(), diag::err_attribute_argument_not_int)
496 << AL.getName()->getName() << IdxExpr->getSourceRange();
497 continue;
500 unsigned x = (unsigned) ArgNum.getZExtValue();
502 if (x > NumArgs || x < 1) {
503 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
504 << AL.getName()->getName() << x << IdxExpr->getSourceRange();
505 continue;
507 --x;
508 if (HasImplicitThisParam) {
509 if (x == 0) {
510 S.Diag(AL.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
511 << "ownership" << IdxExpr->getSourceRange();
512 return;
514 --x;
517 switch (K) {
518 case OwnershipAttr::Takes:
519 case OwnershipAttr::Holds: {
520 // Is the function argument a pointer type?
521 QualType T = getFunctionOrMethodArgType(d, x);
522 if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
523 // FIXME: Should also highlight argument in decl.
524 S.Diag(AL.getLoc(), diag::err_ownership_type)
525 << ((K==OwnershipAttr::Takes)?"ownership_takes":"ownership_holds")
526 << "pointer"
527 << IdxExpr->getSourceRange();
528 continue;
530 break;
532 case OwnershipAttr::Returns: {
533 if (AL.getNumArgs() > 1) {
534 // Is the function argument an integer type?
535 Expr *IdxExpr = AL.getArg(0);
536 llvm::APSInt ArgNum(32);
537 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent()
538 || !IdxExpr->isIntegerConstantExpr(ArgNum, S.Context)) {
539 S.Diag(AL.getLoc(), diag::err_ownership_type)
540 << "ownership_returns" << "integer"
541 << IdxExpr->getSourceRange();
542 return;
545 break;
547 default:
548 llvm_unreachable("Unknown ownership attribute");
549 } // switch
551 // Check we don't have a conflict with another ownership attribute.
552 for (specific_attr_iterator<OwnershipAttr>
553 i = d->specific_attr_begin<OwnershipAttr>(),
554 e = d->specific_attr_end<OwnershipAttr>();
555 i != e; ++i) {
556 if ((*i)->getOwnKind() != K) {
557 for (const unsigned *I = (*i)->args_begin(), *E = (*i)->args_end();
558 I!=E; ++I) {
559 if (x == *I) {
560 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
561 << AL.getName()->getName() << "ownership_*";
566 OwnershipArgs.push_back(x);
569 unsigned* start = OwnershipArgs.data();
570 unsigned size = OwnershipArgs.size();
571 llvm::array_pod_sort(start, start + size);
573 if (K != OwnershipAttr::Returns && OwnershipArgs.empty()) {
574 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << 2;
575 return;
578 d->addAttr(::new (S.Context) OwnershipAttr(AL.getLoc(), S.Context, K, Module,
579 start, size));
582 static bool isStaticVarOrStaticFunciton(Decl *D) {
583 if (VarDecl *VD = dyn_cast<VarDecl>(D))
584 return VD->getStorageClass() == SC_Static;
585 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
586 return FD->getStorageClass() == SC_Static;
587 return false;
590 static void HandleWeakRefAttr(Decl *d, const AttributeList &Attr, Sema &S) {
591 // Check the attribute arguments.
592 if (Attr.getNumArgs() > 1) {
593 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
594 return;
597 // gcc rejects
598 // class c {
599 // static int a __attribute__((weakref ("v2")));
600 // static int b() __attribute__((weakref ("f3")));
601 // };
602 // and ignores the attributes of
603 // void f(void) {
604 // static int a __attribute__((weakref ("v2")));
605 // }
606 // we reject them
607 const DeclContext *Ctx = d->getDeclContext()->getRedeclContext();
608 if (!Ctx->isFileContext()) {
609 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
610 dyn_cast<NamedDecl>(d)->getNameAsString();
611 return;
614 // The GCC manual says
616 // At present, a declaration to which `weakref' is attached can only
617 // be `static'.
619 // It also says
621 // Without a TARGET,
622 // given as an argument to `weakref' or to `alias', `weakref' is
623 // equivalent to `weak'.
625 // gcc 4.4.1 will accept
626 // int a7 __attribute__((weakref));
627 // as
628 // int a7 __attribute__((weak));
629 // This looks like a bug in gcc. We reject that for now. We should revisit
630 // it if this behaviour is actually used.
632 if (!isStaticVarOrStaticFunciton(d)) {
633 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_static) <<
634 dyn_cast<NamedDecl>(d)->getNameAsString();
635 return;
638 // GCC rejects
639 // static ((alias ("y"), weakref)).
640 // Should we? How to check that weakref is before or after alias?
642 if (Attr.getNumArgs() == 1) {
643 Expr *Arg = Attr.getArg(0);
644 Arg = Arg->IgnoreParenCasts();
645 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
647 if (Str == 0 || Str->isWide()) {
648 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
649 << "weakref" << 1;
650 return;
652 // GCC will accept anything as the argument of weakref. Should we
653 // check for an existing decl?
654 d->addAttr(::new (S.Context) AliasAttr(Attr.getLoc(), S.Context,
655 Str->getString()));
658 d->addAttr(::new (S.Context) WeakRefAttr(Attr.getLoc(), S.Context));
661 static void HandleAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
662 // check the attribute arguments.
663 if (Attr.getNumArgs() != 1) {
664 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
665 return;
668 Expr *Arg = Attr.getArg(0);
669 Arg = Arg->IgnoreParenCasts();
670 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
672 if (Str == 0 || Str->isWide()) {
673 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
674 << "alias" << 1;
675 return;
678 // FIXME: check if target symbol exists in current file
680 d->addAttr(::new (S.Context) AliasAttr(Attr.getLoc(), S.Context,
681 Str->getString()));
684 static void HandleNakedAttr(Decl *d, const AttributeList &Attr,
685 Sema &S) {
686 // Check the attribute arguments.
687 if (Attr.getNumArgs() != 0) {
688 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
689 return;
692 if (!isa<FunctionDecl>(d)) {
693 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
694 << Attr.getName() << 0 /*function*/;
695 return;
698 d->addAttr(::new (S.Context) NakedAttr(Attr.getLoc(), S.Context));
701 static void HandleAlwaysInlineAttr(Decl *d, const AttributeList &Attr,
702 Sema &S) {
703 // Check the attribute arguments.
704 if (Attr.getNumArgs() != 0) {
705 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
706 return;
709 if (!isa<FunctionDecl>(d)) {
710 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
711 << Attr.getName() << 0 /*function*/;
712 return;
715 d->addAttr(::new (S.Context) AlwaysInlineAttr(Attr.getLoc(), S.Context));
718 static void HandleMallocAttr(Decl *d, const AttributeList &Attr, Sema &S) {
719 // Check the attribute arguments.
720 if (Attr.getNumArgs() != 0) {
721 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
722 return;
725 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
726 QualType RetTy = FD->getResultType();
727 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
728 d->addAttr(::new (S.Context) MallocAttr(Attr.getLoc(), S.Context));
729 return;
733 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
736 static void HandleMayAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
737 // check the attribute arguments.
738 if (Attr.getNumArgs() != 0) {
739 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
740 return;
743 d->addAttr(::new (S.Context) MayAliasAttr(Attr.getLoc(), S.Context));
746 static void HandleNoCommonAttr(Decl *d, const AttributeList &Attr, Sema &S) {
747 assert(Attr.isInvalid() == false);
748 if (isa<VarDecl>(d))
749 d->addAttr(::new (S.Context) NoCommonAttr(Attr.getLoc(), S.Context));
750 else
751 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
752 << Attr.getName() << 12 /* variable */;
755 static void HandleCommonAttr(Decl *d, const AttributeList &Attr, Sema &S) {
756 assert(Attr.isInvalid() == false);
757 if (isa<VarDecl>(d))
758 d->addAttr(::new (S.Context) CommonAttr(Attr.getLoc(), S.Context));
759 else
760 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
761 << Attr.getName() << 12 /* variable */;
764 static void HandleNoReturnAttr(Decl *d, const AttributeList &Attr, Sema &S) {
765 /* Diagnostics (if any) was emitted by Sema::ProcessFnAttr(). */
766 assert(Attr.isInvalid() == false);
767 d->addAttr(::new (S.Context) NoReturnAttr(Attr.getLoc(), S.Context));
770 static void HandleAnalyzerNoReturnAttr(Decl *d, const AttributeList &Attr,
771 Sema &S) {
773 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
774 // because 'analyzer_noreturn' does not impact the type.
776 if (Attr.getNumArgs() != 0) {
777 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
778 return;
781 if (!isFunctionOrMethod(d) && !isa<BlockDecl>(d)) {
782 ValueDecl *VD = dyn_cast<ValueDecl>(d);
783 if (VD == 0 || (!VD->getType()->isBlockPointerType()
784 && !VD->getType()->isFunctionPointerType())) {
785 S.Diag(Attr.getLoc(),
786 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
787 : diag::warn_attribute_wrong_decl_type)
788 << Attr.getName() << 0 /*function*/;
789 return;
793 d->addAttr(::new (S.Context) AnalyzerNoReturnAttr(Attr.getLoc(), S.Context));
796 // PS3 PPU-specific.
797 static void HandleVecReturnAttr(Decl *d, const AttributeList &Attr,
798 Sema &S) {
800 Returning a Vector Class in Registers
802 According to the PPU ABI specifications, a class with a single member of
803 vector type is returned in memory when used as the return value of a function.
804 This results in inefficient code when implementing vector classes. To return
805 the value in a single vector register, add the vecreturn attribute to the
806 class definition. This attribute is also applicable to struct types.
808 Example:
810 struct Vector
812 __vector float xyzw;
813 } __attribute__((vecreturn));
815 Vector Add(Vector lhs, Vector rhs)
817 Vector result;
818 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
819 return result; // This will be returned in a register
822 if (!isa<RecordDecl>(d)) {
823 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
824 << Attr.getName() << 9 /*class*/;
825 return;
828 if (d->getAttr<VecReturnAttr>()) {
829 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
830 return;
833 RecordDecl *record = cast<RecordDecl>(d);
834 int count = 0;
836 if (!isa<CXXRecordDecl>(record)) {
837 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
838 return;
841 if (!cast<CXXRecordDecl>(record)->isPOD()) {
842 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
843 return;
846 for (RecordDecl::field_iterator iter = record->field_begin();
847 iter != record->field_end(); iter++) {
848 if ((count == 1) || !iter->getType()->isVectorType()) {
849 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
850 return;
852 count++;
855 d->addAttr(::new (S.Context) VecReturnAttr(Attr.getLoc(), S.Context));
858 static void HandleDependencyAttr(Decl *d, const AttributeList &Attr, Sema &S) {
859 if (!isFunctionOrMethod(d) && !isa<ParmVarDecl>(d)) {
860 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
861 << Attr.getName() << 8 /*function, method, or parameter*/;
862 return;
864 // FIXME: Actually store the attribute on the declaration
867 static void HandleUnusedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
868 // check the attribute arguments.
869 if (Attr.getNumArgs() != 0) {
870 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
871 return;
874 if (!isa<VarDecl>(d) && !isa<ObjCIvarDecl>(d) && !isFunctionOrMethod(d) &&
875 !isa<TypeDecl>(d)) {
876 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
877 << Attr.getName() << 2 /*variable and function*/;
878 return;
881 d->addAttr(::new (S.Context) UnusedAttr(Attr.getLoc(), S.Context));
884 static void HandleUsedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
885 // check the attribute arguments.
886 if (Attr.getNumArgs() != 0) {
887 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
888 return;
891 if (const VarDecl *VD = dyn_cast<VarDecl>(d)) {
892 if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
893 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
894 return;
896 } else if (!isFunctionOrMethod(d)) {
897 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
898 << Attr.getName() << 2 /*variable and function*/;
899 return;
902 d->addAttr(::new (S.Context) UsedAttr(Attr.getLoc(), S.Context));
905 static void HandleConstructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
906 // check the attribute arguments.
907 if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
908 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
909 << "0 or 1";
910 return;
913 int priority = 65535; // FIXME: Do not hardcode such constants.
914 if (Attr.getNumArgs() > 0) {
915 Expr *E = Attr.getArg(0);
916 llvm::APSInt Idx(32);
917 if (E->isTypeDependent() || E->isValueDependent() ||
918 !E->isIntegerConstantExpr(Idx, S.Context)) {
919 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
920 << "constructor" << 1 << E->getSourceRange();
921 return;
923 priority = Idx.getZExtValue();
926 if (!isa<FunctionDecl>(d)) {
927 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
928 << Attr.getName() << 0 /*function*/;
929 return;
932 d->addAttr(::new (S.Context) ConstructorAttr(Attr.getLoc(), S.Context,
933 priority));
936 static void HandleDestructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
937 // check the attribute arguments.
938 if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
939 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
940 << "0 or 1";
941 return;
944 int priority = 65535; // FIXME: Do not hardcode such constants.
945 if (Attr.getNumArgs() > 0) {
946 Expr *E = Attr.getArg(0);
947 llvm::APSInt Idx(32);
948 if (E->isTypeDependent() || E->isValueDependent() ||
949 !E->isIntegerConstantExpr(Idx, S.Context)) {
950 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
951 << "destructor" << 1 << E->getSourceRange();
952 return;
954 priority = Idx.getZExtValue();
957 if (!isa<FunctionDecl>(d)) {
958 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
959 << Attr.getName() << 0 /*function*/;
960 return;
963 d->addAttr(::new (S.Context) DestructorAttr(Attr.getLoc(), S.Context,
964 priority));
967 static void HandleDeprecatedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
968 // check the attribute arguments.
969 int noArgs = Attr.getNumArgs();
970 if (noArgs > 1) {
971 S.Diag(Attr.getLoc(),
972 diag::err_attribute_wrong_number_arguments) << "0 or 1";
973 return;
975 // Handle the case where deprecated attribute has a text message.
976 StringLiteral *SE;
977 if (noArgs == 1) {
978 Expr *ArgExpr = Attr.getArg(0);
979 SE = dyn_cast<StringLiteral>(ArgExpr);
980 if (!SE) {
981 S.Diag(ArgExpr->getLocStart(),
982 diag::err_attribute_not_string) << "deprecated";
983 return;
986 else
987 SE = StringLiteral::CreateEmpty(S.Context, 1);
989 d->addAttr(::new (S.Context) DeprecatedAttr(Attr.getLoc(), S.Context,
990 SE->getString()));
993 static void HandleUnavailableAttr(Decl *d, const AttributeList &Attr, Sema &S) {
994 // check the attribute arguments.
995 int noArgs = Attr.getNumArgs();
996 if (noArgs > 1) {
997 S.Diag(Attr.getLoc(),
998 diag::err_attribute_wrong_number_arguments) << "0 or 1";
999 return;
1001 // Handle the case where unavailable attribute has a text message.
1002 StringLiteral *SE;
1003 if (noArgs == 1) {
1004 Expr *ArgExpr = Attr.getArg(0);
1005 SE = dyn_cast<StringLiteral>(ArgExpr);
1006 if (!SE) {
1007 S.Diag(ArgExpr->getLocStart(),
1008 diag::err_attribute_not_string) << "unavailable";
1009 return;
1012 else
1013 SE = StringLiteral::CreateEmpty(S.Context, 1);
1014 d->addAttr(::new (S.Context) UnavailableAttr(Attr.getLoc(), S.Context,
1015 SE->getString()));
1018 static void HandleVisibilityAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1019 // check the attribute arguments.
1020 if (Attr.getNumArgs() != 1) {
1021 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1022 return;
1025 Expr *Arg = Attr.getArg(0);
1026 Arg = Arg->IgnoreParenCasts();
1027 StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
1029 if (Str == 0 || Str->isWide()) {
1030 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1031 << "visibility" << 1;
1032 return;
1035 llvm::StringRef TypeStr = Str->getString();
1036 VisibilityAttr::VisibilityType type;
1038 if (TypeStr == "default")
1039 type = VisibilityAttr::Default;
1040 else if (TypeStr == "hidden")
1041 type = VisibilityAttr::Hidden;
1042 else if (TypeStr == "internal")
1043 type = VisibilityAttr::Hidden; // FIXME
1044 else if (TypeStr == "protected")
1045 type = VisibilityAttr::Protected;
1046 else {
1047 S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
1048 return;
1051 d->addAttr(::new (S.Context) VisibilityAttr(Attr.getLoc(), S.Context, type));
1054 static void HandleObjCExceptionAttr(Decl *D, const AttributeList &Attr,
1055 Sema &S) {
1056 if (Attr.getNumArgs() != 0) {
1057 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1058 return;
1061 ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
1062 if (OCI == 0) {
1063 S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
1064 return;
1067 D->addAttr(::new (S.Context) ObjCExceptionAttr(Attr.getLoc(), S.Context));
1070 static void HandleObjCNSObject(Decl *D, const AttributeList &Attr, Sema &S) {
1071 if (Attr.getNumArgs() != 0) {
1072 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1073 return;
1075 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1076 QualType T = TD->getUnderlyingType();
1077 if (!T->isPointerType() ||
1078 !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
1079 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
1080 return;
1083 D->addAttr(::new (S.Context) ObjCNSObjectAttr(Attr.getLoc(), S.Context));
1086 static void
1087 HandleOverloadableAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1088 if (Attr.getNumArgs() != 0) {
1089 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1090 return;
1093 if (!isa<FunctionDecl>(D)) {
1094 S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
1095 return;
1098 D->addAttr(::new (S.Context) OverloadableAttr(Attr.getLoc(), S.Context));
1101 static void HandleBlocksAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1102 if (!Attr.getParameterName()) {
1103 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1104 << "blocks" << 1;
1105 return;
1108 if (Attr.getNumArgs() != 0) {
1109 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1110 return;
1113 BlocksAttr::BlockType type;
1114 if (Attr.getParameterName()->isStr("byref"))
1115 type = BlocksAttr::ByRef;
1116 else {
1117 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1118 << "blocks" << Attr.getParameterName();
1119 return;
1122 d->addAttr(::new (S.Context) BlocksAttr(Attr.getLoc(), S.Context, type));
1125 static void HandleSentinelAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1126 // check the attribute arguments.
1127 if (Attr.getNumArgs() > 2) {
1128 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1129 << "0, 1 or 2";
1130 return;
1133 int sentinel = 0;
1134 if (Attr.getNumArgs() > 0) {
1135 Expr *E = Attr.getArg(0);
1136 llvm::APSInt Idx(32);
1137 if (E->isTypeDependent() || E->isValueDependent() ||
1138 !E->isIntegerConstantExpr(Idx, S.Context)) {
1139 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1140 << "sentinel" << 1 << E->getSourceRange();
1141 return;
1143 sentinel = Idx.getZExtValue();
1145 if (sentinel < 0) {
1146 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
1147 << E->getSourceRange();
1148 return;
1152 int nullPos = 0;
1153 if (Attr.getNumArgs() > 1) {
1154 Expr *E = Attr.getArg(1);
1155 llvm::APSInt Idx(32);
1156 if (E->isTypeDependent() || E->isValueDependent() ||
1157 !E->isIntegerConstantExpr(Idx, S.Context)) {
1158 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1159 << "sentinel" << 2 << E->getSourceRange();
1160 return;
1162 nullPos = Idx.getZExtValue();
1164 if (nullPos > 1 || nullPos < 0) {
1165 // FIXME: This error message could be improved, it would be nice
1166 // to say what the bounds actually are.
1167 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
1168 << E->getSourceRange();
1169 return;
1173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
1174 const FunctionType *FT = FD->getType()->getAs<FunctionType>();
1175 assert(FT && "FunctionDecl has non-function type?");
1177 if (isa<FunctionNoProtoType>(FT)) {
1178 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
1179 return;
1182 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1183 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1184 return;
1186 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d)) {
1187 if (!MD->isVariadic()) {
1188 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
1189 return;
1191 } else if (isa<BlockDecl>(d)) {
1192 // Note! BlockDecl is typeless. Variadic diagnostics will be issued by the
1193 // caller.
1195 } else if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
1196 QualType Ty = V->getType();
1197 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
1198 const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(d)
1199 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
1200 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
1201 int m = Ty->isFunctionPointerType() ? 0 : 1;
1202 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
1203 return;
1205 } else {
1206 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1207 << Attr.getName() << 6 /*function, method or block */;
1208 return;
1210 } else {
1211 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1212 << Attr.getName() << 6 /*function, method or block */;
1213 return;
1215 d->addAttr(::new (S.Context) SentinelAttr(Attr.getLoc(), S.Context, sentinel,
1216 nullPos));
1219 static void HandleWarnUnusedResult(Decl *D, const AttributeList &Attr, Sema &S) {
1220 // check the attribute arguments.
1221 if (Attr.getNumArgs() != 0) {
1222 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1223 return;
1226 if (!isFunction(D) && !isa<ObjCMethodDecl>(D)) {
1227 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1228 << Attr.getName() << 0 /*function*/;
1229 return;
1232 if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
1233 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1234 << Attr.getName() << 0;
1235 return;
1237 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
1238 if (MD->getResultType()->isVoidType()) {
1239 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
1240 << Attr.getName() << 1;
1241 return;
1244 D->addAttr(::new (S.Context) WarnUnusedResultAttr(Attr.getLoc(), S.Context));
1247 static void HandleWeakAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1248 // check the attribute arguments.
1249 if (Attr.getNumArgs() != 0) {
1250 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1251 return;
1254 /* weak only applies to non-static declarations */
1255 if (isStaticVarOrStaticFunciton(D)) {
1256 S.Diag(Attr.getLoc(), diag::err_attribute_weak_static) <<
1257 dyn_cast<NamedDecl>(D)->getNameAsString();
1258 return;
1261 // TODO: could also be applied to methods?
1262 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
1263 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1264 << Attr.getName() << 2 /*variable and function*/;
1265 return;
1268 D->addAttr(::new (S.Context) WeakAttr(Attr.getLoc(), S.Context));
1271 static void HandleWeakImportAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1272 // check the attribute arguments.
1273 if (Attr.getNumArgs() != 0) {
1274 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1275 return;
1278 // weak_import only applies to variable & function declarations.
1279 bool isDef = false;
1280 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1281 isDef = (!VD->hasExternalStorage() || VD->getInit());
1282 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1283 isDef = FD->hasBody();
1284 } else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D)) {
1285 // We ignore weak import on properties and methods
1286 return;
1287 } else if (!(S.LangOpts.ObjCNonFragileABI && isa<ObjCInterfaceDecl>(D))) {
1288 // Don't issue the warning for darwin as target; yet, ignore the attribute.
1289 if (S.Context.Target.getTriple().getOS() != llvm::Triple::Darwin ||
1290 !isa<ObjCInterfaceDecl>(D))
1291 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1292 << Attr.getName() << 2 /*variable and function*/;
1293 return;
1296 // Merge should handle any subsequent violations.
1297 if (isDef) {
1298 S.Diag(Attr.getLoc(),
1299 diag::warn_attribute_weak_import_invalid_on_definition)
1300 << "weak_import" << 2 /*variable and function*/;
1301 return;
1304 D->addAttr(::new (S.Context) WeakImportAttr(Attr.getLoc(), S.Context));
1307 static void HandleReqdWorkGroupSize(Decl *D, const AttributeList &Attr,
1308 Sema &S) {
1309 // Attribute has 3 arguments.
1310 if (Attr.getNumArgs() != 3) {
1311 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1312 return;
1315 unsigned WGSize[3];
1316 for (unsigned i = 0; i < 3; ++i) {
1317 Expr *E = Attr.getArg(i);
1318 llvm::APSInt ArgNum(32);
1319 if (E->isTypeDependent() || E->isValueDependent() ||
1320 !E->isIntegerConstantExpr(ArgNum, S.Context)) {
1321 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1322 << "reqd_work_group_size" << E->getSourceRange();
1323 return;
1325 WGSize[i] = (unsigned) ArgNum.getZExtValue();
1327 D->addAttr(::new (S.Context) ReqdWorkGroupSizeAttr(Attr.getLoc(), S.Context,
1328 WGSize[0], WGSize[1],
1329 WGSize[2]));
1332 static void HandleSectionAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1333 // Attribute has no arguments.
1334 if (Attr.getNumArgs() != 1) {
1335 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1336 return;
1339 // Make sure that there is a string literal as the sections's single
1340 // argument.
1341 Expr *ArgExpr = Attr.getArg(0);
1342 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1343 if (!SE) {
1344 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
1345 return;
1348 // If the target wants to validate the section specifier, make it happen.
1349 std::string Error = S.Context.Target.isValidSectionSpecifier(SE->getString());
1350 if (!Error.empty()) {
1351 S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
1352 << Error;
1353 return;
1356 // This attribute cannot be applied to local variables.
1357 if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
1358 S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
1359 return;
1362 D->addAttr(::new (S.Context) SectionAttr(Attr.getLoc(), S.Context,
1363 SE->getString()));
1367 static void HandleNothrowAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1368 // check the attribute arguments.
1369 if (Attr.getNumArgs() != 0) {
1370 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1371 return;
1374 d->addAttr(::new (S.Context) NoThrowAttr(Attr.getLoc(), S.Context));
1377 static void HandleConstAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1378 // check the attribute arguments.
1379 if (Attr.getNumArgs() != 0) {
1380 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1381 return;
1384 d->addAttr(::new (S.Context) ConstAttr(Attr.getLoc(), S.Context));
1387 static void HandlePureAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1388 // check the attribute arguments.
1389 if (Attr.getNumArgs() != 0) {
1390 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1391 return;
1394 d->addAttr(::new (S.Context) PureAttr(Attr.getLoc(), S.Context));
1397 static void HandleCleanupAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1398 if (!Attr.getParameterName()) {
1399 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1400 return;
1403 if (Attr.getNumArgs() != 0) {
1404 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1405 return;
1408 VarDecl *VD = dyn_cast<VarDecl>(d);
1410 if (!VD || !VD->hasLocalStorage()) {
1411 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
1412 return;
1415 // Look up the function
1416 // FIXME: Lookup probably isn't looking in the right place
1417 NamedDecl *CleanupDecl
1418 = S.LookupSingleName(S.TUScope, Attr.getParameterName(),
1419 Attr.getParameterLoc(), Sema::LookupOrdinaryName);
1420 if (!CleanupDecl) {
1421 S.Diag(Attr.getParameterLoc(), diag::err_attribute_cleanup_arg_not_found) <<
1422 Attr.getParameterName();
1423 return;
1426 FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
1427 if (!FD) {
1428 S.Diag(Attr.getParameterLoc(),
1429 diag::err_attribute_cleanup_arg_not_function)
1430 << Attr.getParameterName();
1431 return;
1434 if (FD->getNumParams() != 1) {
1435 S.Diag(Attr.getParameterLoc(),
1436 diag::err_attribute_cleanup_func_must_take_one_arg)
1437 << Attr.getParameterName();
1438 return;
1441 // We're currently more strict than GCC about what function types we accept.
1442 // If this ever proves to be a problem it should be easy to fix.
1443 QualType Ty = S.Context.getPointerType(VD->getType());
1444 QualType ParamTy = FD->getParamDecl(0)->getType();
1445 if (S.CheckAssignmentConstraints(ParamTy, Ty) != Sema::Compatible) {
1446 S.Diag(Attr.getParameterLoc(),
1447 diag::err_attribute_cleanup_func_arg_incompatible_type) <<
1448 Attr.getParameterName() << ParamTy << Ty;
1449 return;
1452 d->addAttr(::new (S.Context) CleanupAttr(Attr.getLoc(), S.Context, FD));
1453 S.MarkDeclarationReferenced(Attr.getParameterLoc(), FD);
1456 /// Handle __attribute__((format_arg((idx)))) attribute based on
1457 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1458 static void HandleFormatArgAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1459 if (Attr.getNumArgs() != 1) {
1460 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1461 return;
1463 if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
1464 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1465 << Attr.getName() << 0 /*function*/;
1466 return;
1469 // In C++ the implicit 'this' function parameter also counts, and they are
1470 // counted from one.
1471 bool HasImplicitThisParam = isInstanceMethod(d);
1472 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
1473 unsigned FirstIdx = 1;
1475 // checks for the 2nd argument
1476 Expr *IdxExpr = Attr.getArg(0);
1477 llvm::APSInt Idx(32);
1478 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1479 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1480 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1481 << "format" << 2 << IdxExpr->getSourceRange();
1482 return;
1485 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1486 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1487 << "format" << 2 << IdxExpr->getSourceRange();
1488 return;
1491 unsigned ArgIdx = Idx.getZExtValue() - 1;
1493 if (HasImplicitThisParam) {
1494 if (ArgIdx == 0) {
1495 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_implicit_this_argument)
1496 << "format_arg" << IdxExpr->getSourceRange();
1497 return;
1499 ArgIdx--;
1502 // make sure the format string is really a string
1503 QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1505 bool not_nsstring_type = !isNSStringType(Ty, S.Context);
1506 if (not_nsstring_type &&
1507 !isCFStringType(Ty, S.Context) &&
1508 (!Ty->isPointerType() ||
1509 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1510 // FIXME: Should highlight the actual expression that has the wrong type.
1511 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1512 << (not_nsstring_type ? "a string type" : "an NSString")
1513 << IdxExpr->getSourceRange();
1514 return;
1516 Ty = getFunctionOrMethodResultType(d);
1517 if (!isNSStringType(Ty, S.Context) &&
1518 !isCFStringType(Ty, S.Context) &&
1519 (!Ty->isPointerType() ||
1520 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1521 // FIXME: Should highlight the actual expression that has the wrong type.
1522 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
1523 << (not_nsstring_type ? "string type" : "NSString")
1524 << IdxExpr->getSourceRange();
1525 return;
1528 d->addAttr(::new (S.Context) FormatArgAttr(Attr.getLoc(), S.Context,
1529 Idx.getZExtValue()));
1532 enum FormatAttrKind {
1533 CFStringFormat,
1534 NSStringFormat,
1535 StrftimeFormat,
1536 SupportedFormat,
1537 IgnoredFormat,
1538 InvalidFormat
1541 /// getFormatAttrKind - Map from format attribute names to supported format
1542 /// types.
1543 static FormatAttrKind getFormatAttrKind(llvm::StringRef Format) {
1544 // Check for formats that get handled specially.
1545 if (Format == "NSString")
1546 return NSStringFormat;
1547 if (Format == "CFString")
1548 return CFStringFormat;
1549 if (Format == "strftime")
1550 return StrftimeFormat;
1552 // Otherwise, check for supported formats.
1553 if (Format == "scanf" || Format == "printf" || Format == "printf0" ||
1554 Format == "strfmon" || Format == "cmn_err" || Format == "strftime" ||
1555 Format == "NSString" || Format == "CFString" || Format == "vcmn_err" ||
1556 Format == "zcmn_err")
1557 return SupportedFormat;
1559 if (Format == "gcc_diag" || Format == "gcc_cdiag" ||
1560 Format == "gcc_cxxdiag" || Format == "gcc_tdiag")
1561 return IgnoredFormat;
1563 return InvalidFormat;
1566 /// Handle __attribute__((init_priority(priority))) attributes based on
1567 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
1568 static void HandleInitPriorityAttr(Decl *d, const AttributeList &Attr,
1569 Sema &S) {
1570 if (!S.getLangOptions().CPlusPlus) {
1571 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1572 return;
1575 if (!isa<VarDecl>(d) || S.getCurFunctionOrMethodDecl()) {
1576 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
1577 Attr.setInvalid();
1578 return;
1580 QualType T = dyn_cast<VarDecl>(d)->getType();
1581 if (S.Context.getAsArrayType(T))
1582 T = S.Context.getBaseElementType(T);
1583 if (!T->getAs<RecordType>()) {
1584 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
1585 Attr.setInvalid();
1586 return;
1589 if (Attr.getNumArgs() != 1) {
1590 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1591 Attr.setInvalid();
1592 return;
1594 Expr *priorityExpr = Attr.getArg(0);
1596 llvm::APSInt priority(32);
1597 if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
1598 !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
1599 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1600 << "init_priority" << priorityExpr->getSourceRange();
1601 Attr.setInvalid();
1602 return;
1604 unsigned prioritynum = priority.getZExtValue();
1605 if (prioritynum < 101 || prioritynum > 65535) {
1606 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
1607 << priorityExpr->getSourceRange();
1608 Attr.setInvalid();
1609 return;
1611 d->addAttr(::new (S.Context) InitPriorityAttr(Attr.getLoc(), S.Context,
1612 prioritynum));
1615 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
1616 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1617 static void HandleFormatAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1619 if (!Attr.getParameterName()) {
1620 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1621 << "format" << 1;
1622 return;
1625 if (Attr.getNumArgs() != 2) {
1626 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
1627 return;
1630 if (!isFunctionOrMethodOrBlock(d) || !hasFunctionProto(d)) {
1631 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1632 << Attr.getName() << 0 /*function*/;
1633 return;
1636 // In C++ the implicit 'this' function parameter also counts, and they are
1637 // counted from one.
1638 bool HasImplicitThisParam = isInstanceMethod(d);
1639 unsigned NumArgs = getFunctionOrMethodNumArgs(d) + HasImplicitThisParam;
1640 unsigned FirstIdx = 1;
1642 llvm::StringRef Format = Attr.getParameterName()->getName();
1644 // Normalize the argument, __foo__ becomes foo.
1645 if (Format.startswith("__") && Format.endswith("__"))
1646 Format = Format.substr(2, Format.size() - 4);
1648 // Check for supported formats.
1649 FormatAttrKind Kind = getFormatAttrKind(Format);
1651 if (Kind == IgnoredFormat)
1652 return;
1654 if (Kind == InvalidFormat) {
1655 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1656 << "format" << Attr.getParameterName()->getName();
1657 return;
1660 // checks for the 2nd argument
1661 Expr *IdxExpr = Attr.getArg(0);
1662 llvm::APSInt Idx(32);
1663 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1664 !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1665 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1666 << "format" << 2 << IdxExpr->getSourceRange();
1667 return;
1670 if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1671 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1672 << "format" << 2 << IdxExpr->getSourceRange();
1673 return;
1676 // FIXME: Do we need to bounds check?
1677 unsigned ArgIdx = Idx.getZExtValue() - 1;
1679 if (HasImplicitThisParam) {
1680 if (ArgIdx == 0) {
1681 S.Diag(Attr.getLoc(),
1682 diag::err_format_attribute_implicit_this_format_string)
1683 << IdxExpr->getSourceRange();
1684 return;
1686 ArgIdx--;
1689 // make sure the format string is really a string
1690 QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1692 if (Kind == CFStringFormat) {
1693 if (!isCFStringType(Ty, S.Context)) {
1694 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1695 << "a CFString" << IdxExpr->getSourceRange();
1696 return;
1698 } else if (Kind == NSStringFormat) {
1699 // FIXME: do we need to check if the type is NSString*? What are the
1700 // semantics?
1701 if (!isNSStringType(Ty, S.Context)) {
1702 // FIXME: Should highlight the actual expression that has the wrong type.
1703 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1704 << "an NSString" << IdxExpr->getSourceRange();
1705 return;
1707 } else if (!Ty->isPointerType() ||
1708 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
1709 // FIXME: Should highlight the actual expression that has the wrong type.
1710 S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1711 << "a string type" << IdxExpr->getSourceRange();
1712 return;
1715 // check the 3rd argument
1716 Expr *FirstArgExpr = Attr.getArg(1);
1717 llvm::APSInt FirstArg(32);
1718 if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
1719 !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
1720 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1721 << "format" << 3 << FirstArgExpr->getSourceRange();
1722 return;
1725 // check if the function is variadic if the 3rd argument non-zero
1726 if (FirstArg != 0) {
1727 if (isFunctionOrMethodVariadic(d)) {
1728 ++NumArgs; // +1 for ...
1729 } else {
1730 S.Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
1731 return;
1735 // strftime requires FirstArg to be 0 because it doesn't read from any
1736 // variable the input is just the current time + the format string.
1737 if (Kind == StrftimeFormat) {
1738 if (FirstArg != 0) {
1739 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
1740 << FirstArgExpr->getSourceRange();
1741 return;
1743 // if 0 it disables parameter checking (to use with e.g. va_list)
1744 } else if (FirstArg != 0 && FirstArg != NumArgs) {
1745 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1746 << "format" << 3 << FirstArgExpr->getSourceRange();
1747 return;
1750 d->addAttr(::new (S.Context) FormatAttr(Attr.getLoc(), S.Context, Format,
1751 Idx.getZExtValue(),
1752 FirstArg.getZExtValue()));
1755 static void HandleTransparentUnionAttr(Decl *d, const AttributeList &Attr,
1756 Sema &S) {
1757 // check the attribute arguments.
1758 if (Attr.getNumArgs() != 0) {
1759 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1760 return;
1763 // Try to find the underlying union declaration.
1764 RecordDecl *RD = 0;
1765 TypedefDecl *TD = dyn_cast<TypedefDecl>(d);
1766 if (TD && TD->getUnderlyingType()->isUnionType())
1767 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
1768 else
1769 RD = dyn_cast<RecordDecl>(d);
1771 if (!RD || !RD->isUnion()) {
1772 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1773 << Attr.getName() << 1 /*union*/;
1774 return;
1777 if (!RD->isDefinition()) {
1778 S.Diag(Attr.getLoc(),
1779 diag::warn_transparent_union_attribute_not_definition);
1780 return;
1783 RecordDecl::field_iterator Field = RD->field_begin(),
1784 FieldEnd = RD->field_end();
1785 if (Field == FieldEnd) {
1786 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
1787 return;
1790 FieldDecl *FirstField = *Field;
1791 QualType FirstType = FirstField->getType();
1792 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
1793 S.Diag(FirstField->getLocation(),
1794 diag::warn_transparent_union_attribute_floating)
1795 << FirstType->isVectorType() << FirstType;
1796 return;
1799 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
1800 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
1801 for (; Field != FieldEnd; ++Field) {
1802 QualType FieldType = Field->getType();
1803 if (S.Context.getTypeSize(FieldType) != FirstSize ||
1804 S.Context.getTypeAlign(FieldType) != FirstAlign) {
1805 // Warn if we drop the attribute.
1806 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
1807 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
1808 : S.Context.getTypeAlign(FieldType);
1809 S.Diag(Field->getLocation(),
1810 diag::warn_transparent_union_attribute_field_size_align)
1811 << isSize << Field->getDeclName() << FieldBits;
1812 unsigned FirstBits = isSize? FirstSize : FirstAlign;
1813 S.Diag(FirstField->getLocation(),
1814 diag::note_transparent_union_first_field_size_align)
1815 << isSize << FirstBits;
1816 return;
1820 RD->addAttr(::new (S.Context) TransparentUnionAttr(Attr.getLoc(), S.Context));
1823 static void HandleAnnotateAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1824 // check the attribute arguments.
1825 if (Attr.getNumArgs() != 1) {
1826 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1827 return;
1829 Expr *ArgExpr = Attr.getArg(0);
1830 StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1832 // Make sure that there is a string literal as the annotation's single
1833 // argument.
1834 if (!SE) {
1835 S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
1836 return;
1838 d->addAttr(::new (S.Context) AnnotateAttr(Attr.getLoc(), S.Context,
1839 SE->getString()));
1842 static void HandleAlignedAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1843 // check the attribute arguments.
1844 if (Attr.getNumArgs() > 1) {
1845 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1846 return;
1849 //FIXME: The C++0x version of this attribute has more limited applicabilty
1850 // than GNU's, and should error out when it is used to specify a
1851 // weaker alignment, rather than being silently ignored.
1853 if (Attr.getNumArgs() == 0) {
1854 D->addAttr(::new (S.Context) AlignedAttr(Attr.getLoc(), S.Context, true, 0));
1855 return;
1858 S.AddAlignedAttr(Attr.getLoc(), D, Attr.getArg(0));
1861 void Sema::AddAlignedAttr(SourceLocation AttrLoc, Decl *D, Expr *E) {
1862 if (E->isTypeDependent() || E->isValueDependent()) {
1863 // Save dependent expressions in the AST to be instantiated.
1864 D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, true, E));
1865 return;
1868 // FIXME: Cache the number on the Attr object?
1869 llvm::APSInt Alignment(32);
1870 if (!E->isIntegerConstantExpr(Alignment, Context)) {
1871 Diag(AttrLoc, diag::err_attribute_argument_not_int)
1872 << "aligned" << E->getSourceRange();
1873 return;
1875 if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
1876 Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
1877 << E->getSourceRange();
1878 return;
1881 D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, true, E));
1884 void Sema::AddAlignedAttr(SourceLocation AttrLoc, Decl *D, TypeSourceInfo *TS) {
1885 // FIXME: Cache the number on the Attr object if non-dependent?
1886 // FIXME: Perform checking of type validity
1887 D->addAttr(::new (Context) AlignedAttr(AttrLoc, Context, false, TS));
1888 return;
1891 /// HandleModeAttr - This attribute modifies the width of a decl with primitive
1892 /// type.
1894 /// Despite what would be logical, the mode attribute is a decl attribute, not a
1895 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
1896 /// HImode, not an intermediate pointer.
1897 static void HandleModeAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1898 // This attribute isn't documented, but glibc uses it. It changes
1899 // the width of an int or unsigned int to the specified size.
1901 // Check that there aren't any arguments
1902 if (Attr.getNumArgs() != 0) {
1903 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1904 return;
1907 IdentifierInfo *Name = Attr.getParameterName();
1908 if (!Name) {
1909 S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
1910 return;
1913 llvm::StringRef Str = Attr.getParameterName()->getName();
1915 // Normalize the attribute name, __foo__ becomes foo.
1916 if (Str.startswith("__") && Str.endswith("__"))
1917 Str = Str.substr(2, Str.size() - 4);
1919 unsigned DestWidth = 0;
1920 bool IntegerMode = true;
1921 bool ComplexMode = false;
1922 switch (Str.size()) {
1923 case 2:
1924 switch (Str[0]) {
1925 case 'Q': DestWidth = 8; break;
1926 case 'H': DestWidth = 16; break;
1927 case 'S': DestWidth = 32; break;
1928 case 'D': DestWidth = 64; break;
1929 case 'X': DestWidth = 96; break;
1930 case 'T': DestWidth = 128; break;
1932 if (Str[1] == 'F') {
1933 IntegerMode = false;
1934 } else if (Str[1] == 'C') {
1935 IntegerMode = false;
1936 ComplexMode = true;
1937 } else if (Str[1] != 'I') {
1938 DestWidth = 0;
1940 break;
1941 case 4:
1942 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
1943 // pointer on PIC16 and other embedded platforms.
1944 if (Str == "word")
1945 DestWidth = S.Context.Target.getPointerWidth(0);
1946 else if (Str == "byte")
1947 DestWidth = S.Context.Target.getCharWidth();
1948 break;
1949 case 7:
1950 if (Str == "pointer")
1951 DestWidth = S.Context.Target.getPointerWidth(0);
1952 break;
1955 QualType OldTy;
1956 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D))
1957 OldTy = TD->getUnderlyingType();
1958 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
1959 OldTy = VD->getType();
1960 else {
1961 S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
1962 << "mode" << SourceRange(Attr.getLoc(), Attr.getLoc());
1963 return;
1966 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
1967 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
1968 else if (IntegerMode) {
1969 if (!OldTy->isIntegralOrEnumerationType())
1970 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1971 } else if (ComplexMode) {
1972 if (!OldTy->isComplexType())
1973 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1974 } else {
1975 if (!OldTy->isFloatingType())
1976 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1979 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
1980 // and friends, at least with glibc.
1981 // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
1982 // width on unusual platforms.
1983 // FIXME: Make sure floating-point mappings are accurate
1984 // FIXME: Support XF and TF types
1985 QualType NewTy;
1986 switch (DestWidth) {
1987 case 0:
1988 S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
1989 return;
1990 default:
1991 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1992 return;
1993 case 8:
1994 if (!IntegerMode) {
1995 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1996 return;
1998 if (OldTy->isSignedIntegerType())
1999 NewTy = S.Context.SignedCharTy;
2000 else
2001 NewTy = S.Context.UnsignedCharTy;
2002 break;
2003 case 16:
2004 if (!IntegerMode) {
2005 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2006 return;
2008 if (OldTy->isSignedIntegerType())
2009 NewTy = S.Context.ShortTy;
2010 else
2011 NewTy = S.Context.UnsignedShortTy;
2012 break;
2013 case 32:
2014 if (!IntegerMode)
2015 NewTy = S.Context.FloatTy;
2016 else if (OldTy->isSignedIntegerType())
2017 NewTy = S.Context.IntTy;
2018 else
2019 NewTy = S.Context.UnsignedIntTy;
2020 break;
2021 case 64:
2022 if (!IntegerMode)
2023 NewTy = S.Context.DoubleTy;
2024 else if (OldTy->isSignedIntegerType())
2025 if (S.Context.Target.getLongWidth() == 64)
2026 NewTy = S.Context.LongTy;
2027 else
2028 NewTy = S.Context.LongLongTy;
2029 else
2030 if (S.Context.Target.getLongWidth() == 64)
2031 NewTy = S.Context.UnsignedLongTy;
2032 else
2033 NewTy = S.Context.UnsignedLongLongTy;
2034 break;
2035 case 96:
2036 NewTy = S.Context.LongDoubleTy;
2037 break;
2038 case 128:
2039 if (!IntegerMode) {
2040 S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
2041 return;
2043 if (OldTy->isSignedIntegerType())
2044 NewTy = S.Context.Int128Ty;
2045 else
2046 NewTy = S.Context.UnsignedInt128Ty;
2047 break;
2050 if (ComplexMode) {
2051 NewTy = S.Context.getComplexType(NewTy);
2054 // Install the new type.
2055 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
2056 // FIXME: preserve existing source info.
2057 TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
2058 } else
2059 cast<ValueDecl>(D)->setType(NewTy);
2062 static void HandleNoDebugAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2063 // check the attribute arguments.
2064 if (Attr.getNumArgs() > 0) {
2065 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2066 return;
2069 if (!isFunctionOrMethod(d)) {
2070 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2071 << Attr.getName() << 0 /*function*/;
2072 return;
2075 d->addAttr(::new (S.Context) NoDebugAttr(Attr.getLoc(), S.Context));
2078 static void HandleNoInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2079 // check the attribute arguments.
2080 if (Attr.getNumArgs() != 0) {
2081 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2082 return;
2085 if (!isa<FunctionDecl>(d)) {
2086 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2087 << Attr.getName() << 0 /*function*/;
2088 return;
2091 d->addAttr(::new (S.Context) NoInlineAttr(Attr.getLoc(), S.Context));
2094 static void HandleNoInstrumentFunctionAttr(Decl *d, const AttributeList &Attr,
2095 Sema &S) {
2096 // check the attribute arguments.
2097 if (Attr.getNumArgs() != 0) {
2098 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2099 return;
2102 if (!isa<FunctionDecl>(d)) {
2103 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2104 << Attr.getName() << 0 /*function*/;
2105 return;
2108 d->addAttr(::new (S.Context) NoInstrumentFunctionAttr(Attr.getLoc(),
2109 S.Context));
2112 static void HandleConstantAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2113 if (S.LangOpts.CUDA) {
2114 // check the attribute arguments.
2115 if (Attr.getNumArgs() != 0) {
2116 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2117 return;
2120 if (!isa<VarDecl>(d)) {
2121 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2122 << Attr.getName() << 12 /*variable*/;
2123 return;
2126 d->addAttr(::new (S.Context) CUDAConstantAttr(Attr.getLoc(), S.Context));
2127 } else {
2128 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
2132 static void HandleDeviceAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2133 if (S.LangOpts.CUDA) {
2134 // check the attribute arguments.
2135 if (Attr.getNumArgs() != 0) {
2136 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2137 return;
2140 if (!isa<FunctionDecl>(d) && !isa<VarDecl>(d)) {
2141 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2142 << Attr.getName() << 2 /*variable and function*/;
2143 return;
2146 d->addAttr(::new (S.Context) CUDADeviceAttr(Attr.getLoc(), S.Context));
2147 } else {
2148 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
2152 static void HandleGlobalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2153 if (S.LangOpts.CUDA) {
2154 // check the attribute arguments.
2155 if (Attr.getNumArgs() != 0) {
2156 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2157 return;
2160 if (!isa<FunctionDecl>(d)) {
2161 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2162 << Attr.getName() << 0 /*function*/;
2163 return;
2166 d->addAttr(::new (S.Context) CUDAGlobalAttr(Attr.getLoc(), S.Context));
2167 } else {
2168 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
2172 static void HandleHostAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2173 if (S.LangOpts.CUDA) {
2174 // check the attribute arguments.
2175 if (Attr.getNumArgs() != 0) {
2176 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2177 return;
2180 if (!isa<FunctionDecl>(d)) {
2181 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2182 << Attr.getName() << 0 /*function*/;
2183 return;
2186 d->addAttr(::new (S.Context) CUDAHostAttr(Attr.getLoc(), S.Context));
2187 } else {
2188 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
2192 static void HandleSharedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2193 if (S.LangOpts.CUDA) {
2194 // check the attribute arguments.
2195 if (Attr.getNumArgs() != 0) {
2196 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2197 return;
2200 if (!isa<VarDecl>(d)) {
2201 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2202 << Attr.getName() << 12 /*variable*/;
2203 return;
2206 d->addAttr(::new (S.Context) CUDASharedAttr(Attr.getLoc(), S.Context));
2207 } else {
2208 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
2212 static void HandleGNUInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2213 // check the attribute arguments.
2214 if (Attr.getNumArgs() != 0) {
2215 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2216 return;
2219 FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2220 if (Fn == 0) {
2221 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2222 << Attr.getName() << 0 /*function*/;
2223 return;
2226 if (!Fn->isInlineSpecified()) {
2227 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
2228 return;
2231 d->addAttr(::new (S.Context) GNUInlineAttr(Attr.getLoc(), S.Context));
2234 static void HandleCallConvAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2235 // Diagnostic is emitted elsewhere: here we store the (valid) Attr
2236 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
2237 assert(Attr.isInvalid() == false);
2239 switch (Attr.getKind()) {
2240 case AttributeList::AT_fastcall:
2241 d->addAttr(::new (S.Context) FastCallAttr(Attr.getLoc(), S.Context));
2242 return;
2243 case AttributeList::AT_stdcall:
2244 d->addAttr(::new (S.Context) StdCallAttr(Attr.getLoc(), S.Context));
2245 return;
2246 case AttributeList::AT_thiscall:
2247 d->addAttr(::new (S.Context) ThisCallAttr(Attr.getLoc(), S.Context));
2248 return;
2249 case AttributeList::AT_cdecl:
2250 d->addAttr(::new (S.Context) CDeclAttr(Attr.getLoc(), S.Context));
2251 return;
2252 case AttributeList::AT_pascal:
2253 d->addAttr(::new (S.Context) PascalAttr(Attr.getLoc(), S.Context));
2254 return;
2255 default:
2256 llvm_unreachable("unexpected attribute kind");
2257 return;
2261 static void HandleRegparmAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2262 // check the attribute arguments.
2263 if (Attr.getNumArgs() != 1) {
2264 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2265 return;
2268 if (!isFunctionOrMethod(d)) {
2269 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2270 << Attr.getName() << 0 /*function*/;
2271 return;
2274 Expr *NumParamsExpr = Attr.getArg(0);
2275 llvm::APSInt NumParams(32);
2276 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
2277 !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
2278 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2279 << "regparm" << NumParamsExpr->getSourceRange();
2280 return;
2283 if (S.Context.Target.getRegParmMax() == 0) {
2284 S.Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
2285 << NumParamsExpr->getSourceRange();
2286 return;
2289 if (NumParams.getLimitedValue(255) > S.Context.Target.getRegParmMax()) {
2290 S.Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
2291 << S.Context.Target.getRegParmMax() << NumParamsExpr->getSourceRange();
2292 return;
2295 d->addAttr(::new (S.Context) RegparmAttr(Attr.getLoc(), S.Context,
2296 NumParams.getZExtValue()));
2299 static void HandleFinalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2300 // check the attribute arguments.
2301 if (Attr.getNumArgs() != 0) {
2302 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2303 return;
2306 if (!isa<CXXRecordDecl>(d)
2307 && (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual())) {
2308 S.Diag(Attr.getLoc(),
2309 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2310 : diag::warn_attribute_wrong_decl_type)
2311 << Attr.getName() << 7 /*virtual method or class*/;
2312 return;
2315 // FIXME: Conform to C++0x redeclaration rules.
2317 if (d->getAttr<FinalAttr>()) {
2318 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "final";
2319 return;
2322 d->addAttr(::new (S.Context) FinalAttr(Attr.getLoc(), S.Context));
2325 //===----------------------------------------------------------------------===//
2326 // C++0x member checking attributes
2327 //===----------------------------------------------------------------------===//
2329 static void HandleBaseCheckAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2330 if (Attr.getNumArgs() != 0) {
2331 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2332 return;
2335 if (!isa<CXXRecordDecl>(d)) {
2336 S.Diag(Attr.getLoc(),
2337 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2338 : diag::warn_attribute_wrong_decl_type)
2339 << Attr.getName() << 9 /*class*/;
2340 return;
2343 if (d->getAttr<BaseCheckAttr>()) {
2344 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "base_check";
2345 return;
2348 d->addAttr(::new (S.Context) BaseCheckAttr(Attr.getLoc(), S.Context));
2351 static void HandleHidingAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2352 if (Attr.getNumArgs() != 0) {
2353 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2354 return;
2357 if (!isa<RecordDecl>(d->getDeclContext())) {
2358 // FIXME: It's not the type that's the problem
2359 S.Diag(Attr.getLoc(),
2360 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2361 : diag::warn_attribute_wrong_decl_type)
2362 << Attr.getName() << 11 /*member*/;
2363 return;
2366 // FIXME: Conform to C++0x redeclaration rules.
2368 if (d->getAttr<HidingAttr>()) {
2369 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "hiding";
2370 return;
2373 d->addAttr(::new (S.Context) HidingAttr(Attr.getLoc(), S.Context));
2376 static void HandleOverrideAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2377 if (Attr.getNumArgs() != 0) {
2378 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2379 return;
2382 if (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual()) {
2383 // FIXME: It's not the type that's the problem
2384 S.Diag(Attr.getLoc(),
2385 Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2386 : diag::warn_attribute_wrong_decl_type)
2387 << Attr.getName() << 10 /*virtual method*/;
2388 return;
2391 // FIXME: Conform to C++0x redeclaration rules.
2393 if (d->getAttr<OverrideAttr>()) {
2394 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "override";
2395 return;
2398 d->addAttr(::new (S.Context) OverrideAttr(Attr.getLoc(), S.Context));
2401 //===----------------------------------------------------------------------===//
2402 // Checker-specific attribute handlers.
2403 //===----------------------------------------------------------------------===//
2405 static void HandleNSReturnsRetainedAttr(Decl *d, const AttributeList &Attr,
2406 Sema &S) {
2408 QualType RetTy;
2410 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
2411 RetTy = MD->getResultType();
2412 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d))
2413 RetTy = FD->getResultType();
2414 else {
2415 SourceLocation L = Attr.getLoc();
2416 S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
2417 << SourceRange(L, L) << Attr.getName() << 3 /* function or method */;
2418 return;
2421 if (!(S.Context.isObjCNSObjectType(RetTy) || RetTy->getAs<PointerType>()
2422 || RetTy->getAs<ObjCObjectPointerType>())) {
2423 SourceLocation L = Attr.getLoc();
2424 S.Diag(d->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
2425 << SourceRange(L, L) << Attr.getName();
2426 return;
2429 switch (Attr.getKind()) {
2430 default:
2431 assert(0 && "invalid ownership attribute");
2432 return;
2433 case AttributeList::AT_cf_returns_not_retained:
2434 d->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(Attr.getLoc(),
2435 S.Context));
2436 return;
2437 case AttributeList::AT_ns_returns_not_retained:
2438 d->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(Attr.getLoc(),
2439 S.Context));
2440 return;
2441 case AttributeList::AT_cf_returns_retained:
2442 d->addAttr(::new (S.Context) CFReturnsRetainedAttr(Attr.getLoc(),
2443 S.Context));
2444 return;
2445 case AttributeList::AT_ns_returns_retained:
2446 d->addAttr(::new (S.Context) NSReturnsRetainedAttr(Attr.getLoc(),
2447 S.Context));
2448 return;
2452 static bool isKnownDeclSpecAttr(const AttributeList &Attr) {
2453 return Attr.getKind() == AttributeList::AT_dllimport ||
2454 Attr.getKind() == AttributeList::AT_dllexport;
2457 //===----------------------------------------------------------------------===//
2458 // Top Level Sema Entry Points
2459 //===----------------------------------------------------------------------===//
2461 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
2462 /// the attribute applies to decls. If the attribute is a type attribute, just
2463 /// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
2464 /// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
2465 static void ProcessDeclAttribute(Scope *scope, Decl *D,
2466 const AttributeList &Attr, Sema &S) {
2467 if (Attr.isInvalid())
2468 return;
2470 if (Attr.isDeclspecAttribute() && !isKnownDeclSpecAttr(Attr))
2471 // FIXME: Try to deal with other __declspec attributes!
2472 return;
2473 switch (Attr.getKind()) {
2474 case AttributeList::AT_IBAction: HandleIBAction(D, Attr, S); break;
2475 case AttributeList::AT_IBOutlet: HandleIBOutlet(D, Attr, S); break;
2476 case AttributeList::AT_IBOutletCollection:
2477 HandleIBOutletCollection(D, Attr, S); break;
2478 case AttributeList::AT_address_space:
2479 case AttributeList::AT_objc_gc:
2480 case AttributeList::AT_vector_size:
2481 case AttributeList::AT_neon_vector_type:
2482 case AttributeList::AT_neon_polyvector_type:
2483 // Ignore these, these are type attributes, handled by
2484 // ProcessTypeAttributes.
2485 break;
2486 case AttributeList::AT_alias: HandleAliasAttr (D, Attr, S); break;
2487 case AttributeList::AT_aligned: HandleAlignedAttr (D, Attr, S); break;
2488 case AttributeList::AT_always_inline:
2489 HandleAlwaysInlineAttr (D, Attr, S); break;
2490 case AttributeList::AT_analyzer_noreturn:
2491 HandleAnalyzerNoReturnAttr (D, Attr, S); break;
2492 case AttributeList::AT_annotate: HandleAnnotateAttr (D, Attr, S); break;
2493 case AttributeList::AT_base_check: HandleBaseCheckAttr (D, Attr, S); break;
2494 case AttributeList::AT_carries_dependency:
2495 HandleDependencyAttr (D, Attr, S); break;
2496 case AttributeList::AT_common: HandleCommonAttr (D, Attr, S); break;
2497 case AttributeList::AT_constant: HandleConstantAttr (D, Attr, S); break;
2498 case AttributeList::AT_constructor: HandleConstructorAttr (D, Attr, S); break;
2499 case AttributeList::AT_deprecated: HandleDeprecatedAttr (D, Attr, S); break;
2500 case AttributeList::AT_destructor: HandleDestructorAttr (D, Attr, S); break;
2501 case AttributeList::AT_device: HandleDeviceAttr (D, Attr, S); break;
2502 case AttributeList::AT_ext_vector_type:
2503 HandleExtVectorTypeAttr(scope, D, Attr, S);
2504 break;
2505 case AttributeList::AT_final: HandleFinalAttr (D, Attr, S); break;
2506 case AttributeList::AT_format: HandleFormatAttr (D, Attr, S); break;
2507 case AttributeList::AT_format_arg: HandleFormatArgAttr (D, Attr, S); break;
2508 case AttributeList::AT_global: HandleGlobalAttr (D, Attr, S); break;
2509 case AttributeList::AT_gnu_inline: HandleGNUInlineAttr (D, Attr, S); break;
2510 case AttributeList::AT_hiding: HandleHidingAttr (D, Attr, S); break;
2511 case AttributeList::AT_host: HandleHostAttr (D, Attr, S); break;
2512 case AttributeList::AT_mode: HandleModeAttr (D, Attr, S); break;
2513 case AttributeList::AT_malloc: HandleMallocAttr (D, Attr, S); break;
2514 case AttributeList::AT_may_alias: HandleMayAliasAttr (D, Attr, S); break;
2515 case AttributeList::AT_nocommon: HandleNoCommonAttr (D, Attr, S); break;
2516 case AttributeList::AT_nonnull: HandleNonNullAttr (D, Attr, S); break;
2517 case AttributeList::AT_ownership_returns:
2518 case AttributeList::AT_ownership_takes:
2519 case AttributeList::AT_ownership_holds:
2520 HandleOwnershipAttr (D, Attr, S); break;
2521 case AttributeList::AT_naked: HandleNakedAttr (D, Attr, S); break;
2522 case AttributeList::AT_noreturn: HandleNoReturnAttr (D, Attr, S); break;
2523 case AttributeList::AT_nothrow: HandleNothrowAttr (D, Attr, S); break;
2524 case AttributeList::AT_override: HandleOverrideAttr (D, Attr, S); break;
2525 case AttributeList::AT_shared: HandleSharedAttr (D, Attr, S); break;
2526 case AttributeList::AT_vecreturn: HandleVecReturnAttr (D, Attr, S); break;
2528 // Checker-specific.
2529 case AttributeList::AT_ns_returns_not_retained:
2530 case AttributeList::AT_cf_returns_not_retained:
2531 case AttributeList::AT_ns_returns_retained:
2532 case AttributeList::AT_cf_returns_retained:
2533 HandleNSReturnsRetainedAttr(D, Attr, S); break;
2535 case AttributeList::AT_reqd_wg_size:
2536 HandleReqdWorkGroupSize(D, Attr, S); break;
2538 case AttributeList::AT_init_priority:
2539 HandleInitPriorityAttr(D, Attr, S); break;
2541 case AttributeList::AT_packed: HandlePackedAttr (D, Attr, S); break;
2542 case AttributeList::AT_section: HandleSectionAttr (D, Attr, S); break;
2543 case AttributeList::AT_unavailable: HandleUnavailableAttr (D, Attr, S); break;
2544 case AttributeList::AT_unused: HandleUnusedAttr (D, Attr, S); break;
2545 case AttributeList::AT_used: HandleUsedAttr (D, Attr, S); break;
2546 case AttributeList::AT_visibility: HandleVisibilityAttr (D, Attr, S); break;
2547 case AttributeList::AT_warn_unused_result: HandleWarnUnusedResult(D,Attr,S);
2548 break;
2549 case AttributeList::AT_weak: HandleWeakAttr (D, Attr, S); break;
2550 case AttributeList::AT_weakref: HandleWeakRefAttr (D, Attr, S); break;
2551 case AttributeList::AT_weak_import: HandleWeakImportAttr (D, Attr, S); break;
2552 case AttributeList::AT_transparent_union:
2553 HandleTransparentUnionAttr(D, Attr, S);
2554 break;
2555 case AttributeList::AT_objc_exception:
2556 HandleObjCExceptionAttr(D, Attr, S);
2557 break;
2558 case AttributeList::AT_overloadable:HandleOverloadableAttr(D, Attr, S); break;
2559 case AttributeList::AT_nsobject: HandleObjCNSObject (D, Attr, S); break;
2560 case AttributeList::AT_blocks: HandleBlocksAttr (D, Attr, S); break;
2561 case AttributeList::AT_sentinel: HandleSentinelAttr (D, Attr, S); break;
2562 case AttributeList::AT_const: HandleConstAttr (D, Attr, S); break;
2563 case AttributeList::AT_pure: HandlePureAttr (D, Attr, S); break;
2564 case AttributeList::AT_cleanup: HandleCleanupAttr (D, Attr, S); break;
2565 case AttributeList::AT_nodebug: HandleNoDebugAttr (D, Attr, S); break;
2566 case AttributeList::AT_noinline: HandleNoInlineAttr (D, Attr, S); break;
2567 case AttributeList::AT_regparm: HandleRegparmAttr (D, Attr, S); break;
2568 case AttributeList::IgnoredAttribute:
2569 // Just ignore
2570 break;
2571 case AttributeList::AT_no_instrument_function: // Interacts with -pg.
2572 HandleNoInstrumentFunctionAttr(D, Attr, S);
2573 break;
2574 case AttributeList::AT_stdcall:
2575 case AttributeList::AT_cdecl:
2576 case AttributeList::AT_fastcall:
2577 case AttributeList::AT_thiscall:
2578 case AttributeList::AT_pascal:
2579 HandleCallConvAttr(D, Attr, S);
2580 break;
2581 default:
2582 // Ask target about the attribute.
2583 const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
2584 if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
2585 S.Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored)
2586 << Attr.getName();
2587 break;
2591 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
2592 /// attribute list to the specified decl, ignoring any type attributes.
2593 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
2594 const AttributeList *AttrList) {
2595 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
2596 ProcessDeclAttribute(S, D, *l, *this);
2599 // GCC accepts
2600 // static int a9 __attribute__((weakref));
2601 // but that looks really pointless. We reject it.
2602 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
2603 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
2604 dyn_cast<NamedDecl>(D)->getNameAsString();
2605 return;
2609 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
2610 /// #pragma weak needs a non-definition decl and source may not have one
2611 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II) {
2612 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
2613 NamedDecl *NewD = 0;
2614 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2615 NewD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
2616 FD->getLocation(), DeclarationName(II),
2617 FD->getType(), FD->getTypeSourceInfo());
2618 if (FD->getQualifier()) {
2619 FunctionDecl *NewFD = cast<FunctionDecl>(NewD);
2620 NewFD->setQualifierInfo(FD->getQualifier(), FD->getQualifierRange());
2622 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
2623 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
2624 VD->getLocation(), II,
2625 VD->getType(), VD->getTypeSourceInfo(),
2626 VD->getStorageClass(),
2627 VD->getStorageClassAsWritten());
2628 if (VD->getQualifier()) {
2629 VarDecl *NewVD = cast<VarDecl>(NewD);
2630 NewVD->setQualifierInfo(VD->getQualifier(), VD->getQualifierRange());
2633 return NewD;
2636 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak
2637 /// applied to it, possibly with an alias.
2638 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
2639 if (W.getUsed()) return; // only do this once
2640 W.setUsed(true);
2641 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
2642 IdentifierInfo *NDId = ND->getIdentifier();
2643 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias());
2644 NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
2645 NDId->getName()));
2646 NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
2647 WeakTopLevelDecl.push_back(NewD);
2648 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
2649 // to insert Decl at TU scope, sorry.
2650 DeclContext *SavedContext = CurContext;
2651 CurContext = Context.getTranslationUnitDecl();
2652 PushOnScopeChains(NewD, S);
2653 CurContext = SavedContext;
2654 } else { // just add weak to existing
2655 ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
2659 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
2660 /// it, apply them to D. This is a bit tricky because PD can have attributes
2661 /// specified in many different places, and we need to find and apply them all.
2662 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
2663 // It's valid to "forward-declare" #pragma weak, in which case we
2664 // have to do this.
2665 if (!WeakUndeclaredIdentifiers.empty()) {
2666 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
2667 if (IdentifierInfo *Id = ND->getIdentifier()) {
2668 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
2669 = WeakUndeclaredIdentifiers.find(Id);
2670 if (I != WeakUndeclaredIdentifiers.end() && ND->hasLinkage()) {
2671 WeakInfo W = I->second;
2672 DeclApplyPragmaWeak(S, ND, W);
2673 WeakUndeclaredIdentifiers[Id] = W;
2679 // Apply decl attributes from the DeclSpec if present.
2680 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes())
2681 ProcessDeclAttributeList(S, D, Attrs);
2683 // Walk the declarator structure, applying decl attributes that were in a type
2684 // position to the decl itself. This handles cases like:
2685 // int *__attr__(x)** D;
2686 // when X is a decl attribute.
2687 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
2688 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
2689 ProcessDeclAttributeList(S, D, Attrs);
2691 // Finally, apply any attributes on the decl itself.
2692 if (const AttributeList *Attrs = PD.getAttributes())
2693 ProcessDeclAttributeList(S, D, Attrs);
2696 /// PushParsingDeclaration - Enter a new "scope" of deprecation
2697 /// warnings.
2699 /// The state token we use is the start index of this scope
2700 /// on the warning stack.
2701 Sema::ParsingDeclStackState Sema::PushParsingDeclaration() {
2702 ParsingDeclDepth++;
2703 return (ParsingDeclStackState) DelayedDiagnostics.size();
2706 void Sema::PopParsingDeclaration(ParsingDeclStackState S, Decl *D) {
2707 assert(ParsingDeclDepth > 0 && "empty ParsingDeclaration stack");
2708 ParsingDeclDepth--;
2710 if (DelayedDiagnostics.empty())
2711 return;
2713 unsigned SavedIndex = (unsigned) S;
2714 assert(SavedIndex <= DelayedDiagnostics.size() &&
2715 "saved index is out of bounds");
2717 unsigned E = DelayedDiagnostics.size();
2719 // We only want to actually emit delayed diagnostics when we
2720 // successfully parsed a decl.
2721 if (D) {
2722 // We really do want to start with 0 here. We get one push for a
2723 // decl spec and another for each declarator; in a decl group like:
2724 // deprecated_typedef foo, *bar, baz();
2725 // only the declarator pops will be passed decls. This is correct;
2726 // we really do need to consider delayed diagnostics from the decl spec
2727 // for each of the different declarations.
2728 for (unsigned I = 0; I != E; ++I) {
2729 if (DelayedDiagnostics[I].Triggered)
2730 continue;
2732 switch (DelayedDiagnostics[I].Kind) {
2733 case DelayedDiagnostic::Deprecation:
2734 HandleDelayedDeprecationCheck(DelayedDiagnostics[I], D);
2735 break;
2737 case DelayedDiagnostic::Access:
2738 HandleDelayedAccessCheck(DelayedDiagnostics[I], D);
2739 break;
2744 // Destroy all the delayed diagnostics we're about to pop off.
2745 for (unsigned I = SavedIndex; I != E; ++I)
2746 DelayedDiagnostics[I].destroy();
2748 DelayedDiagnostics.set_size(SavedIndex);
2751 static bool isDeclDeprecated(Decl *D) {
2752 do {
2753 if (D->hasAttr<DeprecatedAttr>())
2754 return true;
2755 } while ((D = cast_or_null<Decl>(D->getDeclContext())));
2756 return false;
2759 void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
2760 Decl *Ctx) {
2761 if (isDeclDeprecated(Ctx))
2762 return;
2764 DD.Triggered = true;
2765 if (!DD.getDeprecationMessage().empty())
2766 Diag(DD.Loc, diag::warn_deprecated_message)
2767 << DD.getDeprecationDecl()->getDeclName()
2768 << DD.getDeprecationMessage();
2769 else
2770 Diag(DD.Loc, diag::warn_deprecated)
2771 << DD.getDeprecationDecl()->getDeclName();
2774 void Sema::EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message,
2775 SourceLocation Loc) {
2776 // Delay if we're currently parsing a declaration.
2777 if (ParsingDeclDepth) {
2778 DelayedDiagnostics.push_back(DelayedDiagnostic::makeDeprecation(Loc, D,
2779 Message));
2780 return;
2783 // Otherwise, don't warn if our current context is deprecated.
2784 if (isDeclDeprecated(cast<Decl>(CurContext)))
2785 return;
2786 if (!Message.empty())
2787 Diag(Loc, diag::warn_deprecated_message) << D->getDeclName()
2788 << Message;
2789 else
2790 Diag(Loc, diag::warn_deprecated) << D->getDeclName();