SemaDeclAttr.cpp revision 7a73002783b30dcf613b06dbe618cfc1d1116ff8
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 HandleGNUInlineAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2082  // check the attribute arguments.
2083  if (Attr.getNumArgs() != 0) {
2084    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2085    return;
2086  }
2087
2088  FunctionDecl *Fn = dyn_cast<FunctionDecl>(d);
2089  if (Fn == 0) {
2090    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2091      << Attr.getName() << 0 /*function*/;
2092    return;
2093  }
2094
2095  if (!Fn->isInlineSpecified()) {
2096    S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
2097    return;
2098  }
2099
2100  d->addAttr(::new (S.Context) GNUInlineAttr(Attr.getLoc(), S.Context));
2101}
2102
2103static void HandleCallConvAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2104  // Diagnostic is emitted elsewhere: here we store the (valid) Attr
2105  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
2106  assert(Attr.isInvalid() == false);
2107
2108  switch (Attr.getKind()) {
2109  case AttributeList::AT_fastcall:
2110    d->addAttr(::new (S.Context) FastCallAttr(Attr.getLoc(), S.Context));
2111    return;
2112  case AttributeList::AT_stdcall:
2113    d->addAttr(::new (S.Context) StdCallAttr(Attr.getLoc(), S.Context));
2114    return;
2115  case AttributeList::AT_thiscall:
2116    d->addAttr(::new (S.Context) ThisCallAttr(Attr.getLoc(), S.Context));
2117    return;
2118  case AttributeList::AT_cdecl:
2119    d->addAttr(::new (S.Context) CDeclAttr(Attr.getLoc(), S.Context));
2120    return;
2121  case AttributeList::AT_pascal:
2122    d->addAttr(::new (S.Context) PascalAttr(Attr.getLoc(), S.Context));
2123    return;
2124  default:
2125    llvm_unreachable("unexpected attribute kind");
2126    return;
2127  }
2128}
2129
2130static void HandleRegparmAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2131  // check the attribute arguments.
2132  if (Attr.getNumArgs() != 1) {
2133    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2134    return;
2135  }
2136
2137  if (!isFunctionOrMethod(d)) {
2138    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2139    << Attr.getName() << 0 /*function*/;
2140    return;
2141  }
2142
2143  Expr *NumParamsExpr = Attr.getArg(0);
2144  llvm::APSInt NumParams(32);
2145  if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
2146      !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
2147    S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2148      << "regparm" << NumParamsExpr->getSourceRange();
2149    return;
2150  }
2151
2152  if (S.Context.Target.getRegParmMax() == 0) {
2153    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
2154      << NumParamsExpr->getSourceRange();
2155    return;
2156  }
2157
2158  if (NumParams.getLimitedValue(255) > S.Context.Target.getRegParmMax()) {
2159    S.Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
2160      << S.Context.Target.getRegParmMax() << NumParamsExpr->getSourceRange();
2161    return;
2162  }
2163
2164  d->addAttr(::new (S.Context) RegparmAttr(Attr.getLoc(), S.Context,
2165                                           NumParams.getZExtValue()));
2166}
2167
2168static void HandleFinalAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2169  // check the attribute arguments.
2170  if (Attr.getNumArgs() != 0) {
2171    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2172    return;
2173  }
2174
2175  if (!isa<CXXRecordDecl>(d)
2176   && (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual())) {
2177    S.Diag(Attr.getLoc(),
2178           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2179                                   : diag::warn_attribute_wrong_decl_type)
2180      << Attr.getName() << 7 /*virtual method or class*/;
2181    return;
2182  }
2183
2184  // FIXME: Conform to C++0x redeclaration rules.
2185
2186  if (d->getAttr<FinalAttr>()) {
2187    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "final";
2188    return;
2189  }
2190
2191  d->addAttr(::new (S.Context) FinalAttr(Attr.getLoc(), S.Context));
2192}
2193
2194//===----------------------------------------------------------------------===//
2195// C++0x member checking attributes
2196//===----------------------------------------------------------------------===//
2197
2198static void HandleBaseCheckAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2199  if (Attr.getNumArgs() != 0) {
2200    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2201    return;
2202  }
2203
2204  if (!isa<CXXRecordDecl>(d)) {
2205    S.Diag(Attr.getLoc(),
2206           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2207                                   : diag::warn_attribute_wrong_decl_type)
2208      << Attr.getName() << 9 /*class*/;
2209    return;
2210  }
2211
2212  if (d->getAttr<BaseCheckAttr>()) {
2213    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "base_check";
2214    return;
2215  }
2216
2217  d->addAttr(::new (S.Context) BaseCheckAttr(Attr.getLoc(), S.Context));
2218}
2219
2220static void HandleHidingAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2221  if (Attr.getNumArgs() != 0) {
2222    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2223    return;
2224  }
2225
2226  if (!isa<RecordDecl>(d->getDeclContext())) {
2227    // FIXME: It's not the type that's the problem
2228    S.Diag(Attr.getLoc(),
2229           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2230                                   : diag::warn_attribute_wrong_decl_type)
2231      << Attr.getName() << 11 /*member*/;
2232    return;
2233  }
2234
2235  // FIXME: Conform to C++0x redeclaration rules.
2236
2237  if (d->getAttr<HidingAttr>()) {
2238    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "hiding";
2239    return;
2240  }
2241
2242  d->addAttr(::new (S.Context) HidingAttr(Attr.getLoc(), S.Context));
2243}
2244
2245static void HandleOverrideAttr(Decl *d, const AttributeList &Attr, Sema &S) {
2246  if (Attr.getNumArgs() != 0) {
2247    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0;
2248    return;
2249  }
2250
2251  if (!isa<CXXMethodDecl>(d) || !cast<CXXMethodDecl>(d)->isVirtual()) {
2252    // FIXME: It's not the type that's the problem
2253    S.Diag(Attr.getLoc(),
2254           Attr.isCXX0XAttribute() ? diag::err_attribute_wrong_decl_type
2255                                   : diag::warn_attribute_wrong_decl_type)
2256      << Attr.getName() << 10 /*virtual method*/;
2257    return;
2258  }
2259
2260  // FIXME: Conform to C++0x redeclaration rules.
2261
2262  if (d->getAttr<OverrideAttr>()) {
2263    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "override";
2264    return;
2265  }
2266
2267  d->addAttr(::new (S.Context) OverrideAttr(Attr.getLoc(), S.Context));
2268}
2269
2270//===----------------------------------------------------------------------===//
2271// Checker-specific attribute handlers.
2272//===----------------------------------------------------------------------===//
2273
2274static void HandleNSReturnsRetainedAttr(Decl *d, const AttributeList &Attr,
2275                                        Sema &S) {
2276
2277  QualType RetTy;
2278
2279  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(d))
2280    RetTy = MD->getResultType();
2281  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(d))
2282    RetTy = FD->getResultType();
2283  else {
2284    SourceLocation L = Attr.getLoc();
2285    S.Diag(d->getLocStart(), diag::warn_attribute_wrong_decl_type)
2286        << SourceRange(L, L) << Attr.getName() << 3 /* function or method */;
2287    return;
2288  }
2289
2290  if (!(S.Context.isObjCNSObjectType(RetTy) || RetTy->getAs<PointerType>()
2291        || RetTy->getAs<ObjCObjectPointerType>())) {
2292    SourceLocation L = Attr.getLoc();
2293    S.Diag(d->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
2294      << SourceRange(L, L) << Attr.getName();
2295    return;
2296  }
2297
2298  switch (Attr.getKind()) {
2299    default:
2300      assert(0 && "invalid ownership attribute");
2301      return;
2302    case AttributeList::AT_cf_returns_not_retained:
2303      d->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(Attr.getLoc(), S.Context));
2304      return;
2305    case AttributeList::AT_ns_returns_not_retained:
2306      d->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(Attr.getLoc(), S.Context));
2307      return;
2308    case AttributeList::AT_cf_returns_retained:
2309      d->addAttr(::new (S.Context) CFReturnsRetainedAttr(Attr.getLoc(), S.Context));
2310      return;
2311    case AttributeList::AT_ns_returns_retained:
2312      d->addAttr(::new (S.Context) NSReturnsRetainedAttr(Attr.getLoc(), S.Context));
2313      return;
2314  };
2315}
2316
2317static bool isKnownDeclSpecAttr(const AttributeList &Attr) {
2318  return Attr.getKind() == AttributeList::AT_dllimport ||
2319         Attr.getKind() == AttributeList::AT_dllexport;
2320}
2321
2322//===----------------------------------------------------------------------===//
2323// Top Level Sema Entry Points
2324//===----------------------------------------------------------------------===//
2325
2326/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
2327/// the attribute applies to decls.  If the attribute is a type attribute, just
2328/// silently ignore it if a GNU attribute. FIXME: Applying a C++0x attribute to
2329/// the wrong thing is illegal (C++0x [dcl.attr.grammar]/4).
2330static void ProcessDeclAttribute(Scope *scope, Decl *D,
2331                                 const AttributeList &Attr, Sema &S) {
2332  if (Attr.isInvalid())
2333    return;
2334
2335  if (Attr.isDeclspecAttribute() && !isKnownDeclSpecAttr(Attr))
2336    // FIXME: Try to deal with other __declspec attributes!
2337    return;
2338  switch (Attr.getKind()) {
2339  case AttributeList::AT_IBAction:            HandleIBAction(D, Attr, S); break;
2340    case AttributeList::AT_IBOutlet:          HandleIBOutlet(D, Attr, S); break;
2341  case AttributeList::AT_IBOutletCollection:
2342      HandleIBOutletCollection(D, Attr, S); break;
2343  case AttributeList::AT_address_space:
2344  case AttributeList::AT_objc_gc:
2345  case AttributeList::AT_vector_size:
2346  case AttributeList::AT_neon_vector_type:
2347  case AttributeList::AT_neon_polyvector_type:
2348    // Ignore these, these are type attributes, handled by
2349    // ProcessTypeAttributes.
2350    break;
2351  case AttributeList::AT_alias:       HandleAliasAttr       (D, Attr, S); break;
2352  case AttributeList::AT_aligned:     HandleAlignedAttr     (D, Attr, S); break;
2353  case AttributeList::AT_always_inline:
2354    HandleAlwaysInlineAttr  (D, Attr, S); break;
2355  case AttributeList::AT_analyzer_noreturn:
2356    HandleAnalyzerNoReturnAttr  (D, Attr, S); break;
2357  case AttributeList::AT_annotate:    HandleAnnotateAttr    (D, Attr, S); break;
2358  case AttributeList::AT_base_check:  HandleBaseCheckAttr   (D, Attr, S); break;
2359  case AttributeList::AT_carries_dependency:
2360                                      HandleDependencyAttr  (D, Attr, S); break;
2361  case AttributeList::AT_constructor: HandleConstructorAttr (D, Attr, S); break;
2362  case AttributeList::AT_deprecated:  HandleDeprecatedAttr  (D, Attr, S); break;
2363  case AttributeList::AT_destructor:  HandleDestructorAttr  (D, Attr, S); break;
2364  case AttributeList::AT_ext_vector_type:
2365    HandleExtVectorTypeAttr(scope, D, Attr, S);
2366    break;
2367  case AttributeList::AT_final:       HandleFinalAttr       (D, Attr, S); break;
2368  case AttributeList::AT_format:      HandleFormatAttr      (D, Attr, S); break;
2369  case AttributeList::AT_format_arg:  HandleFormatArgAttr   (D, Attr, S); break;
2370  case AttributeList::AT_gnu_inline:  HandleGNUInlineAttr   (D, Attr, S); break;
2371  case AttributeList::AT_hiding:      HandleHidingAttr      (D, Attr, S); break;
2372  case AttributeList::AT_mode:        HandleModeAttr        (D, Attr, S); break;
2373  case AttributeList::AT_malloc:      HandleMallocAttr      (D, Attr, S); break;
2374  case AttributeList::AT_may_alias:   HandleMayAliasAttr    (D, Attr, S); break;
2375  case AttributeList::AT_nonnull:     HandleNonNullAttr     (D, Attr, S); break;
2376  case AttributeList::AT_ownership_returns:
2377  case AttributeList::AT_ownership_takes:
2378  case AttributeList::AT_ownership_holds:
2379      HandleOwnershipAttr     (D, Attr, S); break;
2380  case AttributeList::AT_naked:       HandleNakedAttr       (D, Attr, S); break;
2381  case AttributeList::AT_noreturn:    HandleNoReturnAttr    (D, Attr, S); break;
2382  case AttributeList::AT_nothrow:     HandleNothrowAttr     (D, Attr, S); break;
2383  case AttributeList::AT_override:    HandleOverrideAttr    (D, Attr, S); break;
2384  case AttributeList::AT_vecreturn:   HandleVecReturnAttr   (D, Attr, S); break;
2385
2386  // Checker-specific.
2387  case AttributeList::AT_ns_returns_not_retained:
2388  case AttributeList::AT_cf_returns_not_retained:
2389  case AttributeList::AT_ns_returns_retained:
2390  case AttributeList::AT_cf_returns_retained:
2391    HandleNSReturnsRetainedAttr(D, Attr, S); break;
2392
2393  case AttributeList::AT_reqd_wg_size:
2394    HandleReqdWorkGroupSize(D, Attr, S); break;
2395
2396  case AttributeList::AT_init_priority:
2397      HandleInitPriorityAttr(D, Attr, S); break;
2398
2399  case AttributeList::AT_packed:      HandlePackedAttr      (D, Attr, S); break;
2400  case AttributeList::AT_section:     HandleSectionAttr     (D, Attr, S); break;
2401  case AttributeList::AT_unavailable: HandleUnavailableAttr (D, Attr, S); break;
2402  case AttributeList::AT_unused:      HandleUnusedAttr      (D, Attr, S); break;
2403  case AttributeList::AT_used:        HandleUsedAttr        (D, Attr, S); break;
2404  case AttributeList::AT_visibility:  HandleVisibilityAttr  (D, Attr, S); break;
2405  case AttributeList::AT_warn_unused_result: HandleWarnUnusedResult(D,Attr,S);
2406    break;
2407  case AttributeList::AT_weak:        HandleWeakAttr        (D, Attr, S); break;
2408  case AttributeList::AT_weakref:     HandleWeakRefAttr     (D, Attr, S); break;
2409  case AttributeList::AT_weak_import: HandleWeakImportAttr  (D, Attr, S); break;
2410  case AttributeList::AT_transparent_union:
2411    HandleTransparentUnionAttr(D, Attr, S);
2412    break;
2413  case AttributeList::AT_objc_exception:
2414    HandleObjCExceptionAttr(D, Attr, S);
2415    break;
2416  case AttributeList::AT_overloadable:HandleOverloadableAttr(D, Attr, S); break;
2417  case AttributeList::AT_nsobject:    HandleObjCNSObject    (D, Attr, S); break;
2418  case AttributeList::AT_blocks:      HandleBlocksAttr      (D, Attr, S); break;
2419  case AttributeList::AT_sentinel:    HandleSentinelAttr    (D, Attr, S); break;
2420  case AttributeList::AT_const:       HandleConstAttr       (D, Attr, S); break;
2421  case AttributeList::AT_pure:        HandlePureAttr        (D, Attr, S); break;
2422  case AttributeList::AT_cleanup:     HandleCleanupAttr     (D, Attr, S); break;
2423  case AttributeList::AT_nodebug:     HandleNoDebugAttr     (D, Attr, S); break;
2424  case AttributeList::AT_noinline:    HandleNoInlineAttr    (D, Attr, S); break;
2425  case AttributeList::AT_regparm:     HandleRegparmAttr     (D, Attr, S); break;
2426  case AttributeList::IgnoredAttribute:
2427    // Just ignore
2428    break;
2429  case AttributeList::AT_no_instrument_function:  // Interacts with -pg.
2430    HandleNoInstrumentFunctionAttr(D, Attr, S);
2431    break;
2432  case AttributeList::AT_stdcall:
2433  case AttributeList::AT_cdecl:
2434  case AttributeList::AT_fastcall:
2435  case AttributeList::AT_thiscall:
2436  case AttributeList::AT_pascal:
2437    HandleCallConvAttr(D, Attr, S);
2438    break;
2439  default:
2440    // Ask target about the attribute.
2441    const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
2442    if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
2443      S.Diag(Attr.getLoc(), diag::warn_unknown_attribute_ignored)
2444        << Attr.getName();
2445    break;
2446  }
2447}
2448
2449/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
2450/// attribute list to the specified decl, ignoring any type attributes.
2451void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AttrList) {
2452  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
2453    ProcessDeclAttribute(S, D, *l, *this);
2454  }
2455
2456  // GCC accepts
2457  // static int a9 __attribute__((weakref));
2458  // but that looks really pointless. We reject it.
2459  if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
2460    Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
2461    dyn_cast<NamedDecl>(D)->getNameAsString();
2462    return;
2463  }
2464}
2465
2466/// DeclClonePragmaWeak - clone existing decl (maybe definition),
2467/// #pragma weak needs a non-definition decl and source may not have one
2468NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II) {
2469  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
2470  NamedDecl *NewD = 0;
2471  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2472    NewD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
2473                                FD->getLocation(), DeclarationName(II),
2474                                FD->getType(), FD->getTypeSourceInfo());
2475    if (FD->getQualifier()) {
2476      FunctionDecl *NewFD = cast<FunctionDecl>(NewD);
2477      NewFD->setQualifierInfo(FD->getQualifier(), FD->getQualifierRange());
2478    }
2479  } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
2480    NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
2481                           VD->getLocation(), II,
2482                           VD->getType(), VD->getTypeSourceInfo(),
2483                           VD->getStorageClass(),
2484                           VD->getStorageClassAsWritten());
2485    if (VD->getQualifier()) {
2486      VarDecl *NewVD = cast<VarDecl>(NewD);
2487      NewVD->setQualifierInfo(VD->getQualifier(), VD->getQualifierRange());
2488    }
2489  }
2490  return NewD;
2491}
2492
2493/// DeclApplyPragmaWeak - A declaration (maybe definition) needs #pragma weak
2494/// applied to it, possibly with an alias.
2495void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
2496  if (W.getUsed()) return; // only do this once
2497  W.setUsed(true);
2498  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
2499    IdentifierInfo *NDId = ND->getIdentifier();
2500    NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias());
2501    NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
2502                                            NDId->getName()));
2503    NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
2504    WeakTopLevelDecl.push_back(NewD);
2505    // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
2506    // to insert Decl at TU scope, sorry.
2507    DeclContext *SavedContext = CurContext;
2508    CurContext = Context.getTranslationUnitDecl();
2509    PushOnScopeChains(NewD, S);
2510    CurContext = SavedContext;
2511  } else { // just add weak to existing
2512    ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
2513  }
2514}
2515
2516/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
2517/// it, apply them to D.  This is a bit tricky because PD can have attributes
2518/// specified in many different places, and we need to find and apply them all.
2519void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
2520  // It's valid to "forward-declare" #pragma weak, in which case we
2521  // have to do this.
2522  if (!WeakUndeclaredIdentifiers.empty()) {
2523    if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
2524      if (IdentifierInfo *Id = ND->getIdentifier()) {
2525        llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
2526          = WeakUndeclaredIdentifiers.find(Id);
2527        if (I != WeakUndeclaredIdentifiers.end() && ND->hasLinkage()) {
2528          WeakInfo W = I->second;
2529          DeclApplyPragmaWeak(S, ND, W);
2530          WeakUndeclaredIdentifiers[Id] = W;
2531        }
2532      }
2533    }
2534  }
2535
2536  // Apply decl attributes from the DeclSpec if present.
2537  if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes())
2538    ProcessDeclAttributeList(S, D, Attrs);
2539
2540  // Walk the declarator structure, applying decl attributes that were in a type
2541  // position to the decl itself.  This handles cases like:
2542  //   int *__attr__(x)** D;
2543  // when X is a decl attribute.
2544  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
2545    if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
2546      ProcessDeclAttributeList(S, D, Attrs);
2547
2548  // Finally, apply any attributes on the decl itself.
2549  if (const AttributeList *Attrs = PD.getAttributes())
2550    ProcessDeclAttributeList(S, D, Attrs);
2551}
2552
2553/// PushParsingDeclaration - Enter a new "scope" of deprecation
2554/// warnings.
2555///
2556/// The state token we use is the start index of this scope
2557/// on the warning stack.
2558Sema::ParsingDeclStackState Sema::PushParsingDeclaration() {
2559  ParsingDeclDepth++;
2560  return (ParsingDeclStackState) DelayedDiagnostics.size();
2561}
2562
2563void Sema::PopParsingDeclaration(ParsingDeclStackState S, Decl *D) {
2564  assert(ParsingDeclDepth > 0 && "empty ParsingDeclaration stack");
2565  ParsingDeclDepth--;
2566
2567  if (DelayedDiagnostics.empty())
2568    return;
2569
2570  unsigned SavedIndex = (unsigned) S;
2571  assert(SavedIndex <= DelayedDiagnostics.size() &&
2572         "saved index is out of bounds");
2573
2574  unsigned E = DelayedDiagnostics.size();
2575
2576  // We only want to actually emit delayed diagnostics when we
2577  // successfully parsed a decl.
2578  if (D) {
2579    // We really do want to start with 0 here.  We get one push for a
2580    // decl spec and another for each declarator;  in a decl group like:
2581    //   deprecated_typedef foo, *bar, baz();
2582    // only the declarator pops will be passed decls.  This is correct;
2583    // we really do need to consider delayed diagnostics from the decl spec
2584    // for each of the different declarations.
2585    for (unsigned I = 0; I != E; ++I) {
2586      if (DelayedDiagnostics[I].Triggered)
2587        continue;
2588
2589      switch (DelayedDiagnostics[I].Kind) {
2590      case DelayedDiagnostic::Deprecation:
2591        HandleDelayedDeprecationCheck(DelayedDiagnostics[I], D);
2592        break;
2593
2594      case DelayedDiagnostic::Access:
2595        HandleDelayedAccessCheck(DelayedDiagnostics[I], D);
2596        break;
2597      }
2598    }
2599  }
2600
2601  // Destroy all the delayed diagnostics we're about to pop off.
2602  for (unsigned I = SavedIndex; I != E; ++I)
2603    DelayedDiagnostics[I].destroy();
2604
2605  DelayedDiagnostics.set_size(SavedIndex);
2606}
2607
2608static bool isDeclDeprecated(Decl *D) {
2609  do {
2610    if (D->hasAttr<DeprecatedAttr>())
2611      return true;
2612  } while ((D = cast_or_null<Decl>(D->getDeclContext())));
2613  return false;
2614}
2615
2616void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
2617                                         Decl *Ctx) {
2618  if (isDeclDeprecated(Ctx))
2619    return;
2620
2621  DD.Triggered = true;
2622  if (!DD.getDeprecationMessage().empty())
2623    Diag(DD.Loc, diag::warn_deprecated_message)
2624      << DD.getDeprecationDecl()->getDeclName()
2625      << DD.getDeprecationMessage();
2626  else
2627    Diag(DD.Loc, diag::warn_deprecated)
2628      << DD.getDeprecationDecl()->getDeclName();
2629}
2630
2631void Sema::EmitDeprecationWarning(NamedDecl *D, llvm::StringRef Message,
2632                                  SourceLocation Loc) {
2633  // Delay if we're currently parsing a declaration.
2634  if (ParsingDeclDepth) {
2635    DelayedDiagnostics.push_back(DelayedDiagnostic::makeDeprecation(Loc, D,
2636                                                                    Message));
2637    return;
2638  }
2639
2640  // Otherwise, don't warn if our current context is deprecated.
2641  if (isDeclDeprecated(cast<Decl>(CurContext)))
2642    return;
2643  if (!Message.empty())
2644    Diag(Loc, diag::warn_deprecated_message) << D->getDeclName()
2645                                             << Message;
2646  else
2647    Diag(Loc, diag::warn_deprecated) << D->getDeclName();
2648}
2649