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