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