SemaDeclAttr.cpp revision 1d0a5856d066f9030efbe3e0d9bbbb50ea597b99
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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "TargetAttributesSema.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Parse/DeclSpec.h"
21#include "llvm/ADT/StringExtras.h"
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25//  Helper functions
26//===----------------------------------------------------------------------===//
27
28static const FunctionType *getFunctionType(const Decl *d,
29                                           bool blocksToo = true) {
30  QualType Ty;
31  if (const ValueDecl *decl = dyn_cast<ValueDecl>(d))
32    Ty = decl->getType();
33  else if (const FieldDecl *decl = dyn_cast<FieldDecl>(d))
34    Ty = decl->getType();
35  else if (const TypedefDecl* decl = dyn_cast<TypedefDecl>(d))
36    Ty = decl->getUnderlyingType();
37  else
38    return 0;
39
40  if (Ty->isFunctionPointerType())
41    Ty = Ty->getAs<PointerType>()->getPointeeType();
42  else if (blocksToo && Ty->isBlockPointerType())
43    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
44
45  return Ty->getAs<FunctionType>();
46}
47
48// FIXME: We should provide an abstraction around a method or function
49// to provide the following bits of information.
50
51/// isFunction - Return true if the given decl has function
52/// type (function or function-typed variable).
53static bool isFunction(const Decl *d) {
54  return getFunctionType(d, false) != NULL;
55}
56
57/// isFunctionOrMethod - Return true if the given decl has function
58/// type (function or function-typed variable) or an Objective-C
59/// method.
60static bool isFunctionOrMethod(const Decl *d) {
61  return isFunction(d)|| isa<ObjCMethodDecl>(d);
62}
63
64/// isFunctionOrMethodOrBlock - Return true if the given decl has function
65/// type (function or function-typed variable) or an Objective-C
66/// method or a block.
67static bool isFunctionOrMethodOrBlock(const Decl *d) {
68  if (isFunctionOrMethod(d))
69    return true;
70  // check for block is more involved.
71  if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
72    QualType Ty = V->getType();
73    return Ty->isBlockPointerType();
74  }
75  return isa<BlockDecl>(d);
76}
77
78/// hasFunctionProto - Return true if the given decl has a argument
79/// information. This decl should have already passed
80/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
81static bool hasFunctionProto(const Decl *d) {
82  if (const FunctionType *FnTy = getFunctionType(d))
83    return isa<FunctionProtoType>(FnTy);
84  else {
85    assert(isa<ObjCMethodDecl>(d) || isa<BlockDecl>(d));
86    return true;
87  }
88}
89
90/// getFunctionOrMethodNumArgs - Return number of function or method
91/// arguments. It is an error to call this on a K&R function (use
92/// hasFunctionProto first).
93static unsigned getFunctionOrMethodNumArgs(const Decl *d) {
94  if (const FunctionType *FnTy = getFunctionType(d))
95    return cast<FunctionProtoType>(FnTy)->getNumArgs();
96  if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
97    return BD->getNumParams();
98  return cast<ObjCMethodDecl>(d)->param_size();
99}
100
101static QualType getFunctionOrMethodArgType(const Decl *d, unsigned Idx) {
102  if (const FunctionType *FnTy = getFunctionType(d))
103    return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
104  if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
105    return BD->getParamDecl(Idx)->getType();
106
107  return cast<ObjCMethodDecl>(d)->param_begin()[Idx]->getType();
108}
109
110static QualType getFunctionOrMethodResultType(const Decl *d) {
111  if (const FunctionType *FnTy = getFunctionType(d))
112    return cast<FunctionProtoType>(FnTy)->getResultType();
113  return cast<ObjCMethodDecl>(d)->getResultType();
114}
115
116static bool isFunctionOrMethodVariadic(const Decl *d) {
117  if (const FunctionType *FnTy = getFunctionType(d)) {
118    const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
119    return proto->isVariadic();
120  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(d))
121    return BD->isVariadic();
122  else {
123    return cast<ObjCMethodDecl>(d)->isVariadic();
124  }
125}
126
127static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
128  const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
129  if (!PT)
130    return false;
131
132  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
133  if (!Cls)
134    return false;
135
136  IdentifierInfo* ClsName = Cls->getIdentifier();
137
138  // FIXME: Should we walk the chain of classes?
139  return ClsName == &Ctx.Idents.get("NSString") ||
140         ClsName == &Ctx.Idents.get("NSMutableString");
141}
142
143static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
144  const PointerType *PT = T->getAs<PointerType>();
145  if (!PT)
146    return false;
147
148  const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
149  if (!RT)
150    return false;
151
152  const RecordDecl *RD = RT->getDecl();
153  if (RD->getTagKind() != TTK_Struct)
154    return false;
155
156  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
157}
158
159//===----------------------------------------------------------------------===//
160// Attribute Implementations
161//===----------------------------------------------------------------------===//
162
163// FIXME: All this manual attribute parsing code is gross. At the
164// least add some helper functions to check most argument patterns (#
165// and types of args).
166
167static void HandleExtVectorTypeAttr(Scope *scope, Decl *d,
168                                    const AttributeList &Attr, Sema &S) {
169  TypedefDecl *tDecl = dyn_cast<TypedefDecl>(d);
170  if (tDecl == 0) {
171    S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
172    return;
173  }
174
175  QualType curType = tDecl->getUnderlyingType();
176
177  Expr *sizeExpr;
178
179  // Special case where the argument is a template id.
180  if (Attr.getParameterName()) {
181    CXXScopeSpec SS;
182    UnqualifiedId id;
183    id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
184    sizeExpr = S.ActOnIdExpression(scope, SS, id, false, false).takeAs<Expr>();
185  } else {
186    // check the attribute arguments.
187    if (Attr.getNumArgs() != 1) {
188      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
189      return;
190    }
191    sizeExpr = static_cast<Expr *>(Attr.getArg(0));
192  }
193
194  // Instantiate/Install the vector type, and let Sema build the type for us.
195  // This will run the reguired checks.
196  QualType T = S.BuildExtVectorType(curType, S.Owned(sizeExpr), Attr.getLoc());
197  if (!T.isNull()) {
198    // FIXME: preserve the old source info.
199    tDecl->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(T));
200
201    // Remember this typedef decl, we will need it later for diagnostics.
202    S.ExtVectorDecls.push_back(tDecl);
203  }
204}
205
206static void HandlePackedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
207  // check the attribute arguments.
208  if (Attr.getNumArgs() > 0) {
209    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
210    return;
211  }
212
213  if (TagDecl *TD = dyn_cast<TagDecl>(d))
214    TD->addAttr(::new (S.Context) PackedAttr);
215  else if (FieldDecl *FD = dyn_cast<FieldDecl>(d)) {
216    // If the alignment is less than or equal to 8 bits, the packed attribute
217    // has no effect.
218    if (!FD->getType()->isIncompleteType() &&
219        S.Context.getTypeAlign(FD->getType()) <= 8)
220      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
221        << Attr.getName() << FD->getType();
222    else
223      FD->addAttr(::new (S.Context) PackedAttr);
224  } else
225    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
226}
227
228static void HandleIBAction(Decl *d, const AttributeList &Attr, Sema &S) {
229  // check the attribute arguments.
230  if (Attr.getNumArgs() > 0) {
231    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
232    return;
233  }
234
235  // The IBAction attributes only apply to instance methods.
236  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
237    if (MD->isInstanceMethod()) {
238      d->addAttr(::new (S.Context) IBActionAttr());
239      return;
240    }
241
242  S.Diag(Attr.getLoc(), diag::err_attribute_ibaction) << Attr.getName();
243}
244
245static void HandleIBOutlet(Decl *d, const AttributeList &Attr, Sema &S) {
246  // check the attribute arguments.
247  if (Attr.getNumArgs() > 0) {
248    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
249    return;
250  }
251
252  // The IBOutlet attributes only apply to instance variables of
253  // Objective-C classes.
254  if (isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d)) {
255    d->addAttr(::new (S.Context) IBOutletAttr());
256    return;
257  }
258
259  S.Diag(Attr.getLoc(), diag::err_attribute_iboutlet) << Attr.getName();
260}
261
262static void HandleIBOutletCollection(Decl *d, const AttributeList &Attr,
263                                     Sema &S) {
264
265  // The iboutletcollection attribute can have zero or one arguments.
266  if (Attr.getNumArgs() > 1) {
267    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
268    return;
269  }
270
271  // The IBOutletCollection attributes only apply to instance variables of
272  // Objective-C classes.
273  if (!(isa<ObjCIvarDecl>(d) || isa<ObjCPropertyDecl>(d))) {
274    S.Diag(Attr.getLoc(), diag::err_attribute_iboutlet) << Attr.getName();
275    return;
276  }
277
278  // FIXME: Eventually accept the type argument.
279  d->addAttr(::new (S.Context) IBOutletCollectionAttr());
280}
281
282static void HandleNonNullAttr(Decl *d, const AttributeList &Attr, Sema &S) {
283  // GCC ignores the nonnull attribute on K&R style function prototypes, so we
284  // ignore it as well
285  if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
286    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
287      << Attr.getName() << 0 /*function*/;
288    return;
289  }
290
291  unsigned NumArgs = getFunctionOrMethodNumArgs(d);
292
293  // The nonnull attribute only applies to pointers.
294  llvm::SmallVector<unsigned, 10> NonNullArgs;
295
296  for (AttributeList::arg_iterator I=Attr.arg_begin(),
297                                   E=Attr.arg_end(); I!=E; ++I) {
298
299
300    // The argument must be an integer constant expression.
301    Expr *Ex = static_cast<Expr *>(*I);
302    llvm::APSInt ArgNum(32);
303    if (Ex->isTypeDependent() || Ex->isValueDependent() ||
304        !Ex->isIntegerConstantExpr(ArgNum, S.Context)) {
305      S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
306        << "nonnull" << Ex->getSourceRange();
307      return;
308    }
309
310    unsigned x = (unsigned) ArgNum.getZExtValue();
311
312    if (x < 1 || x > NumArgs) {
313      S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
314       << "nonnull" << I.getArgNum() << Ex->getSourceRange();
315      return;
316    }
317
318    --x;
319
320    // Is the function argument a pointer type?
321    QualType T = getFunctionOrMethodArgType(d, x);
322    if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
323      // FIXME: Should also highlight argument in decl.
324      S.Diag(Attr.getLoc(), diag::err_nonnull_pointers_only)
325        << "nonnull" << Ex->getSourceRange();
326      continue;
327    }
328
329    NonNullArgs.push_back(x);
330  }
331
332  // If no arguments were specified to __attribute__((nonnull)) then all pointer
333  // arguments have a nonnull attribute.
334  if (NonNullArgs.empty()) {
335    for (unsigned I = 0, E = getFunctionOrMethodNumArgs(d); I != E; ++I) {
336      QualType T = getFunctionOrMethodArgType(d, I);
337      if (T->isAnyPointerType() || T->isBlockPointerType())
338        NonNullArgs.push_back(I);
339    }
340
341    if (NonNullArgs.empty()) {
342      S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
343      return;
344    }
345  }
346
347  unsigned* start = &NonNullArgs[0];
348  unsigned size = NonNullArgs.size();
349  std::sort(start, start + size);
350  d->addAttr(::new (S.Context) NonNullAttr(S.Context, start, size));
351}
352
353static bool isStaticVarOrStaticFunciton(Decl *D) {
354  if (VarDecl *VD = dyn_cast<VarDecl>(D))
355    return VD->getStorageClass() == VarDecl::Static;
356  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
357    return FD->getStorageClass() == FunctionDecl::Static;
358  return false;
359}
360
361static void HandleWeakRefAttr(Decl *d, const AttributeList &Attr, Sema &S) {
362  // Check the attribute arguments.
363  if (Attr.getNumArgs() > 1) {
364    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
365    return;
366  }
367
368  // gcc rejects
369  // class c {
370  //   static int a __attribute__((weakref ("v2")));
371  //   static int b() __attribute__((weakref ("f3")));
372  // };
373  // and ignores the attributes of
374  // void f(void) {
375  //   static int a __attribute__((weakref ("v2")));
376  // }
377  // we reject them
378  if (const DeclContext *Ctx = d->getDeclContext()) {
379    Ctx = Ctx->getLookupContext();
380    if (!isa<TranslationUnitDecl>(Ctx) && !isa<NamespaceDecl>(Ctx) ) {
381      S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
382	dyn_cast<NamedDecl>(d)->getNameAsString();
383      return;
384    }
385  }
386
387  // The GCC manual says
388  //
389  // At present, a declaration to which `weakref' is attached can only
390  // be `static'.
391  //
392  // It also says
393  //
394  // Without a TARGET,
395  // given as an argument to `weakref' or to `alias', `weakref' is
396  // equivalent to `weak'.
397  //
398  // gcc 4.4.1 will accept
399  // int a7 __attribute__((weakref));
400  // as
401  // int a7 __attribute__((weak));
402  // This looks like a bug in gcc. We reject that for now. We should revisit
403  // it if this behaviour is actually used.
404
405  if (!isStaticVarOrStaticFunciton(d)) {
406    S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_static) <<
407      dyn_cast<NamedDecl>(d)->getNameAsString();
408    return;
409  }
410
411  // GCC rejects
412  // static ((alias ("y"), weakref)).
413  // Should we? How to check that weakref is before or after alias?
414
415  if (Attr.getNumArgs() == 1) {
416    Expr *Arg = static_cast<Expr*>(Attr.getArg(0));
417    Arg = Arg->IgnoreParenCasts();
418    StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
419
420    if (Str == 0 || Str->isWide()) {
421      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
422          << "weakref" << 1;
423      return;
424    }
425    // GCC will accept anything as the argument of weakref. Should we
426    // check for an existing decl?
427    d->addAttr(::new (S.Context) AliasAttr(S.Context, Str->getString()));
428  }
429
430  d->addAttr(::new (S.Context) WeakRefAttr());
431}
432
433static void HandleAliasAttr(Decl *d, const AttributeList &Attr, Sema &S) {
434  // check the attribute arguments.
435  if (Attr.getNumArgs() != 1) {
436    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
437    return;
438  }
439
440  Expr *Arg = static_cast<Expr*>(Attr.getArg(0));
441  Arg = Arg->IgnoreParenCasts();
442  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
443
444  if (Str == 0 || Str->isWide()) {
445    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
446      << "alias" << 1;
447    return;
448  }
449
450  // FIXME: check if target symbol exists in current file
451
452  d->addAttr(::new (S.Context) AliasAttr(S.Context, Str->getString()));
453}
454
455static void HandleAlwaysInlineAttr(Decl *d, const AttributeList &Attr,
456                                   Sema &S) {
457  // check the attribute arguments.
458  if (Attr.getNumArgs() != 0) {
459    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
460    return;
461  }
462
463  if (!isa<FunctionDecl>(d)) {
464    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
465    << Attr.getName() << 0 /*function*/;
466    return;
467  }
468
469  d->addAttr(::new (S.Context) AlwaysInlineAttr());
470}
471
472static void HandleMallocAttr(Decl *d, const AttributeList &Attr, Sema &S) {
473  // check the attribute arguments.
474  if (Attr.getNumArgs() != 0) {
475    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
476    return;
477  }
478
479  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
480    QualType RetTy = FD->getResultType();
481    if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
482      d->addAttr(::new (S.Context) MallocAttr());
483      return;
484    }
485  }
486
487  S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
488}
489
490static bool HandleCommonNoReturnAttr(Decl *d, const AttributeList &Attr,
491                                     Sema &S) {
492  // check the attribute arguments.
493  if (Attr.getNumArgs() != 0) {
494    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
495    return false;
496  }
497
498  if (!isFunctionOrMethod(d) && !isa<BlockDecl>(d)) {
499    ValueDecl *VD = dyn_cast<ValueDecl>(d);
500    if (VD == 0 || (!VD->getType()->isBlockPointerType()
501                    && !VD->getType()->isFunctionPointerType())) {
502      S.Diag(Attr.getLoc(),
503             Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
504                                     : diag::warn_attribute_wrong_decl_type)
505        << Attr.getName() << 0 /*function*/;
506      return false;
507    }
508  }
509
510  return true;
511}
512
513static void HandleNoReturnAttr(Decl *d, const AttributeList &Attr, Sema &S) {
514  /* Diagnostics (if any) was emitted by Sema::ProcessFnAttr(). */
515  assert(Attr.isInvalid() == false);
516  d->addAttr(::new (S.Context) NoReturnAttr());
517}
518
519static void HandleAnalyzerNoReturnAttr(Decl *d, const AttributeList &Attr,
520                                       Sema &S) {
521  if (HandleCommonNoReturnAttr(d, Attr, S))
522    d->addAttr(::new (S.Context) AnalyzerNoReturnAttr());
523}
524
525static void HandleDependencyAttr(Decl *d, const AttributeList &Attr, Sema &S) {
526  if (!isFunctionOrMethod(d) && !isa<ParmVarDecl>(d)) {
527    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
528      << Attr.getName() << 8 /*function, method, or parameter*/;
529    return;
530  }
531  // FIXME: Actually store the attribute on the declaration
532}
533
534static void HandleUnusedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
535  // check the attribute arguments.
536  if (Attr.getNumArgs() != 0) {
537    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
538    return;
539  }
540
541  if (!isa<VarDecl>(d) && !isa<ObjCIvarDecl>(d) && !isFunctionOrMethod(d) &&
542      !isa<TypeDecl>(d)) {
543    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
544      << Attr.getName() << 2 /*variable and function*/;
545    return;
546  }
547
548  d->addAttr(::new (S.Context) UnusedAttr());
549}
550
551static void HandleUsedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
552  // check the attribute arguments.
553  if (Attr.getNumArgs() != 0) {
554    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
555    return;
556  }
557
558  if (const VarDecl *VD = dyn_cast<VarDecl>(d)) {
559    if (VD->hasLocalStorage() || VD->hasExternalStorage()) {
560      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
561      return;
562    }
563  } else if (!isFunctionOrMethod(d)) {
564    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
565      << Attr.getName() << 2 /*variable and function*/;
566    return;
567  }
568
569  d->addAttr(::new (S.Context) UsedAttr());
570}
571
572static void HandleConstructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
573  // check the attribute arguments.
574  if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
575    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
576      << "0 or 1";
577    return;
578  }
579
580  int priority = 65535; // FIXME: Do not hardcode such constants.
581  if (Attr.getNumArgs() > 0) {
582    Expr *E = static_cast<Expr *>(Attr.getArg(0));
583    llvm::APSInt Idx(32);
584    if (E->isTypeDependent() || E->isValueDependent() ||
585        !E->isIntegerConstantExpr(Idx, S.Context)) {
586      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
587        << "constructor" << 1 << E->getSourceRange();
588      return;
589    }
590    priority = Idx.getZExtValue();
591  }
592
593  if (!isa<FunctionDecl>(d)) {
594    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
595      << Attr.getName() << 0 /*function*/;
596    return;
597  }
598
599  d->addAttr(::new (S.Context) ConstructorAttr(priority));
600}
601
602static void HandleDestructorAttr(Decl *d, const AttributeList &Attr, Sema &S) {
603  // check the attribute arguments.
604  if (Attr.getNumArgs() != 0 && Attr.getNumArgs() != 1) {
605    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
606       << "0 or 1";
607    return;
608  }
609
610  int priority = 65535; // FIXME: Do not hardcode such constants.
611  if (Attr.getNumArgs() > 0) {
612    Expr *E = static_cast<Expr *>(Attr.getArg(0));
613    llvm::APSInt Idx(32);
614    if (E->isTypeDependent() || E->isValueDependent() ||
615        !E->isIntegerConstantExpr(Idx, S.Context)) {
616      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
617        << "destructor" << 1 << E->getSourceRange();
618      return;
619    }
620    priority = Idx.getZExtValue();
621  }
622
623  if (!isa<FunctionDecl>(d)) {
624    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
625      << Attr.getName() << 0 /*function*/;
626    return;
627  }
628
629  d->addAttr(::new (S.Context) DestructorAttr(priority));
630}
631
632static void HandleDeprecatedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
633  // check the attribute arguments.
634  if (Attr.getNumArgs() != 0) {
635    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
636    return;
637  }
638
639  d->addAttr(::new (S.Context) DeprecatedAttr());
640}
641
642static void HandleUnavailableAttr(Decl *d, const AttributeList &Attr, Sema &S) {
643  // check the attribute arguments.
644  if (Attr.getNumArgs() != 0) {
645    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
646    return;
647  }
648
649  d->addAttr(::new (S.Context) UnavailableAttr());
650}
651
652static void HandleVisibilityAttr(Decl *d, const AttributeList &Attr, Sema &S) {
653  // check the attribute arguments.
654  if (Attr.getNumArgs() != 1) {
655    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
656    return;
657  }
658
659  Expr *Arg = static_cast<Expr*>(Attr.getArg(0));
660  Arg = Arg->IgnoreParenCasts();
661  StringLiteral *Str = dyn_cast<StringLiteral>(Arg);
662
663  if (Str == 0 || Str->isWide()) {
664    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
665      << "visibility" << 1;
666    return;
667  }
668
669  llvm::StringRef TypeStr = Str->getString();
670  VisibilityAttr::VisibilityTypes type;
671
672  if (TypeStr == "default")
673    type = VisibilityAttr::DefaultVisibility;
674  else if (TypeStr == "hidden")
675    type = VisibilityAttr::HiddenVisibility;
676  else if (TypeStr == "internal")
677    type = VisibilityAttr::HiddenVisibility; // FIXME
678  else if (TypeStr == "protected")
679    type = VisibilityAttr::ProtectedVisibility;
680  else {
681    S.Diag(Attr.getLoc(), diag::warn_attribute_unknown_visibility) << TypeStr;
682    return;
683  }
684
685  d->addAttr(::new (S.Context) VisibilityAttr(type));
686}
687
688static void HandleObjCExceptionAttr(Decl *D, const AttributeList &Attr,
689                                    Sema &S) {
690  if (Attr.getNumArgs() != 0) {
691    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
692    return;
693  }
694
695  ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
696  if (OCI == 0) {
697    S.Diag(Attr.getLoc(), diag::err_attribute_requires_objc_interface);
698    return;
699  }
700
701  D->addAttr(::new (S.Context) ObjCExceptionAttr());
702}
703
704static void HandleObjCNSObject(Decl *D, const AttributeList &Attr, Sema &S) {
705  if (Attr.getNumArgs() != 0) {
706    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
707    return;
708  }
709  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
710    QualType T = TD->getUnderlyingType();
711    if (!T->isPointerType() ||
712        !T->getAs<PointerType>()->getPointeeType()->isRecordType()) {
713      S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
714      return;
715    }
716  }
717  D->addAttr(::new (S.Context) ObjCNSObjectAttr());
718}
719
720static void
721HandleOverloadableAttr(Decl *D, const AttributeList &Attr, Sema &S) {
722  if (Attr.getNumArgs() != 0) {
723    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
724    return;
725  }
726
727  if (!isa<FunctionDecl>(D)) {
728    S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
729    return;
730  }
731
732  D->addAttr(::new (S.Context) OverloadableAttr());
733}
734
735static void HandleADLInvisibleAttr(Decl *d, const AttributeList &Attr, Sema &S) {
736  if (Attr.getNumArgs() != 0) {
737    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
738    return;
739  }
740
741  if (!isa<RecordDecl>(d)) {
742    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
743      << "adl_invisible" << 12;
744    return;
745  }
746
747  cast<RecordDecl>(d)->setInvisibleToADL();
748}
749
750static void HandleBlocksAttr(Decl *d, const AttributeList &Attr, Sema &S) {
751  if (!Attr.getParameterName()) {
752    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
753      << "blocks" << 1;
754    return;
755  }
756
757  if (Attr.getNumArgs() != 0) {
758    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
759    return;
760  }
761
762  BlocksAttr::BlocksAttrTypes type;
763  if (Attr.getParameterName()->isStr("byref"))
764    type = BlocksAttr::ByRef;
765  else {
766    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
767      << "blocks" << Attr.getParameterName();
768    return;
769  }
770
771  d->addAttr(::new (S.Context) BlocksAttr(type));
772}
773
774static void HandleSentinelAttr(Decl *d, const AttributeList &Attr, Sema &S) {
775  // check the attribute arguments.
776  if (Attr.getNumArgs() > 2) {
777    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
778      << "0, 1 or 2";
779    return;
780  }
781
782  int sentinel = 0;
783  if (Attr.getNumArgs() > 0) {
784    Expr *E = static_cast<Expr *>(Attr.getArg(0));
785    llvm::APSInt Idx(32);
786    if (E->isTypeDependent() || E->isValueDependent() ||
787        !E->isIntegerConstantExpr(Idx, S.Context)) {
788      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
789       << "sentinel" << 1 << E->getSourceRange();
790      return;
791    }
792    sentinel = Idx.getZExtValue();
793
794    if (sentinel < 0) {
795      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
796        << E->getSourceRange();
797      return;
798    }
799  }
800
801  int nullPos = 0;
802  if (Attr.getNumArgs() > 1) {
803    Expr *E = static_cast<Expr *>(Attr.getArg(1));
804    llvm::APSInt Idx(32);
805    if (E->isTypeDependent() || E->isValueDependent() ||
806        !E->isIntegerConstantExpr(Idx, S.Context)) {
807      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
808        << "sentinel" << 2 << E->getSourceRange();
809      return;
810    }
811    nullPos = Idx.getZExtValue();
812
813    if (nullPos > 1 || nullPos < 0) {
814      // FIXME: This error message could be improved, it would be nice
815      // to say what the bounds actually are.
816      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
817        << E->getSourceRange();
818      return;
819    }
820  }
821
822  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d)) {
823    const FunctionType *FT = FD->getType()->getAs<FunctionType>();
824    assert(FT && "FunctionDecl has non-function type?");
825
826    if (isa<FunctionNoProtoType>(FT)) {
827      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
828      return;
829    }
830
831    if (!cast<FunctionProtoType>(FT)->isVariadic()) {
832      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
833      return;
834    }
835  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d)) {
836    if (!MD->isVariadic()) {
837      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
838      return;
839    }
840  } else if (isa<BlockDecl>(d)) {
841    // Note! BlockDecl is typeless. Variadic diagnostics will be issued by the
842    // caller.
843    ;
844  } else if (const VarDecl *V = dyn_cast<VarDecl>(d)) {
845    QualType Ty = V->getType();
846    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
847      const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(d)
848        : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
849      if (!cast<FunctionProtoType>(FT)->isVariadic()) {
850        int m = Ty->isFunctionPointerType() ? 0 : 1;
851        S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
852        return;
853      }
854    } else {
855      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
856      << Attr.getName() << 6 /*function, method or block */;
857      return;
858    }
859  } else {
860    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
861      << Attr.getName() << 6 /*function, method or block */;
862    return;
863  }
864  d->addAttr(::new (S.Context) SentinelAttr(sentinel, nullPos));
865}
866
867static void HandleWarnUnusedResult(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;
872  }
873
874  if (!isFunction(D) && !isa<ObjCMethodDecl>(D)) {
875    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
876      << Attr.getName() << 0 /*function*/;
877    return;
878  }
879
880  if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
881    S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
882      << Attr.getName() << 0;
883    return;
884  }
885  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
886    if (MD->getResultType()->isVoidType()) {
887      S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
888      << Attr.getName() << 1;
889      return;
890    }
891
892  D->addAttr(::new (S.Context) WarnUnusedResultAttr());
893}
894
895static void HandleWeakAttr(Decl *D, const AttributeList &Attr, Sema &S) {
896  // check the attribute arguments.
897  if (Attr.getNumArgs() != 0) {
898    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
899    return;
900  }
901
902  /* weak only applies to non-static declarations */
903  if (isStaticVarOrStaticFunciton(D)) {
904    S.Diag(Attr.getLoc(), diag::err_attribute_weak_static) <<
905      dyn_cast<NamedDecl>(D)->getNameAsString();
906    return;
907  }
908
909  // TODO: could also be applied to methods?
910  if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
911    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
912      << Attr.getName() << 2 /*variable and function*/;
913    return;
914  }
915
916  D->addAttr(::new (S.Context) WeakAttr());
917}
918
919static void HandleWeakImportAttr(Decl *D, const AttributeList &Attr, Sema &S) {
920  // check the attribute arguments.
921  if (Attr.getNumArgs() != 0) {
922    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
923    return;
924  }
925
926  // weak_import only applies to variable & function declarations.
927  bool isDef = false;
928  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
929    isDef = (!VD->hasExternalStorage() || VD->getInit());
930  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
931    isDef = FD->getBody();
932  } else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D)) {
933    // We ignore weak import on properties and methods
934    return;
935  } else if (!(S.LangOpts.ObjCNonFragileABI && isa<ObjCInterfaceDecl>(D))) {
936    // Don't issue the warning for darwin as target; yet, ignore the attribute.
937    if (S.Context.Target.getTriple().getOS() != llvm::Triple::Darwin ||
938        !isa<ObjCInterfaceDecl>(D))
939      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
940        << Attr.getName() << 2 /*variable and function*/;
941      return;
942  }
943
944  // Merge should handle any subsequent violations.
945  if (isDef) {
946    S.Diag(Attr.getLoc(),
947           diag::warn_attribute_weak_import_invalid_on_definition)
948      << "weak_import" << 2 /*variable and function*/;
949    return;
950  }
951
952  D->addAttr(::new (S.Context) WeakImportAttr());
953}
954
955static void HandleReqdWorkGroupSize(Decl *D, const AttributeList &Attr,
956                                    Sema &S) {
957  // Attribute has 3 arguments.
958  if (Attr.getNumArgs() != 3) {
959    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
960    return;
961  }
962
963  unsigned WGSize[3];
964  for (unsigned i = 0; i < 3; ++i) {
965    Expr *E = static_cast<Expr *>(Attr.getArg(i));
966    llvm::APSInt ArgNum(32);
967    if (E->isTypeDependent() || E->isValueDependent() ||
968        !E->isIntegerConstantExpr(ArgNum, S.Context)) {
969      S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
970        << "reqd_work_group_size" << E->getSourceRange();
971      return;
972    }
973    WGSize[i] = (unsigned) ArgNum.getZExtValue();
974  }
975  D->addAttr(::new (S.Context) ReqdWorkGroupSizeAttr(WGSize[0], WGSize[1],
976                                                     WGSize[2]));
977}
978
979static void HandleSectionAttr(Decl *D, const AttributeList &Attr, Sema &S) {
980  // Attribute has no arguments.
981  if (Attr.getNumArgs() != 1) {
982    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
983    return;
984  }
985
986  // Make sure that there is a string literal as the sections's single
987  // argument.
988  Expr *ArgExpr = static_cast<Expr *>(Attr.getArg(0));
989  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
990  if (!SE) {
991    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) << "section";
992    return;
993  }
994
995  // If the target wants to validate the section specifier, make it happen.
996  std::string Error = S.Context.Target.isValidSectionSpecifier(SE->getString());
997  if (!Error.empty()) {
998    S.Diag(SE->getLocStart(), diag::err_attribute_section_invalid_for_target)
999    << Error;
1000    return;
1001  }
1002
1003  // This attribute cannot be applied to local variables.
1004  if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
1005    S.Diag(SE->getLocStart(), diag::err_attribute_section_local_variable);
1006    return;
1007  }
1008
1009  D->addAttr(::new (S.Context) SectionAttr(S.Context, SE->getString()));
1010}
1011
1012
1013static void HandleNothrowAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1014  // check the attribute arguments.
1015  if (Attr.getNumArgs() != 0) {
1016    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1017    return;
1018  }
1019
1020  d->addAttr(::new (S.Context) NoThrowAttr());
1021}
1022
1023static void HandleConstAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1024  // check the attribute arguments.
1025  if (Attr.getNumArgs() != 0) {
1026    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1027    return;
1028  }
1029
1030  d->addAttr(::new (S.Context) ConstAttr());
1031}
1032
1033static void HandlePureAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1034  // check the attribute arguments.
1035  if (Attr.getNumArgs() != 0) {
1036    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1037    return;
1038  }
1039
1040  d->addAttr(::new (S.Context) PureAttr());
1041}
1042
1043static void HandleCleanupAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1044  if (!Attr.getParameterName()) {
1045    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1046    return;
1047  }
1048
1049  if (Attr.getNumArgs() != 0) {
1050    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1051    return;
1052  }
1053
1054  VarDecl *VD = dyn_cast<VarDecl>(d);
1055
1056  if (!VD || !VD->hasLocalStorage()) {
1057    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "cleanup";
1058    return;
1059  }
1060
1061  // Look up the function
1062  // FIXME: Lookup probably isn't looking in the right place
1063  // FIXME: The lookup source location should be in the attribute, not the
1064  // start of the attribute.
1065  NamedDecl *CleanupDecl
1066    = S.LookupSingleName(S.TUScope, Attr.getParameterName(), Attr.getLoc(),
1067                         Sema::LookupOrdinaryName);
1068  if (!CleanupDecl) {
1069    S.Diag(Attr.getLoc(), diag::err_attribute_cleanup_arg_not_found) <<
1070      Attr.getParameterName();
1071    return;
1072  }
1073
1074  FunctionDecl *FD = dyn_cast<FunctionDecl>(CleanupDecl);
1075  if (!FD) {
1076    S.Diag(Attr.getLoc(), diag::err_attribute_cleanup_arg_not_function) <<
1077      Attr.getParameterName();
1078    return;
1079  }
1080
1081  if (FD->getNumParams() != 1) {
1082    S.Diag(Attr.getLoc(), diag::err_attribute_cleanup_func_must_take_one_arg) <<
1083      Attr.getParameterName();
1084    return;
1085  }
1086
1087  // We're currently more strict than GCC about what function types we accept.
1088  // If this ever proves to be a problem it should be easy to fix.
1089  QualType Ty = S.Context.getPointerType(VD->getType());
1090  QualType ParamTy = FD->getParamDecl(0)->getType();
1091  if (S.CheckAssignmentConstraints(ParamTy, Ty) != Sema::Compatible) {
1092    S.Diag(Attr.getLoc(),
1093           diag::err_attribute_cleanup_func_arg_incompatible_type) <<
1094      Attr.getParameterName() << ParamTy << Ty;
1095    return;
1096  }
1097
1098  d->addAttr(::new (S.Context) CleanupAttr(FD));
1099}
1100
1101/// Handle __attribute__((format_arg((idx)))) attribute based on
1102/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1103static void HandleFormatArgAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1104  if (Attr.getNumArgs() != 1) {
1105    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1106    return;
1107  }
1108  if (!isFunctionOrMethod(d) || !hasFunctionProto(d)) {
1109    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1110    << Attr.getName() << 0 /*function*/;
1111    return;
1112  }
1113  // FIXME: in C++ the implicit 'this' function parameter also counts.  this is
1114  // needed in order to be compatible with GCC the index must start with 1.
1115  unsigned NumArgs  = getFunctionOrMethodNumArgs(d);
1116  unsigned FirstIdx = 1;
1117  // checks for the 2nd argument
1118  Expr *IdxExpr = static_cast<Expr *>(Attr.getArg(0));
1119  llvm::APSInt Idx(32);
1120  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1121      !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1122    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1123    << "format" << 2 << IdxExpr->getSourceRange();
1124    return;
1125  }
1126
1127  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1128    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1129    << "format" << 2 << IdxExpr->getSourceRange();
1130    return;
1131  }
1132
1133  unsigned ArgIdx = Idx.getZExtValue() - 1;
1134
1135  // make sure the format string is really a string
1136  QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1137
1138  bool not_nsstring_type = !isNSStringType(Ty, S.Context);
1139  if (not_nsstring_type &&
1140      !isCFStringType(Ty, S.Context) &&
1141      (!Ty->isPointerType() ||
1142       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1143    // FIXME: Should highlight the actual expression that has the wrong type.
1144    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1145    << (not_nsstring_type ? "a string type" : "an NSString")
1146       << IdxExpr->getSourceRange();
1147    return;
1148  }
1149  Ty = getFunctionOrMethodResultType(d);
1150  if (!isNSStringType(Ty, S.Context) &&
1151      !isCFStringType(Ty, S.Context) &&
1152      (!Ty->isPointerType() ||
1153       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
1154    // FIXME: Should highlight the actual expression that has the wrong type.
1155    S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
1156    << (not_nsstring_type ? "string type" : "NSString")
1157       << IdxExpr->getSourceRange();
1158    return;
1159  }
1160
1161  d->addAttr(::new (S.Context) FormatArgAttr(Idx.getZExtValue()));
1162}
1163
1164enum FormatAttrKind {
1165  CFStringFormat,
1166  NSStringFormat,
1167  StrftimeFormat,
1168  SupportedFormat,
1169  IgnoredFormat,
1170  InvalidFormat
1171};
1172
1173/// getFormatAttrKind - Map from format attribute names to supported format
1174/// types.
1175static FormatAttrKind getFormatAttrKind(llvm::StringRef Format) {
1176  // Check for formats that get handled specially.
1177  if (Format == "NSString")
1178    return NSStringFormat;
1179  if (Format == "CFString")
1180    return CFStringFormat;
1181  if (Format == "strftime")
1182    return StrftimeFormat;
1183
1184  // Otherwise, check for supported formats.
1185  if (Format == "scanf" || Format == "printf" || Format == "printf0" ||
1186      Format == "strfmon" || Format == "cmn_err" || Format == "strftime" ||
1187      Format == "NSString" || Format == "CFString" || Format == "vcmn_err" ||
1188      Format == "zcmn_err")
1189    return SupportedFormat;
1190
1191  if (Format == "gcc_diag" || Format == "gcc_cdiag" ||
1192      Format == "gcc_cxxdiag" || Format == "gcc_tdiag")
1193    return IgnoredFormat;
1194
1195  return InvalidFormat;
1196}
1197
1198/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
1199/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
1200static void HandleFormatAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1201
1202  if (!Attr.getParameterName()) {
1203    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1204      << "format" << 1;
1205    return;
1206  }
1207
1208  if (Attr.getNumArgs() != 2) {
1209    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 3;
1210    return;
1211  }
1212
1213  if (!isFunctionOrMethodOrBlock(d) || !hasFunctionProto(d)) {
1214    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1215      << Attr.getName() << 0 /*function*/;
1216    return;
1217  }
1218
1219  unsigned NumArgs  = getFunctionOrMethodNumArgs(d);
1220  unsigned FirstIdx = 1;
1221
1222  llvm::StringRef Format = Attr.getParameterName()->getName();
1223
1224  // Normalize the argument, __foo__ becomes foo.
1225  if (Format.startswith("__") && Format.endswith("__"))
1226    Format = Format.substr(2, Format.size() - 4);
1227
1228  // Check for supported formats.
1229  FormatAttrKind Kind = getFormatAttrKind(Format);
1230
1231  if (Kind == IgnoredFormat)
1232    return;
1233
1234  if (Kind == InvalidFormat) {
1235    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1236      << "format" << Attr.getParameterName()->getName();
1237    return;
1238  }
1239
1240  // checks for the 2nd argument
1241  Expr *IdxExpr = static_cast<Expr *>(Attr.getArg(0));
1242  llvm::APSInt Idx(32);
1243  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
1244      !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
1245    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1246      << "format" << 2 << IdxExpr->getSourceRange();
1247    return;
1248  }
1249
1250  // FIXME: We should handle the implicit 'this' parameter in a more generic
1251  // way that can be used for other arguments.
1252  bool HasImplicitThisParam = false;
1253  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(d)) {
1254    if (MD->isInstance()) {
1255      HasImplicitThisParam = true;
1256      NumArgs++;
1257    }
1258  }
1259
1260  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
1261    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1262      << "format" << 2 << IdxExpr->getSourceRange();
1263    return;
1264  }
1265
1266  // FIXME: Do we need to bounds check?
1267  unsigned ArgIdx = Idx.getZExtValue() - 1;
1268
1269  if (HasImplicitThisParam) {
1270    if (ArgIdx == 0) {
1271      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1272        << "a string type" << IdxExpr->getSourceRange();
1273      return;
1274    }
1275    ArgIdx--;
1276  }
1277
1278  // make sure the format string is really a string
1279  QualType Ty = getFunctionOrMethodArgType(d, ArgIdx);
1280
1281  if (Kind == CFStringFormat) {
1282    if (!isCFStringType(Ty, S.Context)) {
1283      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1284        << "a CFString" << IdxExpr->getSourceRange();
1285      return;
1286    }
1287  } else if (Kind == NSStringFormat) {
1288    // FIXME: do we need to check if the type is NSString*?  What are the
1289    // semantics?
1290    if (!isNSStringType(Ty, S.Context)) {
1291      // FIXME: Should highlight the actual expression that has the wrong type.
1292      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1293        << "an NSString" << IdxExpr->getSourceRange();
1294      return;
1295    }
1296  } else if (!Ty->isPointerType() ||
1297             !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
1298    // FIXME: Should highlight the actual expression that has the wrong type.
1299    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
1300      << "a string type" << IdxExpr->getSourceRange();
1301    return;
1302  }
1303
1304  // check the 3rd argument
1305  Expr *FirstArgExpr = static_cast<Expr *>(Attr.getArg(1));
1306  llvm::APSInt FirstArg(32);
1307  if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
1308      !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
1309    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_int)
1310      << "format" << 3 << FirstArgExpr->getSourceRange();
1311    return;
1312  }
1313
1314  // check if the function is variadic if the 3rd argument non-zero
1315  if (FirstArg != 0) {
1316    if (isFunctionOrMethodVariadic(d)) {
1317      ++NumArgs; // +1 for ...
1318    } else {
1319      S.Diag(d->getLocation(), diag::err_format_attribute_requires_variadic);
1320      return;
1321    }
1322  }
1323
1324  // strftime requires FirstArg to be 0 because it doesn't read from any
1325  // variable the input is just the current time + the format string.
1326  if (Kind == StrftimeFormat) {
1327    if (FirstArg != 0) {
1328      S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
1329        << FirstArgExpr->getSourceRange();
1330      return;
1331    }
1332  // if 0 it disables parameter checking (to use with e.g. va_list)
1333  } else if (FirstArg != 0 && FirstArg != NumArgs) {
1334    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
1335      << "format" << 3 << FirstArgExpr->getSourceRange();
1336    return;
1337  }
1338
1339  d->addAttr(::new (S.Context) FormatAttr(S.Context, Format, Idx.getZExtValue(),
1340                                          FirstArg.getZExtValue()));
1341}
1342
1343static void HandleTransparentUnionAttr(Decl *d, const AttributeList &Attr,
1344                                       Sema &S) {
1345  // check the attribute arguments.
1346  if (Attr.getNumArgs() != 0) {
1347    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1348    return;
1349  }
1350
1351  // Try to find the underlying union declaration.
1352  RecordDecl *RD = 0;
1353  TypedefDecl *TD = dyn_cast<TypedefDecl>(d);
1354  if (TD && TD->getUnderlyingType()->isUnionType())
1355    RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
1356  else
1357    RD = dyn_cast<RecordDecl>(d);
1358
1359  if (!RD || !RD->isUnion()) {
1360    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1361      << Attr.getName() << 1 /*union*/;
1362    return;
1363  }
1364
1365  if (!RD->isDefinition()) {
1366    S.Diag(Attr.getLoc(),
1367        diag::warn_transparent_union_attribute_not_definition);
1368    return;
1369  }
1370
1371  RecordDecl::field_iterator Field = RD->field_begin(),
1372                          FieldEnd = RD->field_end();
1373  if (Field == FieldEnd) {
1374    S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
1375    return;
1376  }
1377
1378  FieldDecl *FirstField = *Field;
1379  QualType FirstType = FirstField->getType();
1380  if (FirstType->isFloatingType() || FirstType->isVectorType()) {
1381    S.Diag(FirstField->getLocation(),
1382           diag::warn_transparent_union_attribute_floating);
1383    return;
1384  }
1385
1386  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
1387  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
1388  for (; Field != FieldEnd; ++Field) {
1389    QualType FieldType = Field->getType();
1390    if (S.Context.getTypeSize(FieldType) != FirstSize ||
1391        S.Context.getTypeAlign(FieldType) != FirstAlign) {
1392      // Warn if we drop the attribute.
1393      bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
1394      unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
1395                                 : S.Context.getTypeAlign(FieldType);
1396      S.Diag(Field->getLocation(),
1397          diag::warn_transparent_union_attribute_field_size_align)
1398        << isSize << Field->getDeclName() << FieldBits;
1399      unsigned FirstBits = isSize? FirstSize : FirstAlign;
1400      S.Diag(FirstField->getLocation(),
1401             diag::note_transparent_union_first_field_size_align)
1402        << isSize << FirstBits;
1403      return;
1404    }
1405  }
1406
1407  RD->addAttr(::new (S.Context) TransparentUnionAttr());
1408}
1409
1410static void HandleAnnotateAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1411  // check the attribute arguments.
1412  if (Attr.getNumArgs() != 1) {
1413    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1414    return;
1415  }
1416  Expr *ArgExpr = static_cast<Expr *>(Attr.getArg(0));
1417  StringLiteral *SE = dyn_cast<StringLiteral>(ArgExpr);
1418
1419  // Make sure that there is a string literal as the annotation's single
1420  // argument.
1421  if (!SE) {
1422    S.Diag(ArgExpr->getLocStart(), diag::err_attribute_not_string) <<"annotate";
1423    return;
1424  }
1425  d->addAttr(::new (S.Context) AnnotateAttr(S.Context, SE->getString()));
1426}
1427
1428static void HandleAlignedAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1429  // check the attribute arguments.
1430  if (Attr.getNumArgs() > 1) {
1431    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1432    return;
1433  }
1434
1435  //FIXME: The C++0x version of this attribute has more limited applicabilty
1436  //       than GNU's, and should error out when it is used to specify a
1437  //       weaker alignment, rather than being silently ignored.
1438
1439  unsigned Align = 0;
1440  if (Attr.getNumArgs() == 0) {
1441    // FIXME: This should be the target specific maximum alignment.
1442    // (For now we just use 128 bits which is the maximum on X86).
1443    Align = 128;
1444    d->addAttr(::new (S.Context) AlignedAttr(Align));
1445    return;
1446  }
1447
1448  Expr *alignmentExpr = static_cast<Expr *>(Attr.getArg(0));
1449  llvm::APSInt Alignment(32);
1450  if (alignmentExpr->isTypeDependent() || alignmentExpr->isValueDependent() ||
1451      !alignmentExpr->isIntegerConstantExpr(Alignment, S.Context)) {
1452    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1453      << "aligned" << alignmentExpr->getSourceRange();
1454    return;
1455  }
1456  if (!llvm::isPowerOf2_64(Alignment.getZExtValue())) {
1457    S.Diag(Attr.getLoc(), diag::err_attribute_aligned_not_power_of_two)
1458      << alignmentExpr->getSourceRange();
1459    return;
1460  }
1461
1462  d->addAttr(::new (S.Context) AlignedAttr(Alignment.getZExtValue() * 8));
1463}
1464
1465/// HandleModeAttr - This attribute modifies the width of a decl with primitive
1466/// type.
1467///
1468/// Despite what would be logical, the mode attribute is a decl attribute, not a
1469/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
1470/// HImode, not an intermediate pointer.
1471static void HandleModeAttr(Decl *D, const AttributeList &Attr, Sema &S) {
1472  // This attribute isn't documented, but glibc uses it.  It changes
1473  // the width of an int or unsigned int to the specified size.
1474
1475  // Check that there aren't any arguments
1476  if (Attr.getNumArgs() != 0) {
1477    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1478    return;
1479  }
1480
1481  IdentifierInfo *Name = Attr.getParameterName();
1482  if (!Name) {
1483    S.Diag(Attr.getLoc(), diag::err_attribute_missing_parameter_name);
1484    return;
1485  }
1486
1487  llvm::StringRef Str = Attr.getParameterName()->getName();
1488
1489  // Normalize the attribute name, __foo__ becomes foo.
1490  if (Str.startswith("__") && Str.endswith("__"))
1491    Str = Str.substr(2, Str.size() - 4);
1492
1493  unsigned DestWidth = 0;
1494  bool IntegerMode = true;
1495  bool ComplexMode = false;
1496  switch (Str.size()) {
1497  case 2:
1498    switch (Str[0]) {
1499    case 'Q': DestWidth = 8; break;
1500    case 'H': DestWidth = 16; break;
1501    case 'S': DestWidth = 32; break;
1502    case 'D': DestWidth = 64; break;
1503    case 'X': DestWidth = 96; break;
1504    case 'T': DestWidth = 128; break;
1505    }
1506    if (Str[1] == 'F') {
1507      IntegerMode = false;
1508    } else if (Str[1] == 'C') {
1509      IntegerMode = false;
1510      ComplexMode = true;
1511    } else if (Str[1] != 'I') {
1512      DestWidth = 0;
1513    }
1514    break;
1515  case 4:
1516    // FIXME: glibc uses 'word' to define register_t; this is narrower than a
1517    // pointer on PIC16 and other embedded platforms.
1518    if (Str == "word")
1519      DestWidth = S.Context.Target.getPointerWidth(0);
1520    else if (Str == "byte")
1521      DestWidth = S.Context.Target.getCharWidth();
1522    break;
1523  case 7:
1524    if (Str == "pointer")
1525      DestWidth = S.Context.Target.getPointerWidth(0);
1526    break;
1527  }
1528
1529  QualType OldTy;
1530  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D))
1531    OldTy = TD->getUnderlyingType();
1532  else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
1533    OldTy = VD->getType();
1534  else {
1535    S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
1536      << "mode" << SourceRange(Attr.getLoc(), Attr.getLoc());
1537    return;
1538  }
1539
1540  if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
1541    S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
1542  else if (IntegerMode) {
1543    if (!OldTy->isIntegralType())
1544      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1545  } else if (ComplexMode) {
1546    if (!OldTy->isComplexType())
1547      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1548  } else {
1549    if (!OldTy->isFloatingType())
1550      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
1551  }
1552
1553  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
1554  // and friends, at least with glibc.
1555  // FIXME: Make sure 32/64-bit integers don't get defined to types of the wrong
1556  // width on unusual platforms.
1557  // FIXME: Make sure floating-point mappings are accurate
1558  // FIXME: Support XF and TF types
1559  QualType NewTy;
1560  switch (DestWidth) {
1561  case 0:
1562    S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
1563    return;
1564  default:
1565    S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1566    return;
1567  case 8:
1568    if (!IntegerMode) {
1569      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1570      return;
1571    }
1572    if (OldTy->isSignedIntegerType())
1573      NewTy = S.Context.SignedCharTy;
1574    else
1575      NewTy = S.Context.UnsignedCharTy;
1576    break;
1577  case 16:
1578    if (!IntegerMode) {
1579      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1580      return;
1581    }
1582    if (OldTy->isSignedIntegerType())
1583      NewTy = S.Context.ShortTy;
1584    else
1585      NewTy = S.Context.UnsignedShortTy;
1586    break;
1587  case 32:
1588    if (!IntegerMode)
1589      NewTy = S.Context.FloatTy;
1590    else if (OldTy->isSignedIntegerType())
1591      NewTy = S.Context.IntTy;
1592    else
1593      NewTy = S.Context.UnsignedIntTy;
1594    break;
1595  case 64:
1596    if (!IntegerMode)
1597      NewTy = S.Context.DoubleTy;
1598    else if (OldTy->isSignedIntegerType())
1599      if (S.Context.Target.getLongWidth() == 64)
1600        NewTy = S.Context.LongTy;
1601      else
1602        NewTy = S.Context.LongLongTy;
1603    else
1604      if (S.Context.Target.getLongWidth() == 64)
1605        NewTy = S.Context.UnsignedLongTy;
1606      else
1607        NewTy = S.Context.UnsignedLongLongTy;
1608    break;
1609  case 96:
1610    NewTy = S.Context.LongDoubleTy;
1611    break;
1612  case 128:
1613    if (!IntegerMode) {
1614      S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
1615      return;
1616    }
1617    if (OldTy->isSignedIntegerType())
1618      NewTy = S.Context.Int128Ty;
1619    else
1620      NewTy = S.Context.UnsignedInt128Ty;
1621    break;
1622  }
1623
1624  if (ComplexMode) {
1625    NewTy = S.Context.getComplexType(NewTy);
1626  }
1627
1628  // Install the new type.
1629  if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1630    // FIXME: preserve existing source info.
1631    TD->setTypeSourceInfo(S.Context.getTrivialTypeSourceInfo(NewTy));
1632  } else
1633    cast<ValueDecl>(D)->setType(NewTy);
1634}
1635
1636static void HandleNoDebugAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1637  // check the attribute arguments.
1638  if (Attr.getNumArgs() > 0) {
1639    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1640    return;
1641  }
1642
1643  if (!isFunctionOrMethod(d)) {
1644    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1645      << Attr.getName() << 0 /*function*/;
1646    return;
1647  }
1648
1649  d->addAttr(::new (S.Context) NoDebugAttr());
1650}
1651
1652static void HandleNoInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1653  // check the attribute arguments.
1654  if (Attr.getNumArgs() != 0) {
1655    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1656    return;
1657  }
1658
1659  if (!isa<FunctionDecl>(d)) {
1660    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1661    << Attr.getName() << 0 /*function*/;
1662    return;
1663  }
1664
1665  d->addAttr(::new (S.Context) NoInlineAttr());
1666}
1667
1668static void HandleGNUInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1669  // check the attribute arguments.
1670  if (Attr.getNumArgs() != 0) {
1671    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1672    return;
1673  }
1674
1675  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
1676  if (Fn == 0) {
1677    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1678      << Attr.getName() << 0 /*function*/;
1679    return;
1680  }
1681
1682  if (!Fn->isInlineSpecified()) {
1683    S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
1684    return;
1685  }
1686
1687  d->addAttr(::new (S.Context) GNUInlineAttr());
1688}
1689
1690static void HandleCallConvAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1691  // Diagnostic is emitted elsewhere: here we store the (valid) Attr
1692  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
1693  assert(Attr.isInvalid() == false);
1694
1695  switch (Attr.getKind()) {
1696  case AttributeList::AT_fastcall:
1697    d->addAttr(::new (S.Context) FastCallAttr());
1698    return;
1699  case AttributeList::AT_stdcall:
1700    d->addAttr(::new (S.Context) StdCallAttr());
1701    return;
1702  case AttributeList::AT_thiscall:
1703    d->addAttr(::new (S.Context) ThisCallAttr());
1704  case AttributeList::AT_cdecl:
1705    d->addAttr(::new (S.Context) CDeclAttr());
1706    return;
1707  default:
1708    llvm_unreachable("unexpected attribute kind");
1709    return;
1710  }
1711}
1712
1713static void HandleRegparmAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1714  // check the attribute arguments.
1715  if (Attr.getNumArgs() != 1) {
1716    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1717    return;
1718  }
1719
1720  if (!isFunctionOrMethod(d)) {
1721    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1722    << Attr.getName() << 0 /*function*/;
1723    return;
1724  }
1725
1726  Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0));
1727  llvm::APSInt NumParams(32);
1728  if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
1729      !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
1730    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
1731      << "regparm" << NumParamsExpr->getSourceRange();
1732    return;
1733  }
1734
1735  if (S.Context.Target.getRegParmMax() == 0) {
1736    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
1737      << NumParamsExpr->getSourceRange();
1738    return;
1739  }
1740
1741  if (NumParams.getLimitedValue(255) > S.Context.Target.getRegParmMax()) {
1742    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
1743      << S.Context.Target.getRegParmMax() << NumParamsExpr->getSourceRange();
1744    return;
1745  }
1746
1747  d->addAttr(::new (S.Context) RegparmAttr(NumParams.getZExtValue()));
1748}
1749
1750static void HandleFinalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1751  // check the attribute arguments.
1752  if (Attr.getNumArgs() != 0) {
1753    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1754    return;
1755  }
1756
1757  if (!isa<CXXRecordDecl>(d)
1758   && (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual())) {
1759    S.Diag(Attr.getLoc(),
1760           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1761                                   : diag::warn_attribute_wrong_decl_type)
1762      << Attr.getName() << 7 /*virtual method or class*/;
1763    return;
1764  }
1765
1766  // FIXME: Conform to C++0x redeclaration rules.
1767
1768  if (d->getAttr<FinalAttr>()) {
1769    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "final";
1770    return;
1771  }
1772
1773  d->addAttr(::new (S.Context) FinalAttr());
1774}
1775
1776//===----------------------------------------------------------------------===//
1777// C++0x member checking attributes
1778//===----------------------------------------------------------------------===//
1779
1780static void HandleBaseCheckAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1781  if (Attr.getNumArgs() != 0) {
1782    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1783    return;
1784  }
1785
1786  if (!isa<CXXRecordDecl>(d)) {
1787    S.Diag(Attr.getLoc(),
1788           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1789                                   : diag::warn_attribute_wrong_decl_type)
1790      << Attr.getName() << 9 /*class*/;
1791    return;
1792  }
1793
1794  if (d->getAttr<BaseCheckAttr>()) {
1795    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "base_check";
1796    return;
1797  }
1798
1799  d->addAttr(::new (S.Context) BaseCheckAttr());
1800}
1801
1802static void HandleHidingAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1803  if (Attr.getNumArgs() != 0) {
1804    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1805    return;
1806  }
1807
1808  if (!isa<RecordDecl>(d->getDeclContext())) {
1809    // FIXME: It's not the type that's the problem
1810    S.Diag(Attr.getLoc(),
1811           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1812                                   : diag::warn_attribute_wrong_decl_type)
1813      << Attr.getName() << 11 /*member*/;
1814    return;
1815  }
1816
1817  // FIXME: Conform to C++0x redeclaration rules.
1818
1819  if (d->getAttr<HidingAttr>()) {
1820    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "hiding";
1821    return;
1822  }
1823
1824  d->addAttr(::new (S.Context) HidingAttr());
1825}
1826
1827static void HandleOverrideAttr(Decl *d, const AttributeList &Attr, Sema &S) {
1828  if (Attr.getNumArgs() != 0) {
1829    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
1830    return;
1831  }
1832
1833  if (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual()) {
1834    // FIXME: It's not the type that's the problem
1835    S.Diag(Attr.getLoc(),
1836           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
1837                                   : diag::warn_attribute_wrong_decl_type)
1838      << Attr.getName() << 10 /*virtual method*/;
1839    return;
1840  }
1841
1842  // FIXME: Conform to C++0x redeclaration rules.
1843
1844  if (d->getAttr<OverrideAttr>()) {
1845    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "override";
1846    return;
1847  }
1848
1849  d->addAttr(::new (S.Context) OverrideAttr());
1850}
1851
1852//===----------------------------------------------------------------------===//
1853// Checker-specific attribute handlers.
1854//===----------------------------------------------------------------------===//
1855
1856static void HandleNSReturnsRetainedAttr(Decl *d, const AttributeList &Attr,
1857                                        Sema &S) {
1858
1859  QualType RetTy;
1860
1861  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
1862    RetTy = MD->getResultType();
1863  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d))
1864    RetTy = FD->getResultType();
1865  else {
1866    SourceLocation L = Attr.getLoc();
1867    S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
1868        << SourceRange(L, L) << Attr.getName() << 3 /* function or method */;
1869    return;
1870  }
1871
1872  if (!(S.Context.isObjCNSObjectType(RetTy) || RetTy->getAs<PointerType>()
1873        || RetTy->getAs<ObjCObjectPointerType>())) {
1874    SourceLocation L = Attr.getLoc();
1875    S.Diag(d->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
1876      << SourceRange(L, L) << Attr.getName();
1877    return;
1878  }
1879
1880  switch (Attr.getKind()) {
1881    default:
1882      assert(0 && "invalid ownership attribute");
1883      return;
1884    case AttributeList::AT_cf_returns_not_retained:
1885      d->addAttr(::new (S.Context) CFReturnsNotRetainedAttr());
1886      return;
1887    case AttributeList::AT_ns_returns_not_retained:
1888      d->addAttr(::new (S.Context) NSReturnsNotRetainedAttr());
1889      return;
1890    case AttributeList::AT_cf_returns_retained:
1891      d->addAttr(::new (S.Context) CFReturnsRetainedAttr());
1892      return;
1893    case AttributeList::AT_ns_returns_retained:
1894      d->addAttr(::new (S.Context) NSReturnsRetainedAttr());
1895      return;
1896  };
1897}
1898
1899static bool isKnownDeclSpecAttr(const AttributeList &Attr) {
1900  return Attr.getKind() == AttributeList::AT_dllimport ||
1901         Attr.getKind() == AttributeList::AT_dllexport;
1902}
1903
1904//===----------------------------------------------------------------------===//
1905// Top Level Sema Entry Points
1906//===----------------------------------------------------------------------===//
1907
1908/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
1909/// the attribute applies to decls.  If the attribute is a type attribute, just
1910/// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
1911/// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
1912static void ProcessDeclAttribute(Scope *scope, Decl *D,
1913                                 const AttributeList &Attr, Sema &S) {
1914  if (Attr.isInvalid())
1915    return;
1916
1917  if (Attr.isDeclspecAttribute() && !isKnownDeclSpecAttr(Attr))
1918    // FIXME: Try to deal with other __declspec attributes!
1919    return;
1920  switch (Attr.getKind()) {
1921  case AttributeList::AT_IBAction:            HandleIBAction(D, Attr, S); break;
1922    case AttributeList::AT_IBOutlet:          HandleIBOutlet(D, Attr, S); break;
1923  case AttributeList::AT_IBOutletCollection:
1924      HandleIBOutletCollection(D, Attr, S); break;
1925  case AttributeList::AT_address_space:
1926  case AttributeList::AT_objc_gc:
1927  case AttributeList::AT_vector_size:
1928    // Ignore these, these are type attributes, handled by
1929    // ProcessTypeAttributes.
1930    break;
1931  case AttributeList::AT_alias:       HandleAliasAttr       (D, Attr, S); break;
1932  case AttributeList::AT_aligned:     HandleAlignedAttr     (D, Attr, S); break;
1933  case AttributeList::AT_always_inline:
1934    HandleAlwaysInlineAttr  (D, Attr, S); break;
1935  case AttributeList::AT_analyzer_noreturn:
1936    HandleAnalyzerNoReturnAttr  (D, Attr, S); break;
1937  case AttributeList::AT_annotate:    HandleAnnotateAttr    (D, Attr, S); break;
1938  case AttributeList::AT_base_check:  HandleBaseCheckAttr   (D, Attr, S); break;
1939  case AttributeList::AT_carries_dependency:
1940                                      HandleDependencyAttr  (D, Attr, S); break;
1941  case AttributeList::AT_constructor: HandleConstructorAttr (D, Attr, S); break;
1942  case AttributeList::AT_deprecated:  HandleDeprecatedAttr  (D, Attr, S); break;
1943  case AttributeList::AT_destructor:  HandleDestructorAttr  (D, Attr, S); break;
1944  case AttributeList::AT_ext_vector_type:
1945    HandleExtVectorTypeAttr(scope, D, Attr, S);
1946    break;
1947  case AttributeList::AT_final:       HandleFinalAttr       (D, Attr, S); break;
1948  case AttributeList::AT_format:      HandleFormatAttr      (D, Attr, S); break;
1949  case AttributeList::AT_format_arg:  HandleFormatArgAttr   (D, Attr, S); break;
1950  case AttributeList::AT_gnu_inline:  HandleGNUInlineAttr   (D, Attr, S); break;
1951  case AttributeList::AT_hiding:      HandleHidingAttr      (D, Attr, S); break;
1952  case AttributeList::AT_mode:        HandleModeAttr        (D, Attr, S); break;
1953  case AttributeList::AT_malloc:      HandleMallocAttr      (D, Attr, S); break;
1954  case AttributeList::AT_nonnull:     HandleNonNullAttr     (D, Attr, S); break;
1955  case AttributeList::AT_noreturn:    HandleNoReturnAttr    (D, Attr, S); break;
1956  case AttributeList::AT_nothrow:     HandleNothrowAttr     (D, Attr, S); break;
1957  case AttributeList::AT_override:    HandleOverrideAttr    (D, Attr, S); break;
1958
1959  // Checker-specific.
1960  case AttributeList::AT_ns_returns_not_retained:
1961  case AttributeList::AT_cf_returns_not_retained:
1962  case AttributeList::AT_ns_returns_retained:
1963  case AttributeList::AT_cf_returns_retained:
1964    HandleNSReturnsRetainedAttr(D, Attr, S); break;
1965
1966  case AttributeList::AT_reqd_wg_size:
1967    HandleReqdWorkGroupSize(D, Attr, S); break;
1968
1969  case AttributeList::AT_packed:      HandlePackedAttr      (D, Attr, S); break;
1970  case AttributeList::AT_section:     HandleSectionAttr     (D, Attr, S); break;
1971  case AttributeList::AT_unavailable: HandleUnavailableAttr (D, Attr, S); break;
1972  case AttributeList::AT_unused:      HandleUnusedAttr      (D, Attr, S); break;
1973  case AttributeList::AT_used:        HandleUsedAttr        (D, Attr, S); break;
1974  case AttributeList::AT_visibility:  HandleVisibilityAttr  (D, Attr, S); break;
1975  case AttributeList::AT_warn_unused_result: HandleWarnUnusedResult(D,Attr,S);
1976    break;
1977  case AttributeList::AT_weak:        HandleWeakAttr        (D, Attr, S); break;
1978  case AttributeList::AT_weakref:     HandleWeakRefAttr     (D, Attr, S); break;
1979  case AttributeList::AT_weak_import: HandleWeakImportAttr  (D, Attr, S); break;
1980  case AttributeList::AT_transparent_union:
1981    HandleTransparentUnionAttr(D, Attr, S);
1982    break;
1983  case AttributeList::AT_objc_exception:
1984    HandleObjCExceptionAttr(D, Attr, S);
1985    break;
1986  case AttributeList::AT_overloadable:HandleOverloadableAttr(D, Attr, S); break;
1987  case AttributeList::AT_adl_invisible: HandleADLInvisibleAttr(D, Attr, S); break;
1988  case AttributeList::AT_nsobject:    HandleObjCNSObject    (D, Attr, S); break;
1989  case AttributeList::AT_blocks:      HandleBlocksAttr      (D, Attr, S); break;
1990  case AttributeList::AT_sentinel:    HandleSentinelAttr    (D, Attr, S); break;
1991  case AttributeList::AT_const:       HandleConstAttr       (D, Attr, S); break;
1992  case AttributeList::AT_pure:        HandlePureAttr        (D, Attr, S); break;
1993  case AttributeList::AT_cleanup:     HandleCleanupAttr     (D, Attr, S); break;
1994  case AttributeList::AT_nodebug:     HandleNoDebugAttr     (D, Attr, S); break;
1995  case AttributeList::AT_noinline:    HandleNoInlineAttr    (D, Attr, S); break;
1996  case AttributeList::AT_regparm:     HandleRegparmAttr     (D, Attr, S); break;
1997  case AttributeList::IgnoredAttribute:
1998  case AttributeList::AT_no_instrument_function:  // Interacts with -pg.
1999    // Just ignore
2000    break;
2001  case AttributeList::AT_stdcall:
2002  case AttributeList::AT_cdecl:
2003  case AttributeList::AT_fastcall:
2004  case AttributeList::AT_thiscall:
2005    HandleCallConvAttr(D, Attr, S);
2006    break;
2007  default:
2008    // Ask target about the attribute.
2009    const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
2010    if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
2011      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2012    break;
2013  }
2014}
2015
2016/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
2017/// attribute list to the specified decl, ignoring any type attributes.
2018void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AttrList) {
2019  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
2020    ProcessDeclAttribute(S, D, *l, *this);
2021  }
2022
2023  // GCC accepts
2024  // static int a9 __attribute__((weakref));
2025  // but that looks really pointless. We reject it.
2026  if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
2027    Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
2028	dyn_cast<NamedDecl>(D)->getNameAsString();
2029    return;
2030  }
2031}
2032
2033/// DeclClonePragmaWeak - clone existing decl (maybe definition),
2034/// #pragma weak needs a non-definition decl and source may not have one
2035NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II) {
2036  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
2037  NamedDecl *NewD = 0;
2038  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2039    NewD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
2040                                FD->getLocation(), DeclarationName(II),
2041                                FD->getType(), FD->getTypeSourceInfo());
2042    if (FD->getQualifier()) {
2043      FunctionDecl *NewFD = cast<FunctionDecl>(NewD);
2044      NewFD->setQualifierInfo(FD->getQualifier(), FD->getQualifierRange());
2045    }
2046  } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
2047    NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
2048                           VD->getLocation(), II,
2049                           VD->getType(), VD->getTypeSourceInfo(),
2050                           VD->getStorageClass(),
2051                           VD->getStorageClassAsWritten());
2052    if (VD->getQualifier()) {
2053      VarDecl *NewVD = cast<VarDecl>(NewD);
2054      NewVD->setQualifierInfo(VD->getQualifier(), VD->getQualifierRange());
2055    }
2056  }
2057  return NewD;
2058}
2059
2060/// DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak
2061/// applied to it, possibly with an alias.
2062void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
2063  if (W.getUsed()) return; // only do this once
2064  W.setUsed(true);
2065  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
2066    IdentifierInfo *NDId = ND->getIdentifier();
2067    NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias());
2068    NewD->addAttr(::new (Context) AliasAttr(Context, NDId->getName()));
2069    NewD->addAttr(::new (Context) WeakAttr());
2070    WeakTopLevelDecl.push_back(NewD);
2071    // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
2072    // to insert Decl at TU scope, sorry.
2073    DeclContext *SavedContext = CurContext;
2074    CurContext = Context.getTranslationUnitDecl();
2075    PushOnScopeChains(NewD, S);
2076    CurContext = SavedContext;
2077  } else { // just add weak to existing
2078    ND->addAttr(::new (Context) WeakAttr());
2079  }
2080}
2081
2082/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
2083/// it, apply them to D.  This is a bit tricky because PD can have attributes
2084/// specified in many different places, and we need to find and apply them all.
2085void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
2086  // Handle #pragma weak
2087  if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
2088    if (ND->hasLinkage()) {
2089      WeakInfo W = WeakUndeclaredIdentifiers.lookup(ND->getIdentifier());
2090      if (W != WeakInfo()) {
2091        // Identifier referenced by #pragma weak before it was declared
2092        DeclApplyPragmaWeak(S, ND, W);
2093        WeakUndeclaredIdentifiers[ND->getIdentifier()] = W;
2094      }
2095    }
2096  }
2097
2098  // Apply decl attributes from the DeclSpec if present.
2099  if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes())
2100    ProcessDeclAttributeList(S, D, Attrs);
2101
2102  // Walk the declarator structure, applying decl attributes that were in a type
2103  // position to the decl itself.  This handles cases like:
2104  //   int *__attr__(x)** D;
2105  // when X is a decl attribute.
2106  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
2107    if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
2108      ProcessDeclAttributeList(S, D, Attrs);
2109
2110  // Finally, apply any attributes on the decl itself.
2111  if (const AttributeList *Attrs = PD.getAttributes())
2112    ProcessDeclAttributeList(S, D, Attrs);
2113}
2114
2115/// PushParsingDeclaration - Enter a new "scope" of deprecation
2116/// warnings.
2117///
2118/// The state token we use is the start index of this scope
2119/// on the warning stack.
2120Action::ParsingDeclStackState Sema::PushParsingDeclaration() {
2121  ParsingDeclDepth++;
2122  return (ParsingDeclStackState) DelayedDiagnostics.size();
2123}
2124
2125void Sema::PopParsingDeclaration(ParsingDeclStackState S, DeclPtrTy Ctx) {
2126  assert(ParsingDeclDepth > 0 && "empty ParsingDeclaration stack");
2127  ParsingDeclDepth--;
2128
2129  if (DelayedDiagnostics.empty())
2130    return;
2131
2132  unsigned SavedIndex = (unsigned) S;
2133  assert(SavedIndex <= DelayedDiagnostics.size() &&
2134         "saved index is out of bounds");
2135
2136  unsigned E = DelayedDiagnostics.size();
2137
2138  // We only want to actually emit delayed diagnostics when we
2139  // successfully parsed a decl.
2140  Decl *D = Ctx ? Ctx.getAs<Decl>() : 0;
2141  if (D) {
2142    // We really do want to start with 0 here.  We get one push for a
2143    // decl spec and another for each declarator;  in a decl group like:
2144    //   deprecated_typedef foo, *bar, baz();
2145    // only the declarator pops will be passed decls.  This is correct;
2146    // we really do need to consider delayed diagnostics from the decl spec
2147    // for each of the different declarations.
2148    for (unsigned I = 0; I != E; ++I) {
2149      if (DelayedDiagnostics[I].Triggered)
2150        continue;
2151
2152      switch (DelayedDiagnostics[I].Kind) {
2153      case DelayedDiagnostic::Deprecation:
2154        HandleDelayedDeprecationCheck(DelayedDiagnostics[I], D);
2155        break;
2156
2157      case DelayedDiagnostic::Access:
2158        HandleDelayedAccessCheck(DelayedDiagnostics[I], D);
2159        break;
2160      }
2161    }
2162  }
2163
2164  // Destroy all the delayed diagnostics we're about to pop off.
2165  for (unsigned I = SavedIndex; I != E; ++I)
2166    DelayedDiagnostics[I].destroy();
2167
2168  DelayedDiagnostics.set_size(SavedIndex);
2169}
2170
2171static bool isDeclDeprecated(Decl *D) {
2172  do {
2173    if (D->hasAttr<DeprecatedAttr>())
2174      return true;
2175  } while ((D = cast_or_null<Decl>(D->getDeclContext())));
2176  return false;
2177}
2178
2179void Sema::HandleDelayedDeprecationCheck(Sema::DelayedDiagnostic &DD,
2180                                         Decl *Ctx) {
2181  if (isDeclDeprecated(Ctx))
2182    return;
2183
2184  DD.Triggered = true;
2185  Diag(DD.Loc, diag::warn_deprecated)
2186    << DD.DeprecationData.Decl->getDeclName();
2187}
2188
2189void Sema::EmitDeprecationWarning(NamedDecl *D, SourceLocation Loc) {
2190  // Delay if we're currently parsing a declaration.
2191  if (ParsingDeclDepth) {
2192    DelayedDiagnostics.push_back(DelayedDiagnostic::makeDeprecation(Loc, D));
2193    return;
2194  }
2195
2196  // Otherwise, don't warn if our current context is deprecated.
2197  if (isDeclDeprecated(cast<Decl>(CurContext)))
2198    return;
2199
2200  Diag(Loc, diag::warn_deprecated) << D->getDeclName();
2201}
2202