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