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