SemaDeclAttr.cpp revision 1bf6343612e394051fffc587e6899de6901065e0
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/CXXInheritance.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/Mangle.h"
23#include "clang/Basic/CharInfo.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Lex/Preprocessor.h"
27#include "clang/Sema/DeclSpec.h"
28#include "clang/Sema/DelayedDiagnostic.h"
29#include "clang/Sema/Lookup.h"
30#include "clang/Sema/Scope.h"
31#include "llvm/ADT/StringExtras.h"
32using namespace clang;
33using namespace sema;
34
35/// These constants match the enumerated choices of
36/// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
37enum AttributeDeclKind {
38  ExpectedFunction,
39  ExpectedUnion,
40  ExpectedVariableOrFunction,
41  ExpectedFunctionOrMethod,
42  ExpectedParameter,
43  ExpectedFunctionMethodOrBlock,
44  ExpectedFunctionMethodOrClass,
45  ExpectedFunctionMethodOrParameter,
46  ExpectedClass,
47  ExpectedVariable,
48  ExpectedMethod,
49  ExpectedVariableFunctionOrLabel,
50  ExpectedFieldOrGlobalVar,
51  ExpectedStruct,
52  ExpectedVariableFunctionOrTag,
53  ExpectedTLSVar,
54  ExpectedVariableOrField,
55  ExpectedVariableFieldOrTag,
56  ExpectedTypeOrNamespace,
57  ExpectedObjectiveCInterface,
58  ExpectedMethodOrProperty
59};
60
61//===----------------------------------------------------------------------===//
62//  Helper functions
63//===----------------------------------------------------------------------===//
64
65static const FunctionType *getFunctionType(const Decl *D,
66                                           bool blocksToo = true) {
67  QualType Ty;
68  if (const ValueDecl *decl = dyn_cast<ValueDecl>(D))
69    Ty = decl->getType();
70  else if (const FieldDecl *decl = dyn_cast<FieldDecl>(D))
71    Ty = decl->getType();
72  else if (const TypedefNameDecl* decl = dyn_cast<TypedefNameDecl>(D))
73    Ty = decl->getUnderlyingType();
74  else
75    return 0;
76
77  if (Ty->isFunctionPointerType())
78    Ty = Ty->getAs<PointerType>()->getPointeeType();
79  else if (blocksToo && Ty->isBlockPointerType())
80    Ty = Ty->getAs<BlockPointerType>()->getPointeeType();
81
82  return Ty->getAs<FunctionType>();
83}
84
85// FIXME: We should provide an abstraction around a method or function
86// to provide the following bits of information.
87
88/// isFunction - Return true if the given decl has function
89/// type (function or function-typed variable).
90static bool isFunction(const Decl *D) {
91  return getFunctionType(D, false) != NULL;
92}
93
94/// isFunctionOrMethod - Return true if the given decl has function
95/// type (function or function-typed variable) or an Objective-C
96/// method.
97static bool isFunctionOrMethod(const Decl *D) {
98  return isFunction(D) || isa<ObjCMethodDecl>(D);
99}
100
101/// isFunctionOrMethodOrBlock - Return true if the given decl has function
102/// type (function or function-typed variable) or an Objective-C
103/// method or a block.
104static bool isFunctionOrMethodOrBlock(const Decl *D) {
105  if (isFunctionOrMethod(D))
106    return true;
107  // check for block is more involved.
108  if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
109    QualType Ty = V->getType();
110    return Ty->isBlockPointerType();
111  }
112  return isa<BlockDecl>(D);
113}
114
115/// Return true if the given decl has a declarator that should have
116/// been processed by Sema::GetTypeForDeclarator.
117static bool hasDeclarator(const Decl *D) {
118  // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
119  return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
120         isa<ObjCPropertyDecl>(D);
121}
122
123/// hasFunctionProto - Return true if the given decl has a argument
124/// information. This decl should have already passed
125/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
126static bool hasFunctionProto(const Decl *D) {
127  if (const FunctionType *FnTy = getFunctionType(D))
128    return isa<FunctionProtoType>(FnTy);
129  else {
130    assert(isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D));
131    return true;
132  }
133}
134
135/// getFunctionOrMethodNumArgs - Return number of function or method
136/// arguments. It is an error to call this on a K&R function (use
137/// hasFunctionProto first).
138static unsigned getFunctionOrMethodNumArgs(const Decl *D) {
139  if (const FunctionType *FnTy = getFunctionType(D))
140    return cast<FunctionProtoType>(FnTy)->getNumArgs();
141  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
142    return BD->getNumParams();
143  return cast<ObjCMethodDecl>(D)->param_size();
144}
145
146static QualType getFunctionOrMethodArgType(const Decl *D, unsigned Idx) {
147  if (const FunctionType *FnTy = getFunctionType(D))
148    return cast<FunctionProtoType>(FnTy)->getArgType(Idx);
149  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
150    return BD->getParamDecl(Idx)->getType();
151
152  return cast<ObjCMethodDecl>(D)->param_begin()[Idx]->getType();
153}
154
155static QualType getFunctionOrMethodResultType(const Decl *D) {
156  if (const FunctionType *FnTy = getFunctionType(D))
157    return cast<FunctionProtoType>(FnTy)->getResultType();
158  return cast<ObjCMethodDecl>(D)->getResultType();
159}
160
161static bool isFunctionOrMethodVariadic(const Decl *D) {
162  if (const FunctionType *FnTy = getFunctionType(D)) {
163    const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
164    return proto->isVariadic();
165  } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
166    return BD->isVariadic();
167  else {
168    return cast<ObjCMethodDecl>(D)->isVariadic();
169  }
170}
171
172static bool isInstanceMethod(const Decl *D) {
173  if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
174    return MethodDecl->isInstance();
175  return false;
176}
177
178static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
179  const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
180  if (!PT)
181    return false;
182
183  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
184  if (!Cls)
185    return false;
186
187  IdentifierInfo* ClsName = Cls->getIdentifier();
188
189  // FIXME: Should we walk the chain of classes?
190  return ClsName == &Ctx.Idents.get("NSString") ||
191         ClsName == &Ctx.Idents.get("NSMutableString");
192}
193
194static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
195  const PointerType *PT = T->getAs<PointerType>();
196  if (!PT)
197    return false;
198
199  const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
200  if (!RT)
201    return false;
202
203  const RecordDecl *RD = RT->getDecl();
204  if (RD->getTagKind() != TTK_Struct)
205    return false;
206
207  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
208}
209
210/// \brief Check if the attribute has exactly as many args as Num. May
211/// output an error.
212static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
213                                  unsigned int Num) {
214  if (Attr.getNumArgs() != Num) {
215    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
216      << Attr.getName() << Num;
217    return false;
218  }
219
220  return true;
221}
222
223
224/// \brief Check if the attribute has at least as many args as Num. May
225/// output an error.
226static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
227                                  unsigned int Num) {
228  if (Attr.getNumArgs() < Num) {
229    S.Diag(Attr.getLoc(), diag::err_attribute_too_few_arguments) << Num;
230    return false;
231  }
232
233  return true;
234}
235
236/// \brief Check if IdxExpr is a valid argument index for a function or
237/// instance method D.  May output an error.
238///
239/// \returns true if IdxExpr is a valid index.
240static bool checkFunctionOrMethodArgumentIndex(Sema &S, const Decl *D,
241                                               StringRef AttrName,
242                                               SourceLocation AttrLoc,
243                                               unsigned AttrArgNum,
244                                               const Expr *IdxExpr,
245                                               uint64_t &Idx)
246{
247  assert(isFunctionOrMethod(D));
248
249  // In C++ the implicit 'this' function parameter also counts.
250  // Parameters are counted from one.
251  bool HP = hasFunctionProto(D);
252  bool HasImplicitThisParam = isInstanceMethod(D);
253  bool IV = HP && isFunctionOrMethodVariadic(D);
254  unsigned NumArgs = (HP ? getFunctionOrMethodNumArgs(D) : 0) +
255                     HasImplicitThisParam;
256
257  llvm::APSInt IdxInt;
258  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
259      !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
260    std::string Name = std::string("'") + AttrName.str() + std::string("'");
261    S.Diag(AttrLoc, diag::err_attribute_argument_n_type) << Name.c_str()
262      << AttrArgNum << AANT_ArgumentIntegerConstant << IdxExpr->getSourceRange();
263    return false;
264  }
265
266  Idx = IdxInt.getLimitedValue();
267  if (Idx < 1 || (!IV && Idx > NumArgs)) {
268    S.Diag(AttrLoc, diag::err_attribute_argument_out_of_bounds)
269      << AttrName << AttrArgNum << IdxExpr->getSourceRange();
270    return false;
271  }
272  Idx--; // Convert to zero-based.
273  if (HasImplicitThisParam) {
274    if (Idx == 0) {
275      S.Diag(AttrLoc,
276             diag::err_attribute_invalid_implicit_this_argument)
277        << AttrName << IdxExpr->getSourceRange();
278      return false;
279    }
280    --Idx;
281  }
282
283  return true;
284}
285
286/// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
287/// If not emit an error and return false. If the argument is an identifier it
288/// will emit an error with a fixit hint and treat it as if it was a string
289/// literal.
290bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
291                                          unsigned ArgNum, StringRef &Str,
292                                          SourceLocation *ArgLocation) {
293  // Look for identifiers. If we have one emit a hint to fix it to a literal.
294  if (Attr.isArgIdent(ArgNum)) {
295    IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
296    Diag(Loc->Loc, diag::err_attribute_argument_type)
297        << Attr.getName() << AANT_ArgumentString
298        << FixItHint::CreateInsertion(Loc->Loc, "\"")
299        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\"");
300    Str = Loc->Ident->getName();
301    if (ArgLocation)
302      *ArgLocation = Loc->Loc;
303    return true;
304  }
305
306  // Now check for an actual string literal.
307  Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
308  StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
309  if (ArgLocation)
310    *ArgLocation = ArgExpr->getLocStart();
311
312  if (!Literal || !Literal->isAscii()) {
313    Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
314        << Attr.getName() << AANT_ArgumentString;
315    return false;
316  }
317
318  Str = Literal->getString();
319  return true;
320}
321
322///
323/// \brief Check if passed in Decl is a field or potentially shared global var
324/// \return true if the Decl is a field or potentially shared global variable
325///
326static bool mayBeSharedVariable(const Decl *D) {
327  if (isa<FieldDecl>(D))
328    return true;
329  if (const VarDecl *vd = dyn_cast<VarDecl>(D))
330    return vd->hasGlobalStorage() && !vd->getTLSKind();
331
332  return false;
333}
334
335/// \brief Check if the passed-in expression is of type int or bool.
336static bool isIntOrBool(Expr *Exp) {
337  QualType QT = Exp->getType();
338  return QT->isBooleanType() || QT->isIntegerType();
339}
340
341
342// Check to see if the type is a smart pointer of some kind.  We assume
343// it's a smart pointer if it defines both operator-> and operator*.
344static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
345  DeclContextLookupConstResult Res1 = RT->getDecl()->lookup(
346    S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
347  if (Res1.empty())
348    return false;
349
350  DeclContextLookupConstResult Res2 = RT->getDecl()->lookup(
351    S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
352  if (Res2.empty())
353    return false;
354
355  return true;
356}
357
358/// \brief Check if passed in Decl is a pointer type.
359/// Note that this function may produce an error message.
360/// \return true if the Decl is a pointer type; false otherwise
361static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
362                                       const AttributeList &Attr) {
363  if (const ValueDecl *vd = dyn_cast<ValueDecl>(D)) {
364    QualType QT = vd->getType();
365    if (QT->isAnyPointerType())
366      return true;
367
368    if (const RecordType *RT = QT->getAs<RecordType>()) {
369      // If it's an incomplete type, it could be a smart pointer; skip it.
370      // (We don't want to force template instantiation if we can avoid it,
371      // since that would alter the order in which templates are instantiated.)
372      if (RT->isIncompleteType())
373        return true;
374
375      if (threadSafetyCheckIsSmartPointer(S, RT))
376        return true;
377    }
378
379    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
380      << Attr.getName()->getName() << QT;
381  } else {
382    S.Diag(Attr.getLoc(), diag::err_attribute_can_be_applied_only_to_value_decl)
383      << Attr.getName();
384  }
385  return false;
386}
387
388/// \brief Checks that the passed in QualType either is of RecordType or points
389/// to RecordType. Returns the relevant RecordType, null if it does not exit.
390static const RecordType *getRecordType(QualType QT) {
391  if (const RecordType *RT = QT->getAs<RecordType>())
392    return RT;
393
394  // Now check if we point to record type.
395  if (const PointerType *PT = QT->getAs<PointerType>())
396    return PT->getPointeeType()->getAs<RecordType>();
397
398  return 0;
399}
400
401
402static bool checkBaseClassIsLockableCallback(const CXXBaseSpecifier *Specifier,
403                                             CXXBasePath &Path, void *Unused) {
404  const RecordType *RT = Specifier->getType()->getAs<RecordType>();
405  if (RT->getDecl()->getAttr<LockableAttr>())
406    return true;
407  return false;
408}
409
410
411/// \brief Thread Safety Analysis: Checks that the passed in RecordType
412/// resolves to a lockable object.
413static void checkForLockableRecord(Sema &S, Decl *D, const AttributeList &Attr,
414                                   QualType Ty) {
415  const RecordType *RT = getRecordType(Ty);
416
417  // Warn if could not get record type for this argument.
418  if (!RT) {
419    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_class)
420      << Attr.getName() << Ty.getAsString();
421    return;
422  }
423
424  // Don't check for lockable if the class hasn't been defined yet.
425  if (RT->isIncompleteType())
426    return;
427
428  // Allow smart pointers to be used as lockable objects.
429  // FIXME -- Check the type that the smart pointer points to.
430  if (threadSafetyCheckIsSmartPointer(S, RT))
431    return;
432
433  // Check if the type is lockable.
434  RecordDecl *RD = RT->getDecl();
435  if (RD->getAttr<LockableAttr>())
436    return;
437
438  // Else check if any base classes are lockable.
439  if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
440    CXXBasePaths BPaths(false, false);
441    if (CRD->lookupInBases(checkBaseClassIsLockableCallback, 0, BPaths))
442      return;
443  }
444
445  S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
446    << Attr.getName() << Ty.getAsString();
447}
448
449/// \brief Thread Safety Analysis: Checks that all attribute arguments, starting
450/// from Sidx, resolve to a lockable object.
451/// \param Sidx The attribute argument index to start checking with.
452/// \param ParamIdxOk Whether an argument can be indexing into a function
453/// parameter list.
454static void checkAttrArgsAreLockableObjs(Sema &S, Decl *D,
455                                         const AttributeList &Attr,
456                                         SmallVectorImpl<Expr*> &Args,
457                                         int Sidx = 0,
458                                         bool ParamIdxOk = false) {
459  for(unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
460    Expr *ArgExp = Attr.getArgAsExpr(Idx);
461
462    if (ArgExp->isTypeDependent()) {
463      // FIXME -- need to check this again on template instantiation
464      Args.push_back(ArgExp);
465      continue;
466    }
467
468    if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
469      if (StrLit->getLength() == 0 ||
470          (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
471        // Pass empty strings to the analyzer without warnings.
472        // Treat "*" as the universal lock.
473        Args.push_back(ArgExp);
474        continue;
475      }
476
477      // We allow constant strings to be used as a placeholder for expressions
478      // that are not valid C++ syntax, but warn that they are ignored.
479      S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
480        Attr.getName();
481      Args.push_back(ArgExp);
482      continue;
483    }
484
485    QualType ArgTy = ArgExp->getType();
486
487    // A pointer to member expression of the form  &MyClass::mu is treated
488    // specially -- we need to look at the type of the member.
489    if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
490      if (UOp->getOpcode() == UO_AddrOf)
491        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
492          if (DRE->getDecl()->isCXXInstanceMember())
493            ArgTy = DRE->getDecl()->getType();
494
495    // First see if we can just cast to record type, or point to record type.
496    const RecordType *RT = getRecordType(ArgTy);
497
498    // Now check if we index into a record type function param.
499    if(!RT && ParamIdxOk) {
500      FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
501      IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
502      if(FD && IL) {
503        unsigned int NumParams = FD->getNumParams();
504        llvm::APInt ArgValue = IL->getValue();
505        uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
506        uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
507        if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
508          S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
509            << Attr.getName() << Idx + 1 << NumParams;
510          continue;
511        }
512        ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
513      }
514    }
515
516    checkForLockableRecord(S, D, Attr, ArgTy);
517
518    Args.push_back(ArgExp);
519  }
520}
521
522//===----------------------------------------------------------------------===//
523// Attribute Implementations
524//===----------------------------------------------------------------------===//
525
526// FIXME: All this manual attribute parsing code is gross. At the
527// least add some helper functions to check most argument patterns (#
528// and types of args).
529
530enum ThreadAttributeDeclKind {
531  ThreadExpectedFieldOrGlobalVar,
532  ThreadExpectedFunctionOrMethod,
533  ThreadExpectedClassOrStruct
534};
535
536static bool checkGuardedVarAttrCommon(Sema &S, Decl *D,
537                                      const AttributeList &Attr) {
538  // D must be either a member field or global (potentially shared) variable.
539  if (!mayBeSharedVariable(D)) {
540    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
541      << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
542    return false;
543  }
544
545  return true;
546}
547
548static void handleGuardedVarAttr(Sema &S, Decl *D, const AttributeList &Attr) {
549  if (!checkGuardedVarAttrCommon(S, D, Attr))
550    return;
551
552  D->addAttr(::new (S.Context)
553             GuardedVarAttr(Attr.getRange(), S.Context,
554                            Attr.getAttributeSpellingListIndex()));
555}
556
557static void handlePtGuardedVarAttr(Sema &S, Decl *D,
558                                   const AttributeList &Attr) {
559  if (!checkGuardedVarAttrCommon(S, D, Attr))
560    return;
561
562  if (!threadSafetyCheckIsPointer(S, D, Attr))
563    return;
564
565  D->addAttr(::new (S.Context)
566             PtGuardedVarAttr(Attr.getRange(), S.Context,
567                              Attr.getAttributeSpellingListIndex()));
568}
569
570static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
571                                     const AttributeList &Attr,
572                                     Expr* &Arg) {
573  // D must be either a member field or global (potentially shared) variable.
574  if (!mayBeSharedVariable(D)) {
575    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
576      << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
577    return false;
578  }
579
580  SmallVector<Expr*, 1> Args;
581  // check that all arguments are lockable objects
582  checkAttrArgsAreLockableObjs(S, D, Attr, Args);
583  unsigned Size = Args.size();
584  if (Size != 1)
585    return false;
586
587  Arg = Args[0];
588
589  return true;
590}
591
592static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
593  Expr *Arg = 0;
594  if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
595    return;
596
597  D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg));
598}
599
600static void handlePtGuardedByAttr(Sema &S, Decl *D,
601                                  const AttributeList &Attr) {
602  Expr *Arg = 0;
603  if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
604    return;
605
606  if (!threadSafetyCheckIsPointer(S, D, Attr))
607    return;
608
609  D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
610                                               S.Context, Arg));
611}
612
613static bool checkLockableAttrCommon(Sema &S, Decl *D,
614                                    const AttributeList &Attr) {
615  // FIXME: Lockable structs for C code.
616  if (!isa<RecordDecl>(D)) {
617    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
618      << Attr.getName() << ThreadExpectedClassOrStruct;
619    return false;
620  }
621
622  return true;
623}
624
625static void handleLockableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
626  if (!checkLockableAttrCommon(S, D, Attr))
627    return;
628
629  D->addAttr(::new (S.Context) LockableAttr(Attr.getRange(), S.Context));
630}
631
632static void handleScopedLockableAttr(Sema &S, Decl *D,
633                             const AttributeList &Attr) {
634  if (!checkLockableAttrCommon(S, D, Attr))
635    return;
636
637  D->addAttr(::new (S.Context)
638             ScopedLockableAttr(Attr.getRange(), S.Context,
639                                Attr.getAttributeSpellingListIndex()));
640}
641
642static void handleNoThreadSafetyAnalysis(Sema &S, Decl *D,
643                                         const AttributeList &Attr) {
644  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
645    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
646      << Attr.getName() << ThreadExpectedFunctionOrMethod;
647    return;
648  }
649
650  D->addAttr(::new (S.Context) NoThreadSafetyAnalysisAttr(Attr.getRange(),
651                                                          S.Context));
652}
653
654static void handleNoSanitizeAddressAttr(Sema &S, Decl *D,
655                                      const AttributeList &Attr) {
656  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
657    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
658      << Attr.getName() << ExpectedFunctionOrMethod;
659    return;
660  }
661
662  D->addAttr(::new (S.Context)
663             NoSanitizeAddressAttr(Attr.getRange(), S.Context,
664                                   Attr.getAttributeSpellingListIndex()));
665}
666
667static void handleNoSanitizeMemory(Sema &S, Decl *D,
668                                   const AttributeList &Attr) {
669  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
670    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
671      << Attr.getName() << ExpectedFunctionOrMethod;
672    return;
673  }
674
675  D->addAttr(::new (S.Context) NoSanitizeMemoryAttr(Attr.getRange(),
676                                                         S.Context));
677}
678
679static void handleNoSanitizeThread(Sema &S, Decl *D,
680                                   const AttributeList &Attr) {
681  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
682    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
683      << Attr.getName() << ExpectedFunctionOrMethod;
684    return;
685  }
686
687  D->addAttr(::new (S.Context) NoSanitizeThreadAttr(Attr.getRange(),
688                                                    S.Context));
689}
690
691static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
692                                        const AttributeList &Attr,
693                                        SmallVectorImpl<Expr *> &Args) {
694  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
695    return false;
696
697  // D must be either a member field or global (potentially shared) variable.
698  ValueDecl *VD = dyn_cast<ValueDecl>(D);
699  if (!VD || !mayBeSharedVariable(D)) {
700    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
701      << Attr.getName() << ThreadExpectedFieldOrGlobalVar;
702    return false;
703  }
704
705  // Check that this attribute only applies to lockable types.
706  QualType QT = VD->getType();
707  if (!QT->isDependentType()) {
708    const RecordType *RT = getRecordType(QT);
709    if (!RT || !RT->getDecl()->getAttr<LockableAttr>()) {
710      S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
711        << Attr.getName();
712      return false;
713    }
714  }
715
716  // Check that all arguments are lockable objects.
717  checkAttrArgsAreLockableObjs(S, D, Attr, Args);
718  if (Args.empty())
719    return false;
720
721  return true;
722}
723
724static void handleAcquiredAfterAttr(Sema &S, Decl *D,
725                                    const AttributeList &Attr) {
726  SmallVector<Expr*, 1> Args;
727  if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
728    return;
729
730  Expr **StartArg = &Args[0];
731  D->addAttr(::new (S.Context)
732             AcquiredAfterAttr(Attr.getRange(), S.Context,
733                               StartArg, Args.size(),
734                               Attr.getAttributeSpellingListIndex()));
735}
736
737static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
738                                     const AttributeList &Attr) {
739  SmallVector<Expr*, 1> Args;
740  if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
741    return;
742
743  Expr **StartArg = &Args[0];
744  D->addAttr(::new (S.Context)
745             AcquiredBeforeAttr(Attr.getRange(), S.Context,
746                                StartArg, Args.size(),
747                                Attr.getAttributeSpellingListIndex()));
748}
749
750static bool checkLockFunAttrCommon(Sema &S, Decl *D,
751                                   const AttributeList &Attr,
752                                   SmallVectorImpl<Expr *> &Args) {
753  // zero or more arguments ok
754
755  // check that the attribute is applied to a function
756  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
757    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
758      << Attr.getName() << ThreadExpectedFunctionOrMethod;
759    return false;
760  }
761
762  // check that all arguments are lockable objects
763  checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
764
765  return true;
766}
767
768static void handleSharedLockFunctionAttr(Sema &S, Decl *D,
769                                         const AttributeList &Attr) {
770  SmallVector<Expr*, 1> Args;
771  if (!checkLockFunAttrCommon(S, D, Attr, Args))
772    return;
773
774  unsigned Size = Args.size();
775  Expr **StartArg = Size == 0 ? 0 : &Args[0];
776  D->addAttr(::new (S.Context)
777             SharedLockFunctionAttr(Attr.getRange(), S.Context, StartArg, Size,
778                                    Attr.getAttributeSpellingListIndex()));
779}
780
781static void handleExclusiveLockFunctionAttr(Sema &S, Decl *D,
782                                            const AttributeList &Attr) {
783  SmallVector<Expr*, 1> Args;
784  if (!checkLockFunAttrCommon(S, D, Attr, Args))
785    return;
786
787  unsigned Size = Args.size();
788  Expr **StartArg = Size == 0 ? 0 : &Args[0];
789  D->addAttr(::new (S.Context)
790             ExclusiveLockFunctionAttr(Attr.getRange(), S.Context,
791                                       StartArg, Size,
792                                       Attr.getAttributeSpellingListIndex()));
793}
794
795static void handleAssertSharedLockAttr(Sema &S, Decl *D,
796                                       const AttributeList &Attr) {
797  SmallVector<Expr*, 1> Args;
798  if (!checkLockFunAttrCommon(S, D, Attr, Args))
799    return;
800
801  unsigned Size = Args.size();
802  Expr **StartArg = Size == 0 ? 0 : &Args[0];
803  D->addAttr(::new (S.Context)
804             AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
805                                  Attr.getAttributeSpellingListIndex()));
806}
807
808static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
809                                          const AttributeList &Attr) {
810  SmallVector<Expr*, 1> Args;
811  if (!checkLockFunAttrCommon(S, D, Attr, Args))
812    return;
813
814  unsigned Size = Args.size();
815  Expr **StartArg = Size == 0 ? 0 : &Args[0];
816  D->addAttr(::new (S.Context)
817             AssertExclusiveLockAttr(Attr.getRange(), S.Context,
818                                     StartArg, Size,
819                                     Attr.getAttributeSpellingListIndex()));
820}
821
822
823static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
824                                      const AttributeList &Attr,
825                                      SmallVectorImpl<Expr *> &Args) {
826  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
827    return false;
828
829  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
830    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
831      << Attr.getName() << ThreadExpectedFunctionOrMethod;
832    return false;
833  }
834
835  if (!isIntOrBool(Attr.getArgAsExpr(0))) {
836    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
837      << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
838    return false;
839  }
840
841  // check that all arguments are lockable objects
842  checkAttrArgsAreLockableObjs(S, D, Attr, Args, 1);
843
844  return true;
845}
846
847static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
848                                            const AttributeList &Attr) {
849  SmallVector<Expr*, 2> Args;
850  if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
851    return;
852
853  D->addAttr(::new (S.Context)
854             SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
855                                       Attr.getArgAsExpr(0),
856                                       Args.data(), Args.size(),
857                                       Attr.getAttributeSpellingListIndex()));
858}
859
860static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
861                                               const AttributeList &Attr) {
862  SmallVector<Expr*, 2> Args;
863  if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
864    return;
865
866  D->addAttr(::new (S.Context)
867             ExclusiveTrylockFunctionAttr(Attr.getRange(), S.Context,
868                                          Attr.getArgAsExpr(0),
869                                          Args.data(), Args.size(),
870                                          Attr.getAttributeSpellingListIndex()));
871}
872
873static bool checkLocksRequiredCommon(Sema &S, Decl *D,
874                                     const AttributeList &Attr,
875                                     SmallVectorImpl<Expr *> &Args) {
876  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
877    return false;
878
879  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
880    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
881      << Attr.getName() << ThreadExpectedFunctionOrMethod;
882    return false;
883  }
884
885  // check that all arguments are lockable objects
886  checkAttrArgsAreLockableObjs(S, D, Attr, Args);
887  if (Args.empty())
888    return false;
889
890  return true;
891}
892
893static void handleExclusiveLocksRequiredAttr(Sema &S, Decl *D,
894                                             const AttributeList &Attr) {
895  SmallVector<Expr*, 1> Args;
896  if (!checkLocksRequiredCommon(S, D, Attr, Args))
897    return;
898
899  Expr **StartArg = &Args[0];
900  D->addAttr(::new (S.Context)
901             ExclusiveLocksRequiredAttr(Attr.getRange(), S.Context,
902                                        StartArg, Args.size(),
903                                        Attr.getAttributeSpellingListIndex()));
904}
905
906static void handleSharedLocksRequiredAttr(Sema &S, Decl *D,
907                                          const AttributeList &Attr) {
908  SmallVector<Expr*, 1> Args;
909  if (!checkLocksRequiredCommon(S, D, Attr, Args))
910    return;
911
912  Expr **StartArg = &Args[0];
913  D->addAttr(::new (S.Context)
914             SharedLocksRequiredAttr(Attr.getRange(), S.Context,
915                                     StartArg, Args.size(),
916                                     Attr.getAttributeSpellingListIndex()));
917}
918
919static void handleUnlockFunAttr(Sema &S, Decl *D,
920                                const AttributeList &Attr) {
921  // zero or more arguments ok
922
923  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
924    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
925      << Attr.getName() << ThreadExpectedFunctionOrMethod;
926    return;
927  }
928
929  // check that all arguments are lockable objects
930  SmallVector<Expr*, 1> Args;
931  checkAttrArgsAreLockableObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
932  unsigned Size = Args.size();
933  Expr **StartArg = Size == 0 ? 0 : &Args[0];
934
935  D->addAttr(::new (S.Context)
936             UnlockFunctionAttr(Attr.getRange(), S.Context, StartArg, Size,
937                                Attr.getAttributeSpellingListIndex()));
938}
939
940static void handleLockReturnedAttr(Sema &S, Decl *D,
941                                   const AttributeList &Attr) {
942  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
943    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
944      << Attr.getName() << ThreadExpectedFunctionOrMethod;
945    return;
946  }
947
948  // check that the argument is lockable object
949  SmallVector<Expr*, 1> Args;
950  checkAttrArgsAreLockableObjs(S, D, Attr, Args);
951  unsigned Size = Args.size();
952  if (Size == 0)
953    return;
954
955  D->addAttr(::new (S.Context)
956             LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
957                              Attr.getAttributeSpellingListIndex()));
958}
959
960static void handleLocksExcludedAttr(Sema &S, Decl *D,
961                                    const AttributeList &Attr) {
962  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
963    return;
964
965  if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D)) {
966    S.Diag(Attr.getLoc(), diag::warn_thread_attribute_wrong_decl_type)
967      << Attr.getName() << ThreadExpectedFunctionOrMethod;
968    return;
969  }
970
971  // check that all arguments are lockable objects
972  SmallVector<Expr*, 1> Args;
973  checkAttrArgsAreLockableObjs(S, D, Attr, Args);
974  unsigned Size = Args.size();
975  if (Size == 0)
976    return;
977  Expr **StartArg = &Args[0];
978
979  D->addAttr(::new (S.Context)
980             LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
981                               Attr.getAttributeSpellingListIndex()));
982}
983
984static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
985  ConsumableAttr::ConsumedState DefaultState;
986
987  if (Attr.isArgIdent(0)) {
988    IdentifierLoc *IL = Attr.getArgAsIdent(0);
989    if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
990                                                   DefaultState)) {
991      S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
992        << Attr.getName() << IL->Ident;
993      return;
994    }
995  } else {
996    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
997        << Attr.getName() << AANT_ArgumentIdentifier;
998    return;
999  }
1000
1001  if (!isa<CXXRecordDecl>(D)) {
1002    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1003      Attr.getName() << ExpectedClass;
1004    return;
1005  }
1006
1007  D->addAttr(::new (S.Context)
1008             ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
1009                            Attr.getAttributeSpellingListIndex()));
1010}
1011
1012static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1013                                        const AttributeList &Attr) {
1014  ASTContext &CurrContext = S.getASTContext();
1015  QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1016
1017  if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1018    if (!RD->hasAttr<ConsumableAttr>()) {
1019      S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1020        RD->getNameAsString();
1021
1022      return false;
1023    }
1024  }
1025
1026  return true;
1027}
1028
1029static void handleConsumesAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1030  if (!isa<CXXMethodDecl>(D)) {
1031    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1032      Attr.getName() << ExpectedMethod;
1033    return;
1034  }
1035
1036  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1037    return;
1038
1039  D->addAttr(::new (S.Context)
1040             ConsumesAttr(Attr.getRange(), S.Context,
1041                          Attr.getAttributeSpellingListIndex()));
1042}
1043
1044static void handleCallableWhenAttr(Sema &S, Decl *D,
1045                                   const AttributeList &Attr) {
1046
1047  if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) return;
1048
1049  if (!isa<CXXMethodDecl>(D)) {
1050    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1051      Attr.getName() << ExpectedMethod;
1052    return;
1053  }
1054
1055  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1056    return;
1057
1058  SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1059  for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
1060    CallableWhenAttr::ConsumedState CallableState;
1061
1062    StringRef StateString;
1063    SourceLocation Loc;
1064    if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
1065      return;
1066
1067    if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1068                                                      CallableState)) {
1069      S.Diag(Loc, diag::warn_attribute_type_not_supported)
1070        << Attr.getName() << StateString;
1071      return;
1072    }
1073
1074    States.push_back(CallableState);
1075  }
1076
1077  D->addAttr(::new (S.Context)
1078             CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
1079               States.size(), Attr.getAttributeSpellingListIndex()));
1080}
1081
1082
1083static void handleTestsTypestateAttr(Sema &S, Decl *D,
1084                                     const AttributeList &Attr) {
1085  if (!checkAttributeNumArgs(S, Attr, 1)) return;
1086
1087  if (!isa<CXXMethodDecl>(D)) {
1088    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1089      Attr.getName() << ExpectedMethod;
1090    return;
1091  }
1092
1093  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
1094    return;
1095
1096  TestsTypestateAttr::ConsumedState TestState;
1097
1098  if (Attr.isArgIdent(0)) {
1099    StringRef Param = Attr.getArgAsIdent(0)->Ident->getName();
1100
1101    if (Param == "consumed") {
1102      TestState = TestsTypestateAttr::Consumed;
1103    } else if (Param == "unconsumed") {
1104      TestState = TestsTypestateAttr::Unconsumed;
1105    } else {
1106      S.Diag(Attr.getLoc(), diag::warn_invalid_test_typestate) << Param;
1107      return;
1108    }
1109
1110  } else {
1111    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1112      Attr.getName() << AANT_ArgumentIdentifier;
1113    return;
1114  }
1115
1116  D->addAttr(::new (S.Context)
1117             TestsTypestateAttr(Attr.getRange(), S.Context, TestState,
1118                                Attr.getAttributeSpellingListIndex()));
1119}
1120
1121static void handleReturnTypestateAttr(Sema &S, Decl *D,
1122                                      const AttributeList &Attr) {
1123  ReturnTypestateAttr::ConsumedState ReturnState;
1124
1125  if (Attr.isArgIdent(0)) {
1126    IdentifierLoc *IL = Attr.getArgAsIdent(0);
1127    if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1128                                                        ReturnState)) {
1129      S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1130        << Attr.getName() << IL->Ident;
1131      return;
1132    }
1133  } else {
1134    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
1135      Attr.getName() << AANT_ArgumentIdentifier;
1136    return;
1137  }
1138
1139  if (!isa<FunctionDecl>(D)) {
1140    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
1141      Attr.getName() << ExpectedFunction;
1142    return;
1143  }
1144
1145  // FIXME: This check is currently being done in the analysis.  It can be
1146  //        enabled here only after the parser propagates attributes at
1147  //        template specialization definition, not declaration.
1148  //QualType ReturnType;
1149  //
1150  //if (const CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1151  //  ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1152  //
1153  //} else {
1154  //
1155  //  ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1156  //}
1157  //
1158  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1159  //
1160  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1161  //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1162  //      ReturnType.getAsString();
1163  //    return;
1164  //}
1165
1166  D->addAttr(::new (S.Context)
1167             ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
1168                                 Attr.getAttributeSpellingListIndex()));
1169}
1170
1171static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
1172                                    const AttributeList &Attr) {
1173  TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
1174  if (TD == 0) {
1175    // __attribute__((ext_vector_type(N))) can only be applied to typedefs
1176    // and type-ids.
1177    S.Diag(Attr.getLoc(), diag::err_typecheck_ext_vector_not_typedef);
1178    return;
1179  }
1180
1181  // Remember this typedef decl, we will need it later for diagnostics.
1182  S.ExtVectorDecls.push_back(TD);
1183}
1184
1185static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1186  if (TagDecl *TD = dyn_cast<TagDecl>(D))
1187    TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context));
1188  else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1189    // If the alignment is less than or equal to 8 bits, the packed attribute
1190    // has no effect.
1191    if (!FD->getType()->isDependentType() &&
1192        !FD->getType()->isIncompleteType() &&
1193        S.Context.getTypeAlign(FD->getType()) <= 8)
1194      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1195        << Attr.getName() << FD->getType();
1196    else
1197      FD->addAttr(::new (S.Context)
1198                  PackedAttr(Attr.getRange(), S.Context,
1199                             Attr.getAttributeSpellingListIndex()));
1200  } else
1201    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1202}
1203
1204static void handleMsStructAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1205  if (RecordDecl *RD = dyn_cast<RecordDecl>(D))
1206    RD->addAttr(::new (S.Context)
1207                MsStructAttr(Attr.getRange(), S.Context,
1208                             Attr.getAttributeSpellingListIndex()));
1209  else
1210    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
1211}
1212
1213static void handleIBAction(Sema &S, Decl *D, const AttributeList &Attr) {
1214  // The IBAction attributes only apply to instance methods.
1215  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
1216    if (MD->isInstanceMethod()) {
1217      D->addAttr(::new (S.Context)
1218                 IBActionAttr(Attr.getRange(), S.Context,
1219                              Attr.getAttributeSpellingListIndex()));
1220      return;
1221    }
1222
1223  S.Diag(Attr.getLoc(), diag::warn_attribute_ibaction) << Attr.getName();
1224}
1225
1226static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
1227  // The IBOutlet/IBOutletCollection attributes only apply to instance
1228  // variables or properties of Objective-C classes.  The outlet must also
1229  // have an object reference type.
1230  if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
1231    if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1232      S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1233        << Attr.getName() << VD->getType() << 0;
1234      return false;
1235    }
1236  }
1237  else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1238    if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1239      S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
1240        << Attr.getName() << PD->getType() << 1;
1241      return false;
1242    }
1243  }
1244  else {
1245    S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
1246    return false;
1247  }
1248
1249  return true;
1250}
1251
1252static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
1253  if (!checkIBOutletCommon(S, D, Attr))
1254    return;
1255
1256  D->addAttr(::new (S.Context)
1257             IBOutletAttr(Attr.getRange(), S.Context,
1258                          Attr.getAttributeSpellingListIndex()));
1259}
1260
1261static void handleIBOutletCollection(Sema &S, Decl *D,
1262                                     const AttributeList &Attr) {
1263
1264  // The iboutletcollection attribute can have zero or one arguments.
1265  if (Attr.getNumArgs() > 1) {
1266    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1267      << Attr.getName() << 1;
1268    return;
1269  }
1270
1271  if (!checkIBOutletCommon(S, D, Attr))
1272    return;
1273
1274  IdentifierLoc *IL = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : 0;
1275  IdentifierInfo *II;
1276  SourceLocation ILS;
1277  if (IL) {
1278    II = IL->Ident;
1279    ILS = IL->Loc;
1280  } else {
1281    II = &S.Context.Idents.get("NSObject");
1282  }
1283
1284  ParsedType TypeRep = S.getTypeName(*II, Attr.getLoc(),
1285                        S.getScopeForContext(D->getDeclContext()->getParent()));
1286  if (!TypeRep) {
1287    S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
1288    return;
1289  }
1290  QualType QT = TypeRep.get();
1291  // Diagnose use of non-object type in iboutletcollection attribute.
1292  // FIXME. Gnu attribute extension ignores use of builtin types in
1293  // attributes. So, __attribute__((iboutletcollection(char))) will be
1294  // treated as __attribute__((iboutletcollection())).
1295  if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1296    S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << II;
1297    return;
1298  }
1299  D->addAttr(::new (S.Context)
1300             IBOutletCollectionAttr(Attr.getRange(), S.Context, QT, ILS,
1301                                    Attr.getAttributeSpellingListIndex()));
1302}
1303
1304static void possibleTransparentUnionPointerType(QualType &T) {
1305  if (const RecordType *UT = T->getAsUnionType())
1306    if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1307      RecordDecl *UD = UT->getDecl();
1308      for (RecordDecl::field_iterator it = UD->field_begin(),
1309           itend = UD->field_end(); it != itend; ++it) {
1310        QualType QT = it->getType();
1311        if (QT->isAnyPointerType() || QT->isBlockPointerType()) {
1312          T = QT;
1313          return;
1314        }
1315      }
1316    }
1317}
1318
1319static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1320  if (!isFunctionOrMethod(D)) {
1321    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1322    << Attr.getName() << ExpectedFunctionOrMethod;
1323    return;
1324  }
1325
1326  if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
1327    return;
1328
1329  SmallVector<unsigned, 8> SizeArgs;
1330  for (unsigned i = 0; i < Attr.getNumArgs(); ++i) {
1331    Expr *Ex = Attr.getArgAsExpr(i);
1332    uint64_t Idx;
1333    if (!checkFunctionOrMethodArgumentIndex(S, D, Attr.getName()->getName(),
1334                                            Attr.getLoc(), i + 1, Ex, Idx))
1335      return;
1336
1337    // check if the function argument is of an integer type
1338    QualType T = getFunctionOrMethodArgType(D, Idx).getNonReferenceType();
1339    if (!T->isIntegerType()) {
1340      S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
1341        << Attr.getName() << AANT_ArgumentIntegerConstant
1342        << Ex->getSourceRange();
1343      return;
1344    }
1345    SizeArgs.push_back(Idx);
1346  }
1347
1348  // check if the function returns a pointer
1349  if (!getFunctionType(D)->getResultType()->isAnyPointerType()) {
1350    S.Diag(Attr.getLoc(), diag::warn_ns_attribute_wrong_return_type)
1351    << Attr.getName() << 0 /*function*/<< 1 /*pointer*/ << D->getSourceRange();
1352  }
1353
1354  D->addAttr(::new (S.Context)
1355             AllocSizeAttr(Attr.getRange(), S.Context,
1356                           SizeArgs.data(), SizeArgs.size(),
1357                           Attr.getAttributeSpellingListIndex()));
1358}
1359
1360static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1361  // GCC ignores the nonnull attribute on K&R style function prototypes, so we
1362  // ignore it as well
1363  if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
1364    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1365      << Attr.getName() << ExpectedFunction;
1366    return;
1367  }
1368
1369  SmallVector<unsigned, 8> NonNullArgs;
1370  for (unsigned i = 0; i < Attr.getNumArgs(); ++i) {
1371    Expr *Ex = Attr.getArgAsExpr(i);
1372    uint64_t Idx;
1373    if (!checkFunctionOrMethodArgumentIndex(S, D, Attr.getName()->getName(),
1374                                            Attr.getLoc(), i + 1, Ex, Idx))
1375      return;
1376
1377    // Is the function argument a pointer type?
1378    QualType T = getFunctionOrMethodArgType(D, Idx).getNonReferenceType();
1379    possibleTransparentUnionPointerType(T);
1380
1381    if (!T->isAnyPointerType() && !T->isBlockPointerType()) {
1382      // FIXME: Should also highlight argument in decl.
1383      S.Diag(Attr.getLoc(), diag::warn_nonnull_pointers_only)
1384        << "nonnull" << Ex->getSourceRange();
1385      continue;
1386    }
1387
1388    NonNullArgs.push_back(Idx);
1389  }
1390
1391  // If no arguments were specified to __attribute__((nonnull)) then all pointer
1392  // arguments have a nonnull attribute.
1393  if (NonNullArgs.empty()) {
1394    for (unsigned i = 0, e = getFunctionOrMethodNumArgs(D); i != e; ++i) {
1395      QualType T = getFunctionOrMethodArgType(D, i).getNonReferenceType();
1396      possibleTransparentUnionPointerType(T);
1397      if (T->isAnyPointerType() || T->isBlockPointerType())
1398        NonNullArgs.push_back(i);
1399    }
1400
1401    // No pointer arguments?
1402    if (NonNullArgs.empty()) {
1403      // Warn the trivial case only if attribute is not coming from a
1404      // macro instantiation.
1405      if (Attr.getLoc().isFileID())
1406        S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1407      return;
1408    }
1409  }
1410
1411  unsigned *start = &NonNullArgs[0];
1412  unsigned size = NonNullArgs.size();
1413  llvm::array_pod_sort(start, start + size);
1414  D->addAttr(::new (S.Context)
1415             NonNullAttr(Attr.getRange(), S.Context, start, size,
1416                         Attr.getAttributeSpellingListIndex()));
1417}
1418
1419static const char *ownershipKindToDiagName(OwnershipAttr::OwnershipKind K) {
1420  switch (K) {
1421    case OwnershipAttr::Holds:    return "'ownership_holds'";
1422    case OwnershipAttr::Takes:    return "'ownership_takes'";
1423    case OwnershipAttr::Returns:  return "'ownership_returns'";
1424  }
1425  llvm_unreachable("unknown ownership");
1426}
1427
1428static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
1429  // This attribute must be applied to a function declaration. The first
1430  // argument to the attribute must be an identifier, the name of the resource,
1431  // for example: malloc. The following arguments must be argument indexes, the
1432  // arguments must be of integer type for Returns, otherwise of pointer type.
1433  // The difference between Holds and Takes is that a pointer may still be used
1434  // after being held. free() should be __attribute((ownership_takes)), whereas
1435  // a list append function may well be __attribute((ownership_holds)).
1436
1437  if (!AL.isArgIdent(0)) {
1438    S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1439      << AL.getName() << 1 << AANT_ArgumentIdentifier;
1440    return;
1441  }
1442
1443  // Figure out our Kind, and check arguments while we're at it.
1444  OwnershipAttr::OwnershipKind K;
1445  switch (AL.getKind()) {
1446  case AttributeList::AT_ownership_takes:
1447    K = OwnershipAttr::Takes;
1448    if (AL.getNumArgs() < 2) {
1449      S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << 2;
1450      return;
1451    }
1452    break;
1453  case AttributeList::AT_ownership_holds:
1454    K = OwnershipAttr::Holds;
1455    if (AL.getNumArgs() < 2) {
1456      S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << 2;
1457      return;
1458    }
1459    break;
1460  case AttributeList::AT_ownership_returns:
1461    K = OwnershipAttr::Returns;
1462
1463    if (AL.getNumArgs() > 2) {
1464      S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1465      return;
1466    }
1467    break;
1468  default:
1469    // This should never happen given how we are called.
1470    llvm_unreachable("Unknown ownership attribute");
1471  }
1472
1473  if (!isFunction(D) || !hasFunctionProto(D)) {
1474    S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
1475      << AL.getName() << ExpectedFunction;
1476    return;
1477  }
1478
1479  StringRef Module = AL.getArgAsIdent(0)->Ident->getName();
1480
1481  // Normalize the argument, __foo__ becomes foo.
1482  if (Module.startswith("__") && Module.endswith("__"))
1483    Module = Module.substr(2, Module.size() - 4);
1484
1485  SmallVector<unsigned, 8> OwnershipArgs;
1486  for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1487    Expr *Ex = AL.getArgAsExpr(i);
1488    uint64_t Idx;
1489    if (!checkFunctionOrMethodArgumentIndex(S, D, AL.getName()->getName(),
1490                                            AL.getLoc(), i, Ex, Idx))
1491      return;
1492
1493    // Is the function argument a pointer type?
1494    QualType T = getFunctionOrMethodArgType(D, Idx);
1495    int Err = -1;  // No error
1496    switch (K) {
1497      case OwnershipAttr::Takes:
1498      case OwnershipAttr::Holds:
1499        if (!T->isAnyPointerType() && !T->isBlockPointerType())
1500          Err = 0;
1501        break;
1502      case OwnershipAttr::Returns:
1503        if (!T->isIntegerType())
1504          Err = 1;
1505        break;
1506    }
1507    if (-1 != Err) {
1508      S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1509        << Ex->getSourceRange();
1510      return;
1511    }
1512
1513    // Check we don't have a conflict with another ownership attribute.
1514    for (specific_attr_iterator<OwnershipAttr>
1515         i = D->specific_attr_begin<OwnershipAttr>(),
1516         e = D->specific_attr_end<OwnershipAttr>(); i != e; ++i) {
1517      if ((*i)->getOwnKind() != K && (*i)->args_end() !=
1518          std::find((*i)->args_begin(), (*i)->args_end(), Idx)) {
1519        S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1520          << AL.getName() << ownershipKindToDiagName((*i)->getOwnKind());
1521        return;
1522      }
1523    }
1524    OwnershipArgs.push_back(Idx);
1525  }
1526
1527  unsigned* start = OwnershipArgs.data();
1528  unsigned size = OwnershipArgs.size();
1529  llvm::array_pod_sort(start, start + size);
1530
1531  D->addAttr(::new (S.Context)
1532             OwnershipAttr(AL.getLoc(), S.Context, K, Module, start, size,
1533                           AL.getAttributeSpellingListIndex()));
1534}
1535
1536static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1537  // Check the attribute arguments.
1538  if (Attr.getNumArgs() > 1) {
1539    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
1540      << Attr.getName() << 1;
1541    return;
1542  }
1543
1544  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
1545    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1546      << Attr.getName() << ExpectedVariableOrFunction;
1547    return;
1548  }
1549
1550  NamedDecl *nd = cast<NamedDecl>(D);
1551
1552  // gcc rejects
1553  // class c {
1554  //   static int a __attribute__((weakref ("v2")));
1555  //   static int b() __attribute__((weakref ("f3")));
1556  // };
1557  // and ignores the attributes of
1558  // void f(void) {
1559  //   static int a __attribute__((weakref ("v2")));
1560  // }
1561  // we reject them
1562  const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1563  if (!Ctx->isFileContext()) {
1564    S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) <<
1565        nd->getNameAsString();
1566    return;
1567  }
1568
1569  // The GCC manual says
1570  //
1571  // At present, a declaration to which `weakref' is attached can only
1572  // be `static'.
1573  //
1574  // It also says
1575  //
1576  // Without a TARGET,
1577  // given as an argument to `weakref' or to `alias', `weakref' is
1578  // equivalent to `weak'.
1579  //
1580  // gcc 4.4.1 will accept
1581  // int a7 __attribute__((weakref));
1582  // as
1583  // int a7 __attribute__((weak));
1584  // This looks like a bug in gcc. We reject that for now. We should revisit
1585  // it if this behaviour is actually used.
1586
1587  // GCC rejects
1588  // static ((alias ("y"), weakref)).
1589  // Should we? How to check that weakref is before or after alias?
1590
1591  // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1592  // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
1593  // StringRef parameter it was given anyway.
1594  StringRef Str;
1595  if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1596    // GCC will accept anything as the argument of weakref. Should we
1597    // check for an existing decl?
1598    D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1599                                        Attr.getAttributeSpellingListIndex()));
1600
1601  D->addAttr(::new (S.Context)
1602             WeakRefAttr(Attr.getRange(), S.Context,
1603                         Attr.getAttributeSpellingListIndex()));
1604}
1605
1606static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1607  StringRef Str;
1608  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
1609    return;
1610
1611  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1612    S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
1613    return;
1614  }
1615
1616  // FIXME: check if target symbol exists in current file
1617
1618  D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
1619                                         Attr.getAttributeSpellingListIndex()));
1620}
1621
1622static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1623  if (!isa<FunctionDecl>(D) && !isa<ObjCMethodDecl>(D)) {
1624    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1625      << Attr.getName() << ExpectedFunctionOrMethod;
1626    return;
1627  }
1628
1629  D->addAttr(::new (S.Context)
1630             MinSizeAttr(Attr.getRange(), S.Context,
1631                         Attr.getAttributeSpellingListIndex()));
1632}
1633
1634static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1635  if (!isa<FunctionDecl>(D)) {
1636    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1637      << Attr.getName() << ExpectedFunction;
1638    return;
1639  }
1640
1641  if (D->hasAttr<HotAttr>()) {
1642    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1643      << Attr.getName() << "hot";
1644    return;
1645  }
1646
1647  D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
1648                                        Attr.getAttributeSpellingListIndex()));
1649}
1650
1651static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1652  if (!isa<FunctionDecl>(D)) {
1653    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1654      << Attr.getName() << ExpectedFunction;
1655    return;
1656  }
1657
1658  if (D->hasAttr<ColdAttr>()) {
1659    S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
1660      << Attr.getName() << "cold";
1661    return;
1662  }
1663
1664  D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
1665                                       Attr.getAttributeSpellingListIndex()));
1666}
1667
1668static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1669  if (!isa<FunctionDecl>(D)) {
1670    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1671      << Attr.getName() << ExpectedFunction;
1672    return;
1673  }
1674
1675  D->addAttr(::new (S.Context)
1676             NakedAttr(Attr.getRange(), S.Context,
1677                       Attr.getAttributeSpellingListIndex()));
1678}
1679
1680static void handleAlwaysInlineAttr(Sema &S, Decl *D,
1681                                   const AttributeList &Attr) {
1682  if (!isa<FunctionDecl>(D)) {
1683    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1684      << Attr.getName() << ExpectedFunction;
1685    return;
1686  }
1687
1688  D->addAttr(::new (S.Context)
1689             AlwaysInlineAttr(Attr.getRange(), S.Context,
1690                              Attr.getAttributeSpellingListIndex()));
1691}
1692
1693static void handleTLSModelAttr(Sema &S, Decl *D,
1694                               const AttributeList &Attr) {
1695  StringRef Model;
1696  SourceLocation LiteralLoc;
1697  // Check that it is a string.
1698  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
1699    return;
1700
1701  if (!isa<VarDecl>(D) || !cast<VarDecl>(D)->getTLSKind()) {
1702    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1703      << Attr.getName() << ExpectedTLSVar;
1704    return;
1705  }
1706
1707  // Check that the value.
1708  if (Model != "global-dynamic" && Model != "local-dynamic"
1709      && Model != "initial-exec" && Model != "local-exec") {
1710    S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1711    return;
1712  }
1713
1714  D->addAttr(::new (S.Context)
1715             TLSModelAttr(Attr.getRange(), S.Context, Model,
1716                          Attr.getAttributeSpellingListIndex()));
1717}
1718
1719static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1720  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1721    QualType RetTy = FD->getResultType();
1722    if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) {
1723      D->addAttr(::new (S.Context)
1724                 MallocAttr(Attr.getRange(), S.Context,
1725                            Attr.getAttributeSpellingListIndex()));
1726      return;
1727    }
1728  }
1729
1730  S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only);
1731}
1732
1733static void handleMayAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1734  D->addAttr(::new (S.Context)
1735             MayAliasAttr(Attr.getRange(), S.Context,
1736                          Attr.getAttributeSpellingListIndex()));
1737}
1738
1739static void handleNoCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1740  if (isa<VarDecl>(D))
1741    D->addAttr(::new (S.Context)
1742               NoCommonAttr(Attr.getRange(), S.Context,
1743                            Attr.getAttributeSpellingListIndex()));
1744  else
1745    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1746      << Attr.getName() << ExpectedVariable;
1747}
1748
1749static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1750  if (S.LangOpts.CPlusPlus) {
1751    S.Diag(Attr.getLoc(), diag::err_common_not_supported_cplusplus);
1752    return;
1753  }
1754
1755  if (isa<VarDecl>(D))
1756    D->addAttr(::new (S.Context)
1757               CommonAttr(Attr.getRange(), S.Context,
1758                          Attr.getAttributeSpellingListIndex()));
1759  else
1760    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1761      << Attr.getName() << ExpectedVariable;
1762}
1763
1764static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
1765  if (hasDeclarator(D)) return;
1766
1767  if (S.CheckNoReturnAttr(attr)) return;
1768
1769  if (!isa<ObjCMethodDecl>(D)) {
1770    S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1771      << attr.getName() << ExpectedFunctionOrMethod;
1772    return;
1773  }
1774
1775  D->addAttr(::new (S.Context)
1776             NoReturnAttr(attr.getRange(), S.Context,
1777                          attr.getAttributeSpellingListIndex()));
1778}
1779
1780bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
1781  if (!checkAttributeNumArgs(*this, attr, 0)) {
1782    attr.setInvalid();
1783    return true;
1784  }
1785
1786  return false;
1787}
1788
1789static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
1790                                       const AttributeList &Attr) {
1791
1792  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1793  // because 'analyzer_noreturn' does not impact the type.
1794  if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) {
1795    ValueDecl *VD = dyn_cast<ValueDecl>(D);
1796    if (VD == 0 || (!VD->getType()->isBlockPointerType()
1797                    && !VD->getType()->isFunctionPointerType())) {
1798      S.Diag(Attr.getLoc(),
1799             Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1800             : diag::warn_attribute_wrong_decl_type)
1801        << Attr.getName() << ExpectedFunctionMethodOrBlock;
1802      return;
1803    }
1804  }
1805
1806  D->addAttr(::new (S.Context)
1807             AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
1808                                  Attr.getAttributeSpellingListIndex()));
1809}
1810
1811static void handleCXX11NoReturnAttr(Sema &S, Decl *D,
1812                                    const AttributeList &Attr) {
1813  // C++11 [dcl.attr.noreturn]p1:
1814  //   The attribute may be applied to the declarator-id in a function
1815  //   declaration.
1816  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1817  if (!FD) {
1818    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1819      << Attr.getName() << ExpectedFunctionOrMethod;
1820    return;
1821  }
1822
1823  D->addAttr(::new (S.Context)
1824             CXX11NoReturnAttr(Attr.getRange(), S.Context,
1825                               Attr.getAttributeSpellingListIndex()));
1826}
1827
1828// PS3 PPU-specific.
1829static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1830/*
1831  Returning a Vector Class in Registers
1832
1833  According to the PPU ABI specifications, a class with a single member of
1834  vector type is returned in memory when used as the return value of a function.
1835  This results in inefficient code when implementing vector classes. To return
1836  the value in a single vector register, add the vecreturn attribute to the
1837  class definition. This attribute is also applicable to struct types.
1838
1839  Example:
1840
1841  struct Vector
1842  {
1843    __vector float xyzw;
1844  } __attribute__((vecreturn));
1845
1846  Vector Add(Vector lhs, Vector rhs)
1847  {
1848    Vector result;
1849    result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1850    return result; // This will be returned in a register
1851  }
1852*/
1853  if (!isa<RecordDecl>(D)) {
1854    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1855      << Attr.getName() << ExpectedClass;
1856    return;
1857  }
1858
1859  if (D->getAttr<VecReturnAttr>()) {
1860    S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << "vecreturn";
1861    return;
1862  }
1863
1864  RecordDecl *record = cast<RecordDecl>(D);
1865  int count = 0;
1866
1867  if (!isa<CXXRecordDecl>(record)) {
1868    S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1869    return;
1870  }
1871
1872  if (!cast<CXXRecordDecl>(record)->isPOD()) {
1873    S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1874    return;
1875  }
1876
1877  for (RecordDecl::field_iterator iter = record->field_begin();
1878       iter != record->field_end(); iter++) {
1879    if ((count == 1) || !iter->getType()->isVectorType()) {
1880      S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1881      return;
1882    }
1883    count++;
1884  }
1885
1886  D->addAttr(::new (S.Context)
1887             VecReturnAttr(Attr.getRange(), S.Context,
1888                           Attr.getAttributeSpellingListIndex()));
1889}
1890
1891static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
1892                                 const AttributeList &Attr) {
1893  if (isa<ParmVarDecl>(D)) {
1894    // [[carries_dependency]] can only be applied to a parameter if it is a
1895    // parameter of a function declaration or lambda.
1896    if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
1897      S.Diag(Attr.getLoc(),
1898             diag::err_carries_dependency_param_not_function_decl);
1899      return;
1900    }
1901  } else if (!isa<FunctionDecl>(D)) {
1902    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
1903      << Attr.getName() << ExpectedFunctionMethodOrParameter;
1904    return;
1905  }
1906
1907  D->addAttr(::new (S.Context) CarriesDependencyAttr(
1908                                   Attr.getRange(), S.Context,
1909                                   Attr.getAttributeSpellingListIndex()));
1910}
1911
1912static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1913  if (!isa<VarDecl>(D) && !isa<ObjCIvarDecl>(D) && !isFunctionOrMethod(D) &&
1914      !isa<TypeDecl>(D) && !isa<LabelDecl>(D) && !isa<FieldDecl>(D)) {
1915    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1916      << Attr.getName() << ExpectedVariableFunctionOrLabel;
1917    return;
1918  }
1919
1920  D->addAttr(::new (S.Context)
1921             UnusedAttr(Attr.getRange(), S.Context,
1922                        Attr.getAttributeSpellingListIndex()));
1923}
1924
1925static void handleReturnsTwiceAttr(Sema &S, Decl *D,
1926                                   const AttributeList &Attr) {
1927  if (!isa<FunctionDecl>(D)) {
1928    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1929      << Attr.getName() << ExpectedFunction;
1930    return;
1931  }
1932
1933  D->addAttr(::new (S.Context)
1934             ReturnsTwiceAttr(Attr.getRange(), S.Context,
1935                              Attr.getAttributeSpellingListIndex()));
1936}
1937
1938static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1939  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1940    if (VD->hasLocalStorage()) {
1941      S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "used";
1942      return;
1943    }
1944  } else if (!isFunctionOrMethod(D)) {
1945    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1946      << Attr.getName() << ExpectedVariableOrFunction;
1947    return;
1948  }
1949
1950  D->addAttr(::new (S.Context)
1951             UsedAttr(Attr.getRange(), S.Context,
1952                      Attr.getAttributeSpellingListIndex()));
1953}
1954
1955static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1956  // check the attribute arguments.
1957  if (Attr.getNumArgs() > 1) {
1958    S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1959    return;
1960  }
1961
1962  int priority = 65535; // FIXME: Do not hardcode such constants.
1963  if (Attr.getNumArgs() > 0) {
1964    Expr *E = Attr.getArgAsExpr(0);
1965    llvm::APSInt Idx(32);
1966    if (E->isTypeDependent() || E->isValueDependent() ||
1967        !E->isIntegerConstantExpr(Idx, S.Context)) {
1968      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
1969        << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
1970        << E->getSourceRange();
1971      return;
1972    }
1973    priority = Idx.getZExtValue();
1974  }
1975
1976  if (!isa<FunctionDecl>(D)) {
1977    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
1978      << Attr.getName() << ExpectedFunction;
1979    return;
1980  }
1981
1982  D->addAttr(::new (S.Context)
1983             ConstructorAttr(Attr.getRange(), S.Context, priority,
1984                             Attr.getAttributeSpellingListIndex()));
1985}
1986
1987static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
1988  // check the attribute arguments.
1989  if (Attr.getNumArgs() > 1) {
1990    S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
1991    return;
1992  }
1993
1994  int priority = 65535; // FIXME: Do not hardcode such constants.
1995  if (Attr.getNumArgs() > 0) {
1996    Expr *E = Attr.getArgAsExpr(0);
1997    llvm::APSInt Idx(32);
1998    if (E->isTypeDependent() || E->isValueDependent() ||
1999        !E->isIntegerConstantExpr(Idx, S.Context)) {
2000      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2001        << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2002        << E->getSourceRange();
2003      return;
2004    }
2005    priority = Idx.getZExtValue();
2006  }
2007
2008  if (!isa<FunctionDecl>(D)) {
2009    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2010      << Attr.getName() << ExpectedFunction;
2011    return;
2012  }
2013
2014  D->addAttr(::new (S.Context)
2015             DestructorAttr(Attr.getRange(), S.Context, priority,
2016                            Attr.getAttributeSpellingListIndex()));
2017}
2018
2019template <typename AttrTy>
2020static void handleAttrWithMessage(Sema &S, Decl *D,
2021                                  const AttributeList &Attr) {
2022  unsigned NumArgs = Attr.getNumArgs();
2023  if (NumArgs > 1) {
2024    S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 1;
2025    return;
2026  }
2027
2028  // Handle the case where the attribute has a text message.
2029  StringRef Str;
2030  if (NumArgs == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
2031    return;
2032
2033  D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
2034                                      Attr.getAttributeSpellingListIndex()));
2035}
2036
2037static void handleArcWeakrefUnavailableAttr(Sema &S, Decl *D,
2038                                            const AttributeList &Attr) {
2039  D->addAttr(::new (S.Context)
2040             ArcWeakrefUnavailableAttr(Attr.getRange(), S.Context,
2041                                       Attr.getAttributeSpellingListIndex()));
2042}
2043
2044static void handleObjCRootClassAttr(Sema &S, Decl *D,
2045                                    const AttributeList &Attr) {
2046  if (!isa<ObjCInterfaceDecl>(D)) {
2047    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2048      << Attr.getName() << ExpectedObjectiveCInterface;
2049    return;
2050  }
2051
2052  D->addAttr(::new (S.Context)
2053             ObjCRootClassAttr(Attr.getRange(), S.Context,
2054                               Attr.getAttributeSpellingListIndex()));
2055}
2056
2057static void handleObjCRequiresPropertyDefsAttr(Sema &S, Decl *D,
2058                                               const AttributeList &Attr) {
2059  if (!isa<ObjCInterfaceDecl>(D)) {
2060    S.Diag(Attr.getLoc(), diag::err_suppress_autosynthesis);
2061    return;
2062  }
2063
2064  D->addAttr(::new (S.Context)
2065             ObjCRequiresPropertyDefsAttr(Attr.getRange(), S.Context,
2066                                          Attr.getAttributeSpellingListIndex()));
2067}
2068
2069static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2070                                  IdentifierInfo *Platform,
2071                                  VersionTuple Introduced,
2072                                  VersionTuple Deprecated,
2073                                  VersionTuple Obsoleted) {
2074  StringRef PlatformName
2075    = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2076  if (PlatformName.empty())
2077    PlatformName = Platform->getName();
2078
2079  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2080  // of these steps are needed).
2081  if (!Introduced.empty() && !Deprecated.empty() &&
2082      !(Introduced <= Deprecated)) {
2083    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2084      << 1 << PlatformName << Deprecated.getAsString()
2085      << 0 << Introduced.getAsString();
2086    return true;
2087  }
2088
2089  if (!Introduced.empty() && !Obsoleted.empty() &&
2090      !(Introduced <= Obsoleted)) {
2091    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2092      << 2 << PlatformName << Obsoleted.getAsString()
2093      << 0 << Introduced.getAsString();
2094    return true;
2095  }
2096
2097  if (!Deprecated.empty() && !Obsoleted.empty() &&
2098      !(Deprecated <= Obsoleted)) {
2099    S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2100      << 2 << PlatformName << Obsoleted.getAsString()
2101      << 1 << Deprecated.getAsString();
2102    return true;
2103  }
2104
2105  return false;
2106}
2107
2108/// \brief Check whether the two versions match.
2109///
2110/// If either version tuple is empty, then they are assumed to match. If
2111/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2112static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2113                          bool BeforeIsOkay) {
2114  if (X.empty() || Y.empty())
2115    return true;
2116
2117  if (X == Y)
2118    return true;
2119
2120  if (BeforeIsOkay && X < Y)
2121    return true;
2122
2123  return false;
2124}
2125
2126AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2127                                              IdentifierInfo *Platform,
2128                                              VersionTuple Introduced,
2129                                              VersionTuple Deprecated,
2130                                              VersionTuple Obsoleted,
2131                                              bool IsUnavailable,
2132                                              StringRef Message,
2133                                              bool Override,
2134                                              unsigned AttrSpellingListIndex) {
2135  VersionTuple MergedIntroduced = Introduced;
2136  VersionTuple MergedDeprecated = Deprecated;
2137  VersionTuple MergedObsoleted = Obsoleted;
2138  bool FoundAny = false;
2139
2140  if (D->hasAttrs()) {
2141    AttrVec &Attrs = D->getAttrs();
2142    for (unsigned i = 0, e = Attrs.size(); i != e;) {
2143      const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2144      if (!OldAA) {
2145        ++i;
2146        continue;
2147      }
2148
2149      IdentifierInfo *OldPlatform = OldAA->getPlatform();
2150      if (OldPlatform != Platform) {
2151        ++i;
2152        continue;
2153      }
2154
2155      FoundAny = true;
2156      VersionTuple OldIntroduced = OldAA->getIntroduced();
2157      VersionTuple OldDeprecated = OldAA->getDeprecated();
2158      VersionTuple OldObsoleted = OldAA->getObsoleted();
2159      bool OldIsUnavailable = OldAA->getUnavailable();
2160
2161      if (!versionsMatch(OldIntroduced, Introduced, Override) ||
2162          !versionsMatch(Deprecated, OldDeprecated, Override) ||
2163          !versionsMatch(Obsoleted, OldObsoleted, Override) ||
2164          !(OldIsUnavailable == IsUnavailable ||
2165            (Override && !OldIsUnavailable && IsUnavailable))) {
2166        if (Override) {
2167          int Which = -1;
2168          VersionTuple FirstVersion;
2169          VersionTuple SecondVersion;
2170          if (!versionsMatch(OldIntroduced, Introduced, Override)) {
2171            Which = 0;
2172            FirstVersion = OldIntroduced;
2173            SecondVersion = Introduced;
2174          } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) {
2175            Which = 1;
2176            FirstVersion = Deprecated;
2177            SecondVersion = OldDeprecated;
2178          } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) {
2179            Which = 2;
2180            FirstVersion = Obsoleted;
2181            SecondVersion = OldObsoleted;
2182          }
2183
2184          if (Which == -1) {
2185            Diag(OldAA->getLocation(),
2186                 diag::warn_mismatched_availability_override_unavail)
2187              << AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2188          } else {
2189            Diag(OldAA->getLocation(),
2190                 diag::warn_mismatched_availability_override)
2191              << Which
2192              << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2193              << FirstVersion.getAsString() << SecondVersion.getAsString();
2194          }
2195          Diag(Range.getBegin(), diag::note_overridden_method);
2196        } else {
2197          Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2198          Diag(Range.getBegin(), diag::note_previous_attribute);
2199        }
2200
2201        Attrs.erase(Attrs.begin() + i);
2202        --e;
2203        continue;
2204      }
2205
2206      VersionTuple MergedIntroduced2 = MergedIntroduced;
2207      VersionTuple MergedDeprecated2 = MergedDeprecated;
2208      VersionTuple MergedObsoleted2 = MergedObsoleted;
2209
2210      if (MergedIntroduced2.empty())
2211        MergedIntroduced2 = OldIntroduced;
2212      if (MergedDeprecated2.empty())
2213        MergedDeprecated2 = OldDeprecated;
2214      if (MergedObsoleted2.empty())
2215        MergedObsoleted2 = OldObsoleted;
2216
2217      if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2218                                MergedIntroduced2, MergedDeprecated2,
2219                                MergedObsoleted2)) {
2220        Attrs.erase(Attrs.begin() + i);
2221        --e;
2222        continue;
2223      }
2224
2225      MergedIntroduced = MergedIntroduced2;
2226      MergedDeprecated = MergedDeprecated2;
2227      MergedObsoleted = MergedObsoleted2;
2228      ++i;
2229    }
2230  }
2231
2232  if (FoundAny &&
2233      MergedIntroduced == Introduced &&
2234      MergedDeprecated == Deprecated &&
2235      MergedObsoleted == Obsoleted)
2236    return NULL;
2237
2238  // Only create a new attribute if !Override, but we want to do
2239  // the checking.
2240  if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2241                             MergedDeprecated, MergedObsoleted) &&
2242      !Override) {
2243    return ::new (Context) AvailabilityAttr(Range, Context, Platform,
2244                                            Introduced, Deprecated,
2245                                            Obsoleted, IsUnavailable, Message,
2246                                            AttrSpellingListIndex);
2247  }
2248  return NULL;
2249}
2250
2251static void handleAvailabilityAttr(Sema &S, Decl *D,
2252                                   const AttributeList &Attr) {
2253  if (!checkAttributeNumArgs(S, Attr, 1))
2254    return;
2255  IdentifierLoc *Platform = Attr.getArgAsIdent(0);
2256  unsigned Index = Attr.getAttributeSpellingListIndex();
2257
2258  IdentifierInfo *II = Platform->Ident;
2259  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2260    S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2261      << Platform->Ident;
2262
2263  NamedDecl *ND = dyn_cast<NamedDecl>(D);
2264  if (!ND) {
2265    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2266    return;
2267  }
2268
2269  AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
2270  AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
2271  AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
2272  bool IsUnavailable = Attr.getUnavailableLoc().isValid();
2273  StringRef Str;
2274  if (const StringLiteral *SE =
2275          dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
2276    Str = SE->getString();
2277
2278  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
2279                                                      Introduced.Version,
2280                                                      Deprecated.Version,
2281                                                      Obsoleted.Version,
2282                                                      IsUnavailable, Str,
2283                                                      /*Override=*/false,
2284                                                      Index);
2285  if (NewAttr)
2286    D->addAttr(NewAttr);
2287}
2288
2289template <class T>
2290static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2291                              typename T::VisibilityType value,
2292                              unsigned attrSpellingListIndex) {
2293  T *existingAttr = D->getAttr<T>();
2294  if (existingAttr) {
2295    typename T::VisibilityType existingValue = existingAttr->getVisibility();
2296    if (existingValue == value)
2297      return NULL;
2298    S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2299    S.Diag(range.getBegin(), diag::note_previous_attribute);
2300    D->dropAttr<T>();
2301  }
2302  return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2303}
2304
2305VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2306                                          VisibilityAttr::VisibilityType Vis,
2307                                          unsigned AttrSpellingListIndex) {
2308  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2309                                               AttrSpellingListIndex);
2310}
2311
2312TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2313                                      TypeVisibilityAttr::VisibilityType Vis,
2314                                      unsigned AttrSpellingListIndex) {
2315  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2316                                                   AttrSpellingListIndex);
2317}
2318
2319static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
2320                                 bool isTypeVisibility) {
2321  // Visibility attributes don't mean anything on a typedef.
2322  if (isa<TypedefNameDecl>(D)) {
2323    S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
2324      << Attr.getName();
2325    return;
2326  }
2327
2328  // 'type_visibility' can only go on a type or namespace.
2329  if (isTypeVisibility &&
2330      !(isa<TagDecl>(D) ||
2331        isa<ObjCInterfaceDecl>(D) ||
2332        isa<NamespaceDecl>(D))) {
2333    S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2334      << Attr.getName() << ExpectedTypeOrNamespace;
2335    return;
2336  }
2337
2338  // Check that the argument is a string literal.
2339  StringRef TypeStr;
2340  SourceLocation LiteralLoc;
2341  if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
2342    return;
2343
2344  VisibilityAttr::VisibilityType type;
2345  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2346    S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2347      << Attr.getName() << TypeStr;
2348    return;
2349  }
2350
2351  // Complain about attempts to use protected visibility on targets
2352  // (like Darwin) that don't support it.
2353  if (type == VisibilityAttr::Protected &&
2354      !S.Context.getTargetInfo().hasProtectedVisibility()) {
2355    S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
2356    type = VisibilityAttr::Default;
2357  }
2358
2359  unsigned Index = Attr.getAttributeSpellingListIndex();
2360  clang::Attr *newAttr;
2361  if (isTypeVisibility) {
2362    newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
2363                                    (TypeVisibilityAttr::VisibilityType) type,
2364                                        Index);
2365  } else {
2366    newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
2367  }
2368  if (newAttr)
2369    D->addAttr(newAttr);
2370}
2371
2372static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
2373                                       const AttributeList &Attr) {
2374  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(decl);
2375  if (!method) {
2376    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2377      << ExpectedMethod;
2378    return;
2379  }
2380
2381  if (!Attr.isArgIdent(0)) {
2382    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2383      << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2384    return;
2385  }
2386
2387  IdentifierLoc *IL = Attr.getArgAsIdent(0);
2388  ObjCMethodFamilyAttr::FamilyKind F;
2389  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2390    S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
2391      << IL->Ident;
2392    return;
2393  }
2394
2395  if (F == ObjCMethodFamilyAttr::OMF_init &&
2396      !method->getResultType()->isObjCObjectPointerType()) {
2397    S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
2398      << method->getResultType();
2399    // Ignore the attribute.
2400    return;
2401  }
2402
2403  method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
2404                                                       S.Context, F));
2405}
2406
2407static void handleObjCExceptionAttr(Sema &S, Decl *D,
2408                                    const AttributeList &Attr) {
2409  ObjCInterfaceDecl *OCI = dyn_cast<ObjCInterfaceDecl>(D);
2410  if (OCI == 0) {
2411    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
2412      << Attr.getName() << ExpectedObjectiveCInterface;
2413    return;
2414  }
2415
2416  D->addAttr(::new (S.Context)
2417             ObjCExceptionAttr(Attr.getRange(), S.Context,
2418                               Attr.getAttributeSpellingListIndex()));
2419}
2420
2421static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
2422  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2423    QualType T = TD->getUnderlyingType();
2424    if (!T->isCARCBridgableType()) {
2425      S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2426      return;
2427    }
2428  }
2429  else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2430    QualType T = PD->getType();
2431    if (!T->isCARCBridgableType()) {
2432      S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2433      return;
2434    }
2435  }
2436  else {
2437    // It is okay to include this attribute on properties, e.g.:
2438    //
2439    //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2440    //
2441    // In this case it follows tradition and suppresses an error in the above
2442    // case.
2443    S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2444  }
2445  D->addAttr(::new (S.Context)
2446             ObjCNSObjectAttr(Attr.getRange(), S.Context,
2447                              Attr.getAttributeSpellingListIndex()));
2448}
2449
2450static void
2451handleOverloadableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2452  if (!isa<FunctionDecl>(D)) {
2453    S.Diag(Attr.getLoc(), diag::err_attribute_overloadable_not_function);
2454    return;
2455  }
2456
2457  D->addAttr(::new (S.Context)
2458             OverloadableAttr(Attr.getRange(), S.Context,
2459                              Attr.getAttributeSpellingListIndex()));
2460}
2461
2462static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2463  if (!Attr.isArgIdent(0)) {
2464    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2465      << Attr.getName() << 1 << AANT_ArgumentIdentifier;
2466    return;
2467  }
2468
2469  IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
2470  BlocksAttr::BlockType type;
2471  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2472    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
2473      << Attr.getName() << II;
2474    return;
2475  }
2476
2477  D->addAttr(::new (S.Context)
2478             BlocksAttr(Attr.getRange(), S.Context, type,
2479                        Attr.getAttributeSpellingListIndex()));
2480}
2481
2482static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2483  // check the attribute arguments.
2484  if (Attr.getNumArgs() > 2) {
2485    S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
2486    return;
2487  }
2488
2489  unsigned sentinel = 0;
2490  if (Attr.getNumArgs() > 0) {
2491    Expr *E = Attr.getArgAsExpr(0);
2492    llvm::APSInt Idx(32);
2493    if (E->isTypeDependent() || E->isValueDependent() ||
2494        !E->isIntegerConstantExpr(Idx, S.Context)) {
2495      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2496        << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
2497        << E->getSourceRange();
2498      return;
2499    }
2500
2501    if (Idx.isSigned() && Idx.isNegative()) {
2502      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2503        << E->getSourceRange();
2504      return;
2505    }
2506
2507    sentinel = Idx.getZExtValue();
2508  }
2509
2510  unsigned nullPos = 0;
2511  if (Attr.getNumArgs() > 1) {
2512    Expr *E = Attr.getArgAsExpr(1);
2513    llvm::APSInt Idx(32);
2514    if (E->isTypeDependent() || E->isValueDependent() ||
2515        !E->isIntegerConstantExpr(Idx, S.Context)) {
2516      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
2517        << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
2518        << E->getSourceRange();
2519      return;
2520    }
2521    nullPos = Idx.getZExtValue();
2522
2523    if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2524      // FIXME: This error message could be improved, it would be nice
2525      // to say what the bounds actually are.
2526      S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2527        << E->getSourceRange();
2528      return;
2529    }
2530  }
2531
2532  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2533    const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2534    if (isa<FunctionNoProtoType>(FT)) {
2535      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2536      return;
2537    }
2538
2539    if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2540      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2541      return;
2542    }
2543  } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2544    if (!MD->isVariadic()) {
2545      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2546      return;
2547    }
2548  } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
2549    if (!BD->isVariadic()) {
2550      S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2551      return;
2552    }
2553  } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
2554    QualType Ty = V->getType();
2555    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2556      const FunctionType *FT = Ty->isFunctionPointerType() ? getFunctionType(D)
2557       : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2558      if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2559        int m = Ty->isFunctionPointerType() ? 0 : 1;
2560        S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2561        return;
2562      }
2563    } else {
2564      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2565        << Attr.getName() << ExpectedFunctionMethodOrBlock;
2566      return;
2567    }
2568  } else {
2569    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2570      << Attr.getName() << ExpectedFunctionMethodOrBlock;
2571    return;
2572  }
2573  D->addAttr(::new (S.Context)
2574             SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
2575                          Attr.getAttributeSpellingListIndex()));
2576}
2577
2578static void handleWarnUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2579  if (RecordDecl *RD = dyn_cast<RecordDecl>(D))
2580    RD->addAttr(::new (S.Context) WarnUnusedAttr(Attr.getRange(), S.Context));
2581  else
2582    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2583}
2584
2585static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
2586  if (!isFunction(D) && !isa<ObjCMethodDecl>(D) && !isa<CXXRecordDecl>(D)) {
2587    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2588      << Attr.getName() << ExpectedFunctionMethodOrClass;
2589    return;
2590  }
2591
2592  if (isFunction(D) && getFunctionType(D)->getResultType()->isVoidType()) {
2593    S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2594      << Attr.getName() << 0;
2595    return;
2596  }
2597  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
2598    if (MD->getResultType()->isVoidType()) {
2599      S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
2600      << Attr.getName() << 1;
2601      return;
2602    }
2603
2604  D->addAttr(::new (S.Context)
2605             WarnUnusedResultAttr(Attr.getRange(), S.Context,
2606                                  Attr.getAttributeSpellingListIndex()));
2607}
2608
2609static void handleWeakAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2610  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D)) {
2611    if (isa<CXXRecordDecl>(D)) {
2612      D->addAttr(::new (S.Context) WeakAttr(Attr.getRange(), S.Context));
2613      return;
2614    }
2615    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2616      << Attr.getName() << ExpectedVariableOrFunction;
2617    return;
2618  }
2619
2620  NamedDecl *nd = cast<NamedDecl>(D);
2621
2622  nd->addAttr(::new (S.Context)
2623              WeakAttr(Attr.getRange(), S.Context,
2624                       Attr.getAttributeSpellingListIndex()));
2625}
2626
2627static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2628  // weak_import only applies to variable & function declarations.
2629  bool isDef = false;
2630  if (!D->canBeWeakImported(isDef)) {
2631    if (isDef)
2632      S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
2633        << "weak_import";
2634    else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2635             (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2636              (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2637      // Nothing to warn about here.
2638    } else
2639      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2640        << Attr.getName() << ExpectedVariableOrFunction;
2641
2642    return;
2643  }
2644
2645  D->addAttr(::new (S.Context)
2646             WeakImportAttr(Attr.getRange(), S.Context,
2647                            Attr.getAttributeSpellingListIndex()));
2648}
2649
2650// Handles reqd_work_group_size and work_group_size_hint.
2651static void handleWorkGroupSize(Sema &S, Decl *D,
2652                                const AttributeList &Attr) {
2653  unsigned WGSize[3];
2654  for (unsigned i = 0; i < 3; ++i) {
2655    Expr *E = Attr.getArgAsExpr(i);
2656    llvm::APSInt ArgNum(32);
2657    if (E->isTypeDependent() || E->isValueDependent() ||
2658        !E->isIntegerConstantExpr(ArgNum, S.Context)) {
2659      S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
2660        << Attr.getName() << AANT_ArgumentIntegerConstant
2661        << E->getSourceRange();
2662      return;
2663    }
2664    WGSize[i] = (unsigned) ArgNum.getZExtValue();
2665  }
2666
2667  if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize
2668    && D->hasAttr<ReqdWorkGroupSizeAttr>()) {
2669      ReqdWorkGroupSizeAttr *A = D->getAttr<ReqdWorkGroupSizeAttr>();
2670      if (!(A->getXDim() == WGSize[0] &&
2671            A->getYDim() == WGSize[1] &&
2672            A->getZDim() == WGSize[2])) {
2673        S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2674          Attr.getName();
2675      }
2676  }
2677
2678  if (Attr.getKind() == AttributeList::AT_WorkGroupSizeHint
2679    && D->hasAttr<WorkGroupSizeHintAttr>()) {
2680      WorkGroupSizeHintAttr *A = D->getAttr<WorkGroupSizeHintAttr>();
2681      if (!(A->getXDim() == WGSize[0] &&
2682            A->getYDim() == WGSize[1] &&
2683            A->getZDim() == WGSize[2])) {
2684        S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) <<
2685          Attr.getName();
2686      }
2687  }
2688
2689  if (Attr.getKind() == AttributeList::AT_ReqdWorkGroupSize)
2690    D->addAttr(::new (S.Context)
2691                 ReqdWorkGroupSizeAttr(Attr.getRange(), S.Context,
2692                                       WGSize[0], WGSize[1], WGSize[2],
2693                                       Attr.getAttributeSpellingListIndex()));
2694  else
2695    D->addAttr(::new (S.Context)
2696                 WorkGroupSizeHintAttr(Attr.getRange(), S.Context,
2697                                       WGSize[0], WGSize[1], WGSize[2],
2698                                       Attr.getAttributeSpellingListIndex()));
2699}
2700
2701static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
2702  assert(Attr.getKind() == AttributeList::AT_VecTypeHint);
2703
2704  if (!checkAttributeNumArgs(S, Attr, 0))
2705    return;
2706
2707  if (!Attr.hasParsedType()) {
2708    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
2709      << Attr.getName() << 1;
2710    return;
2711  }
2712
2713  QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg());
2714
2715  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2716      (ParmType->isBooleanType() ||
2717       !ParmType->isIntegralType(S.getASTContext()))) {
2718    S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
2719        << ParmType;
2720    return;
2721  }
2722
2723  if (Attr.getKind() == AttributeList::AT_VecTypeHint &&
2724      D->hasAttr<VecTypeHintAttr>()) {
2725    VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>();
2726    if (A->getTypeHint() != ParmType) {
2727      S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
2728      return;
2729    }
2730  }
2731
2732  D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
2733                                               ParmType, Attr.getLoc()));
2734}
2735
2736SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2737                                    StringRef Name,
2738                                    unsigned AttrSpellingListIndex) {
2739  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2740    if (ExistingAttr->getName() == Name)
2741      return NULL;
2742    Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
2743    Diag(Range.getBegin(), diag::note_previous_attribute);
2744    return NULL;
2745  }
2746  return ::new (Context) SectionAttr(Range, Context, Name,
2747                                     AttrSpellingListIndex);
2748}
2749
2750static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2751  // Make sure that there is a string literal as the sections's single
2752  // argument.
2753  StringRef Str;
2754  SourceLocation LiteralLoc;
2755  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
2756    return;
2757
2758  // If the target wants to validate the section specifier, make it happen.
2759  std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2760  if (!Error.empty()) {
2761    S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2762    << Error;
2763    return;
2764  }
2765
2766  // This attribute cannot be applied to local variables.
2767  if (isa<VarDecl>(D) && cast<VarDecl>(D)->hasLocalStorage()) {
2768    S.Diag(LiteralLoc, diag::err_attribute_section_local_variable);
2769    return;
2770  }
2771
2772  unsigned Index = Attr.getAttributeSpellingListIndex();
2773  SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
2774  if (NewAttr)
2775    D->addAttr(NewAttr);
2776}
2777
2778
2779static void handleNothrowAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2780  if (NoThrowAttr *Existing = D->getAttr<NoThrowAttr>()) {
2781    if (Existing->getLocation().isInvalid())
2782      Existing->setRange(Attr.getRange());
2783  } else {
2784    D->addAttr(::new (S.Context)
2785               NoThrowAttr(Attr.getRange(), S.Context,
2786                           Attr.getAttributeSpellingListIndex()));
2787  }
2788}
2789
2790static void handleConstAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2791  if (ConstAttr *Existing = D->getAttr<ConstAttr>()) {
2792   if (Existing->getLocation().isInvalid())
2793     Existing->setRange(Attr.getRange());
2794  } else {
2795    D->addAttr(::new (S.Context)
2796               ConstAttr(Attr.getRange(), S.Context,
2797                         Attr.getAttributeSpellingListIndex() ));
2798  }
2799}
2800
2801static void handlePureAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2802  D->addAttr(::new (S.Context)
2803             PureAttr(Attr.getRange(), S.Context,
2804                      Attr.getAttributeSpellingListIndex()));
2805}
2806
2807static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2808  VarDecl *VD = dyn_cast<VarDecl>(D);
2809  if (!VD || !VD->hasLocalStorage()) {
2810    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2811    return;
2812  }
2813
2814  Expr *E = Attr.getArgAsExpr(0);
2815  SourceLocation Loc = E->getExprLoc();
2816  FunctionDecl *FD = 0;
2817  DeclarationNameInfo NI;
2818
2819  // gcc only allows for simple identifiers. Since we support more than gcc, we
2820  // will warn the user.
2821  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2822    if (DRE->hasQualifier())
2823      S.Diag(Loc, diag::warn_cleanup_ext);
2824    FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2825    NI = DRE->getNameInfo();
2826    if (!FD) {
2827      S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
2828        << NI.getName();
2829      return;
2830    }
2831  } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2832    if (ULE->hasExplicitTemplateArgs())
2833      S.Diag(Loc, diag::warn_cleanup_ext);
2834
2835    // This will diagnose the case where the function cannot be found.
2836    FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
2837    NI = ULE->getNameInfo();
2838  } else {
2839    S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
2840    return;
2841  }
2842
2843  if (FD->getNumParams() != 1) {
2844    S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
2845      << NI.getName();
2846    return;
2847  }
2848
2849  // We're currently more strict than GCC about what function types we accept.
2850  // If this ever proves to be a problem it should be easy to fix.
2851  QualType Ty = S.Context.getPointerType(VD->getType());
2852  QualType ParamTy = FD->getParamDecl(0)->getType();
2853  if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
2854                                   ParamTy, Ty) != Sema::Compatible) {
2855    S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
2856      << NI.getName() << ParamTy << Ty;
2857    return;
2858  }
2859
2860  D->addAttr(::new (S.Context)
2861             CleanupAttr(Attr.getRange(), S.Context, FD,
2862                         Attr.getAttributeSpellingListIndex()));
2863}
2864
2865/// Handle __attribute__((format_arg((idx)))) attribute based on
2866/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
2867static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
2868  if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
2869    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
2870      << Attr.getName() << ExpectedFunction;
2871    return;
2872  }
2873
2874  Expr *IdxExpr = Attr.getArgAsExpr(0);
2875  uint64_t ArgIdx;
2876  if (!checkFunctionOrMethodArgumentIndex(S, D, Attr.getName()->getName(),
2877                                          Attr.getLoc(), 1, IdxExpr, ArgIdx))
2878    return;
2879
2880  // make sure the format string is really a string
2881  QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
2882
2883  bool not_nsstring_type = !isNSStringType(Ty, S.Context);
2884  if (not_nsstring_type &&
2885      !isCFStringType(Ty, S.Context) &&
2886      (!Ty->isPointerType() ||
2887       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2888    // FIXME: Should highlight the actual expression that has the wrong type.
2889    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
2890    << (not_nsstring_type ? "a string type" : "an NSString")
2891       << IdxExpr->getSourceRange();
2892    return;
2893  }
2894  Ty = getFunctionOrMethodResultType(D);
2895  if (!isNSStringType(Ty, S.Context) &&
2896      !isCFStringType(Ty, S.Context) &&
2897      (!Ty->isPointerType() ||
2898       !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
2899    // FIXME: Should highlight the actual expression that has the wrong type.
2900    S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
2901    << (not_nsstring_type ? "string type" : "NSString")
2902       << IdxExpr->getSourceRange();
2903    return;
2904  }
2905
2906  // We cannot use the ArgIdx returned from checkFunctionOrMethodArgumentIndex
2907  // because that has corrected for the implicit this parameter, and is zero-
2908  // based.  The attribute expects what the user wrote explicitly.
2909  llvm::APSInt Val;
2910  IdxExpr->EvaluateAsInt(Val, S.Context);
2911
2912  D->addAttr(::new (S.Context)
2913             FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
2914                           Attr.getAttributeSpellingListIndex()));
2915}
2916
2917enum FormatAttrKind {
2918  CFStringFormat,
2919  NSStringFormat,
2920  StrftimeFormat,
2921  SupportedFormat,
2922  IgnoredFormat,
2923  InvalidFormat
2924};
2925
2926/// getFormatAttrKind - Map from format attribute names to supported format
2927/// types.
2928static FormatAttrKind getFormatAttrKind(StringRef Format) {
2929  return llvm::StringSwitch<FormatAttrKind>(Format)
2930    // Check for formats that get handled specially.
2931    .Case("NSString", NSStringFormat)
2932    .Case("CFString", CFStringFormat)
2933    .Case("strftime", StrftimeFormat)
2934
2935    // Otherwise, check for supported formats.
2936    .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
2937    .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
2938    .Case("kprintf", SupportedFormat) // OpenBSD.
2939
2940    .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
2941    .Default(InvalidFormat);
2942}
2943
2944/// Handle __attribute__((init_priority(priority))) attributes based on
2945/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
2946static void handleInitPriorityAttr(Sema &S, Decl *D,
2947                                   const AttributeList &Attr) {
2948  if (!S.getLangOpts().CPlusPlus) {
2949    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
2950    return;
2951  }
2952
2953  if (!isa<VarDecl>(D) || S.getCurFunctionOrMethodDecl()) {
2954    S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2955    Attr.setInvalid();
2956    return;
2957  }
2958  QualType T = dyn_cast<VarDecl>(D)->getType();
2959  if (S.Context.getAsArrayType(T))
2960    T = S.Context.getBaseElementType(T);
2961  if (!T->getAs<RecordType>()) {
2962    S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
2963    Attr.setInvalid();
2964    return;
2965  }
2966
2967  Expr *priorityExpr = Attr.getArgAsExpr(0);
2968
2969  llvm::APSInt priority(32);
2970  if (priorityExpr->isTypeDependent() || priorityExpr->isValueDependent() ||
2971      !priorityExpr->isIntegerConstantExpr(priority, S.Context)) {
2972    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
2973      << Attr.getName() << AANT_ArgumentIntegerConstant
2974      << priorityExpr->getSourceRange();
2975    Attr.setInvalid();
2976    return;
2977  }
2978  unsigned prioritynum = priority.getZExtValue();
2979  if (prioritynum < 101 || prioritynum > 65535) {
2980    S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
2981    <<  priorityExpr->getSourceRange();
2982    Attr.setInvalid();
2983    return;
2984  }
2985  D->addAttr(::new (S.Context)
2986             InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
2987                              Attr.getAttributeSpellingListIndex()));
2988}
2989
2990FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
2991                                  IdentifierInfo *Format, int FormatIdx,
2992                                  int FirstArg,
2993                                  unsigned AttrSpellingListIndex) {
2994  // Check whether we already have an equivalent format attribute.
2995  for (specific_attr_iterator<FormatAttr>
2996         i = D->specific_attr_begin<FormatAttr>(),
2997         e = D->specific_attr_end<FormatAttr>();
2998       i != e ; ++i) {
2999    FormatAttr *f = *i;
3000    if (f->getType() == Format &&
3001        f->getFormatIdx() == FormatIdx &&
3002        f->getFirstArg() == FirstArg) {
3003      // If we don't have a valid location for this attribute, adopt the
3004      // location.
3005      if (f->getLocation().isInvalid())
3006        f->setRange(Range);
3007      return NULL;
3008    }
3009  }
3010
3011  return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3012                                    FirstArg, AttrSpellingListIndex);
3013}
3014
3015/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3016/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3017static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3018  if (!Attr.isArgIdent(0)) {
3019    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3020      << Attr.getName() << 1 << AANT_ArgumentIdentifier;
3021    return;
3022  }
3023
3024  if (!isFunctionOrMethodOrBlock(D) || !hasFunctionProto(D)) {
3025    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3026      << Attr.getName() << ExpectedFunction;
3027    return;
3028  }
3029
3030  // In C++ the implicit 'this' function parameter also counts, and they are
3031  // counted from one.
3032  bool HasImplicitThisParam = isInstanceMethod(D);
3033  unsigned NumArgs  = getFunctionOrMethodNumArgs(D) + HasImplicitThisParam;
3034  unsigned FirstIdx = 1;
3035
3036  IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
3037  StringRef Format = II->getName();
3038
3039  // Normalize the argument, __foo__ becomes foo.
3040  if (Format.startswith("__") && Format.endswith("__")) {
3041    Format = Format.substr(2, Format.size() - 4);
3042    // If we've modified the string name, we need a new identifier for it.
3043    II = &S.Context.Idents.get(Format);
3044  }
3045
3046  // Check for supported formats.
3047  FormatAttrKind Kind = getFormatAttrKind(Format);
3048
3049  if (Kind == IgnoredFormat)
3050    return;
3051
3052  if (Kind == InvalidFormat) {
3053    S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
3054      << "format" << II->getName();
3055    return;
3056  }
3057
3058  // checks for the 2nd argument
3059  Expr *IdxExpr = Attr.getArgAsExpr(1);
3060  llvm::APSInt Idx(32);
3061  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
3062      !IdxExpr->isIntegerConstantExpr(Idx, S.Context)) {
3063    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3064      << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
3065      << IdxExpr->getSourceRange();
3066    return;
3067  }
3068
3069  if (Idx.getZExtValue() < FirstIdx || Idx.getZExtValue() > NumArgs) {
3070    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3071      << "format" << 2 << IdxExpr->getSourceRange();
3072    return;
3073  }
3074
3075  // FIXME: Do we need to bounds check?
3076  unsigned ArgIdx = Idx.getZExtValue() - 1;
3077
3078  if (HasImplicitThisParam) {
3079    if (ArgIdx == 0) {
3080      S.Diag(Attr.getLoc(),
3081             diag::err_format_attribute_implicit_this_format_string)
3082        << IdxExpr->getSourceRange();
3083      return;
3084    }
3085    ArgIdx--;
3086  }
3087
3088  // make sure the format string is really a string
3089  QualType Ty = getFunctionOrMethodArgType(D, ArgIdx);
3090
3091  if (Kind == CFStringFormat) {
3092    if (!isCFStringType(Ty, S.Context)) {
3093      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3094        << "a CFString" << IdxExpr->getSourceRange();
3095      return;
3096    }
3097  } else if (Kind == NSStringFormat) {
3098    // FIXME: do we need to check if the type is NSString*?  What are the
3099    // semantics?
3100    if (!isNSStringType(Ty, S.Context)) {
3101      // FIXME: Should highlight the actual expression that has the wrong type.
3102      S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3103        << "an NSString" << IdxExpr->getSourceRange();
3104      return;
3105    }
3106  } else if (!Ty->isPointerType() ||
3107             !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3108    // FIXME: Should highlight the actual expression that has the wrong type.
3109    S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
3110      << "a string type" << IdxExpr->getSourceRange();
3111    return;
3112  }
3113
3114  // check the 3rd argument
3115  Expr *FirstArgExpr = Attr.getArgAsExpr(2);
3116  llvm::APSInt FirstArg(32);
3117  if (FirstArgExpr->isTypeDependent() || FirstArgExpr->isValueDependent() ||
3118      !FirstArgExpr->isIntegerConstantExpr(FirstArg, S.Context)) {
3119    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3120      << Attr.getName() << 3 << AANT_ArgumentIntegerConstant
3121      << FirstArgExpr->getSourceRange();
3122    return;
3123  }
3124
3125  // check if the function is variadic if the 3rd argument non-zero
3126  if (FirstArg != 0) {
3127    if (isFunctionOrMethodVariadic(D)) {
3128      ++NumArgs; // +1 for ...
3129    } else {
3130      S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3131      return;
3132    }
3133  }
3134
3135  // strftime requires FirstArg to be 0 because it doesn't read from any
3136  // variable the input is just the current time + the format string.
3137  if (Kind == StrftimeFormat) {
3138    if (FirstArg != 0) {
3139      S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
3140        << FirstArgExpr->getSourceRange();
3141      return;
3142    }
3143  // if 0 it disables parameter checking (to use with e.g. va_list)
3144  } else if (FirstArg != 0 && FirstArg != NumArgs) {
3145    S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
3146      << "format" << 3 << FirstArgExpr->getSourceRange();
3147    return;
3148  }
3149
3150  FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
3151                                          Idx.getZExtValue(),
3152                                          FirstArg.getZExtValue(),
3153                                          Attr.getAttributeSpellingListIndex());
3154  if (NewAttr)
3155    D->addAttr(NewAttr);
3156}
3157
3158static void handleTransparentUnionAttr(Sema &S, Decl *D,
3159                                       const AttributeList &Attr) {
3160  // Try to find the underlying union declaration.
3161  RecordDecl *RD = 0;
3162  TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
3163  if (TD && TD->getUnderlyingType()->isUnionType())
3164    RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3165  else
3166    RD = dyn_cast<RecordDecl>(D);
3167
3168  if (!RD || !RD->isUnion()) {
3169    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3170      << Attr.getName() << ExpectedUnion;
3171    return;
3172  }
3173
3174  if (!RD->isCompleteDefinition()) {
3175    S.Diag(Attr.getLoc(),
3176        diag::warn_transparent_union_attribute_not_definition);
3177    return;
3178  }
3179
3180  RecordDecl::field_iterator Field = RD->field_begin(),
3181                          FieldEnd = RD->field_end();
3182  if (Field == FieldEnd) {
3183    S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3184    return;
3185  }
3186
3187  FieldDecl *FirstField = *Field;
3188  QualType FirstType = FirstField->getType();
3189  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3190    S.Diag(FirstField->getLocation(),
3191           diag::warn_transparent_union_attribute_floating)
3192      << FirstType->isVectorType() << FirstType;
3193    return;
3194  }
3195
3196  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3197  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3198  for (; Field != FieldEnd; ++Field) {
3199    QualType FieldType = Field->getType();
3200    if (S.Context.getTypeSize(FieldType) != FirstSize ||
3201        S.Context.getTypeAlign(FieldType) != FirstAlign) {
3202      // Warn if we drop the attribute.
3203      bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3204      unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3205                                 : S.Context.getTypeAlign(FieldType);
3206      S.Diag(Field->getLocation(),
3207          diag::warn_transparent_union_attribute_field_size_align)
3208        << isSize << Field->getDeclName() << FieldBits;
3209      unsigned FirstBits = isSize? FirstSize : FirstAlign;
3210      S.Diag(FirstField->getLocation(),
3211             diag::note_transparent_union_first_field_size_align)
3212        << isSize << FirstBits;
3213      return;
3214    }
3215  }
3216
3217  RD->addAttr(::new (S.Context)
3218              TransparentUnionAttr(Attr.getRange(), S.Context,
3219                                   Attr.getAttributeSpellingListIndex()));
3220}
3221
3222static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3223  // Make sure that there is a string literal as the annotation's single
3224  // argument.
3225  StringRef Str;
3226  if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
3227    return;
3228
3229  // Don't duplicate annotations that are already set.
3230  for (specific_attr_iterator<AnnotateAttr>
3231       i = D->specific_attr_begin<AnnotateAttr>(),
3232       e = D->specific_attr_end<AnnotateAttr>(); i != e; ++i) {
3233    if ((*i)->getAnnotation() == Str)
3234      return;
3235  }
3236
3237  D->addAttr(::new (S.Context)
3238             AnnotateAttr(Attr.getRange(), S.Context, Str,
3239                          Attr.getAttributeSpellingListIndex()));
3240}
3241
3242static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3243  // check the attribute arguments.
3244  if (Attr.getNumArgs() > 1) {
3245    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3246      << Attr.getName() << 1;
3247    return;
3248  }
3249
3250  if (Attr.getNumArgs() == 0) {
3251    D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
3252               true, 0, Attr.getAttributeSpellingListIndex()));
3253    return;
3254  }
3255
3256  Expr *E = Attr.getArgAsExpr(0);
3257  if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3258    S.Diag(Attr.getEllipsisLoc(),
3259           diag::err_pack_expansion_without_parameter_packs);
3260    return;
3261  }
3262
3263  if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3264    return;
3265
3266  S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
3267                   Attr.isPackExpansion());
3268}
3269
3270void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3271                          unsigned SpellingListIndex, bool IsPackExpansion) {
3272  AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3273  SourceLocation AttrLoc = AttrRange.getBegin();
3274
3275  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3276  if (TmpAttr.isAlignas()) {
3277    // C++11 [dcl.align]p1:
3278    //   An alignment-specifier may be applied to a variable or to a class
3279    //   data member, but it shall not be applied to a bit-field, a function
3280    //   parameter, the formal parameter of a catch clause, or a variable
3281    //   declared with the register storage class specifier. An
3282    //   alignment-specifier may also be applied to the declaration of a class
3283    //   or enumeration type.
3284    // C11 6.7.5/2:
3285    //   An alignment attribute shall not be specified in a declaration of
3286    //   a typedef, or a bit-field, or a function, or a parameter, or an
3287    //   object declared with the register storage-class specifier.
3288    int DiagKind = -1;
3289    if (isa<ParmVarDecl>(D)) {
3290      DiagKind = 0;
3291    } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3292      if (VD->getStorageClass() == SC_Register)
3293        DiagKind = 1;
3294      if (VD->isExceptionVariable())
3295        DiagKind = 2;
3296    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
3297      if (FD->isBitField())
3298        DiagKind = 3;
3299    } else if (!isa<TagDecl>(D)) {
3300      Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
3301        << (TmpAttr.isC11() ? "'_Alignas'" : "'alignas'")
3302        << (TmpAttr.isC11() ? ExpectedVariableOrField
3303                            : ExpectedVariableFieldOrTag);
3304      return;
3305    }
3306    if (DiagKind != -1) {
3307      Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3308        << TmpAttr.isC11() << DiagKind;
3309      return;
3310    }
3311  }
3312
3313  if (E->isTypeDependent() || E->isValueDependent()) {
3314    // Save dependent expressions in the AST to be instantiated.
3315    AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3316    AA->setPackExpansion(IsPackExpansion);
3317    D->addAttr(AA);
3318    return;
3319  }
3320
3321  // FIXME: Cache the number on the Attr object?
3322  llvm::APSInt Alignment(32);
3323  ExprResult ICE
3324    = VerifyIntegerConstantExpression(E, &Alignment,
3325        diag::err_aligned_attribute_argument_not_int,
3326        /*AllowFold*/ false);
3327  if (ICE.isInvalid())
3328    return;
3329
3330  // C++11 [dcl.align]p2:
3331  //   -- if the constant expression evaluates to zero, the alignment
3332  //      specifier shall have no effect
3333  // C11 6.7.5p6:
3334  //   An alignment specification of zero has no effect.
3335  if (!(TmpAttr.isAlignas() && !Alignment) &&
3336      !llvm::isPowerOf2_64(Alignment.getZExtValue())) {
3337    Diag(AttrLoc, diag::err_attribute_aligned_not_power_of_two)
3338      << E->getSourceRange();
3339    return;
3340  }
3341
3342  if (TmpAttr.isDeclspec()) {
3343    // We've already verified it's a power of 2, now let's make sure it's
3344    // 8192 or less.
3345    if (Alignment.getZExtValue() > 8192) {
3346      Diag(AttrLoc, diag::err_attribute_aligned_greater_than_8192)
3347        << E->getSourceRange();
3348      return;
3349    }
3350  }
3351
3352  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3353                                                ICE.take(), SpellingListIndex);
3354  AA->setPackExpansion(IsPackExpansion);
3355  D->addAttr(AA);
3356}
3357
3358void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3359                          unsigned SpellingListIndex, bool IsPackExpansion) {
3360  // FIXME: Cache the number on the Attr object if non-dependent?
3361  // FIXME: Perform checking of type validity
3362  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3363                                                SpellingListIndex);
3364  AA->setPackExpansion(IsPackExpansion);
3365  D->addAttr(AA);
3366}
3367
3368void Sema::CheckAlignasUnderalignment(Decl *D) {
3369  assert(D->hasAttrs() && "no attributes on decl");
3370
3371  QualType Ty;
3372  if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3373    Ty = VD->getType();
3374  else
3375    Ty = Context.getTagDeclType(cast<TagDecl>(D));
3376  if (Ty->isDependentType() || Ty->isIncompleteType())
3377    return;
3378
3379  // C++11 [dcl.align]p5, C11 6.7.5/4:
3380  //   The combined effect of all alignment attributes in a declaration shall
3381  //   not specify an alignment that is less strict than the alignment that
3382  //   would otherwise be required for the entity being declared.
3383  AlignedAttr *AlignasAttr = 0;
3384  unsigned Align = 0;
3385  for (specific_attr_iterator<AlignedAttr>
3386         I = D->specific_attr_begin<AlignedAttr>(),
3387         E = D->specific_attr_end<AlignedAttr>(); I != E; ++I) {
3388    if (I->isAlignmentDependent())
3389      return;
3390    if (I->isAlignas())
3391      AlignasAttr = *I;
3392    Align = std::max(Align, I->getAlignment(Context));
3393  }
3394
3395  if (AlignasAttr && Align) {
3396    CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3397    CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty);
3398    if (NaturalAlign > RequestedAlign)
3399      Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3400        << Ty << (unsigned)NaturalAlign.getQuantity();
3401  }
3402}
3403
3404/// handleModeAttr - This attribute modifies the width of a decl with primitive
3405/// type.
3406///
3407/// Despite what would be logical, the mode attribute is a decl attribute, not a
3408/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3409/// HImode, not an intermediate pointer.
3410static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3411  // This attribute isn't documented, but glibc uses it.  It changes
3412  // the width of an int or unsigned int to the specified size.
3413  if (!Attr.isArgIdent(0)) {
3414    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
3415      << AANT_ArgumentIdentifier;
3416    return;
3417  }
3418
3419  IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
3420  StringRef Str = Name->getName();
3421
3422  // Normalize the attribute name, __foo__ becomes foo.
3423  if (Str.startswith("__") && Str.endswith("__"))
3424    Str = Str.substr(2, Str.size() - 4);
3425
3426  unsigned DestWidth = 0;
3427  bool IntegerMode = true;
3428  bool ComplexMode = false;
3429  switch (Str.size()) {
3430  case 2:
3431    switch (Str[0]) {
3432    case 'Q': DestWidth = 8; break;
3433    case 'H': DestWidth = 16; break;
3434    case 'S': DestWidth = 32; break;
3435    case 'D': DestWidth = 64; break;
3436    case 'X': DestWidth = 96; break;
3437    case 'T': DestWidth = 128; break;
3438    }
3439    if (Str[1] == 'F') {
3440      IntegerMode = false;
3441    } else if (Str[1] == 'C') {
3442      IntegerMode = false;
3443      ComplexMode = true;
3444    } else if (Str[1] != 'I') {
3445      DestWidth = 0;
3446    }
3447    break;
3448  case 4:
3449    // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3450    // pointer on PIC16 and other embedded platforms.
3451    if (Str == "word")
3452      DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3453    else if (Str == "byte")
3454      DestWidth = S.Context.getTargetInfo().getCharWidth();
3455    break;
3456  case 7:
3457    if (Str == "pointer")
3458      DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3459    break;
3460  case 11:
3461    if (Str == "unwind_word")
3462      DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3463    break;
3464  }
3465
3466  QualType OldTy;
3467  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3468    OldTy = TD->getUnderlyingType();
3469  else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
3470    OldTy = VD->getType();
3471  else {
3472    S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
3473      << "mode" << Attr.getRange();
3474    return;
3475  }
3476
3477  if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType())
3478    S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
3479  else if (IntegerMode) {
3480    if (!OldTy->isIntegralOrEnumerationType())
3481      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3482  } else if (ComplexMode) {
3483    if (!OldTy->isComplexType())
3484      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3485  } else {
3486    if (!OldTy->isFloatingType())
3487      S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
3488  }
3489
3490  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3491  // and friends, at least with glibc.
3492  // FIXME: Make sure floating-point mappings are accurate
3493  // FIXME: Support XF and TF types
3494  if (!DestWidth) {
3495    S.Diag(Attr.getLoc(), diag::err_unknown_machine_mode) << Name;
3496    return;
3497  }
3498
3499  QualType NewTy;
3500
3501  if (IntegerMode)
3502    NewTy = S.Context.getIntTypeForBitwidth(DestWidth,
3503                                            OldTy->isSignedIntegerType());
3504  else
3505    NewTy = S.Context.getRealTypeForBitwidth(DestWidth);
3506
3507  if (NewTy.isNull()) {
3508    S.Diag(Attr.getLoc(), diag::err_unsupported_machine_mode) << Name;
3509    return;
3510  }
3511
3512  if (ComplexMode) {
3513    NewTy = S.Context.getComplexType(NewTy);
3514  }
3515
3516  // Install the new type.
3517  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
3518    TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3519  else
3520    cast<ValueDecl>(D)->setType(NewTy);
3521
3522  D->addAttr(::new (S.Context)
3523             ModeAttr(Attr.getRange(), S.Context, Name,
3524                      Attr.getAttributeSpellingListIndex()));
3525}
3526
3527static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3528  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3529    if (!VD->hasGlobalStorage())
3530      S.Diag(Attr.getLoc(),
3531             diag::warn_attribute_requires_functions_or_static_globals)
3532        << Attr.getName();
3533  } else if (!isFunctionOrMethod(D)) {
3534    S.Diag(Attr.getLoc(),
3535           diag::warn_attribute_requires_functions_or_static_globals)
3536      << Attr.getName();
3537    return;
3538  }
3539
3540  D->addAttr(::new (S.Context)
3541             NoDebugAttr(Attr.getRange(), S.Context,
3542                         Attr.getAttributeSpellingListIndex()));
3543}
3544
3545static void handleNoInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3546  if (!isa<FunctionDecl>(D)) {
3547    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3548      << Attr.getName() << ExpectedFunction;
3549    return;
3550  }
3551
3552  D->addAttr(::new (S.Context)
3553             NoInlineAttr(Attr.getRange(), S.Context,
3554             Attr.getAttributeSpellingListIndex()));
3555}
3556
3557static void handleNoInstrumentFunctionAttr(Sema &S, Decl *D,
3558                                           const AttributeList &Attr) {
3559  if (!isa<FunctionDecl>(D)) {
3560    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3561      << Attr.getName() << ExpectedFunction;
3562    return;
3563  }
3564
3565  D->addAttr(::new (S.Context)
3566             NoInstrumentFunctionAttr(Attr.getRange(), S.Context,
3567                                      Attr.getAttributeSpellingListIndex()));
3568}
3569
3570static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3571  if (S.LangOpts.CUDA) {
3572    if (!isa<VarDecl>(D)) {
3573      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3574        << Attr.getName() << ExpectedVariable;
3575      return;
3576    }
3577
3578    D->addAttr(::new (S.Context)
3579               CUDAConstantAttr(Attr.getRange(), S.Context,
3580                                Attr.getAttributeSpellingListIndex()));
3581  } else {
3582    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "constant";
3583  }
3584}
3585
3586static void handleDeviceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3587  if (S.LangOpts.CUDA) {
3588    // check the attribute arguments.
3589    if (Attr.getNumArgs() != 0) {
3590      S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3591        << Attr.getName() << 0;
3592      return;
3593    }
3594
3595    if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) {
3596      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3597        << Attr.getName() << ExpectedVariableOrFunction;
3598      return;
3599    }
3600
3601    D->addAttr(::new (S.Context)
3602               CUDADeviceAttr(Attr.getRange(), S.Context,
3603                              Attr.getAttributeSpellingListIndex()));
3604  } else {
3605    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "device";
3606  }
3607}
3608
3609static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3610  if (S.LangOpts.CUDA) {
3611    if (!isa<FunctionDecl>(D)) {
3612      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3613        << Attr.getName() << ExpectedFunction;
3614      return;
3615    }
3616
3617    FunctionDecl *FD = cast<FunctionDecl>(D);
3618    if (!FD->getResultType()->isVoidType()) {
3619      TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3620      if (FunctionTypeLoc FTL = TL.getAs<FunctionTypeLoc>()) {
3621        S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3622          << FD->getType()
3623          << FixItHint::CreateReplacement(FTL.getResultLoc().getSourceRange(),
3624                                          "void");
3625      } else {
3626        S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
3627          << FD->getType();
3628      }
3629      return;
3630    }
3631
3632    D->addAttr(::new (S.Context)
3633               CUDAGlobalAttr(Attr.getRange(), S.Context,
3634                              Attr.getAttributeSpellingListIndex()));
3635  } else {
3636    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "global";
3637  }
3638}
3639
3640static void handleHostAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3641  if (S.LangOpts.CUDA) {
3642    if (!isa<FunctionDecl>(D)) {
3643      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3644        << Attr.getName() << ExpectedFunction;
3645      return;
3646    }
3647
3648    D->addAttr(::new (S.Context)
3649               CUDAHostAttr(Attr.getRange(), S.Context,
3650                            Attr.getAttributeSpellingListIndex()));
3651  } else {
3652    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "host";
3653  }
3654}
3655
3656static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3657  if (S.LangOpts.CUDA) {
3658    if (!isa<VarDecl>(D)) {
3659      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3660        << Attr.getName() << ExpectedVariable;
3661      return;
3662    }
3663
3664    D->addAttr(::new (S.Context)
3665               CUDASharedAttr(Attr.getRange(), S.Context,
3666                              Attr.getAttributeSpellingListIndex()));
3667  } else {
3668    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "shared";
3669  }
3670}
3671
3672static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3673  FunctionDecl *Fn = dyn_cast<FunctionDecl>(D);
3674  if (Fn == 0) {
3675    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3676      << Attr.getName() << ExpectedFunction;
3677    return;
3678  }
3679
3680  if (!Fn->isInlineSpecified()) {
3681    S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
3682    return;
3683  }
3684
3685  D->addAttr(::new (S.Context)
3686             GNUInlineAttr(Attr.getRange(), S.Context,
3687                           Attr.getAttributeSpellingListIndex()));
3688}
3689
3690static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3691  if (hasDeclarator(D)) return;
3692
3693  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3694  // Diagnostic is emitted elsewhere: here we store the (valid) Attr
3695  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
3696  CallingConv CC;
3697  if (S.CheckCallingConvAttr(Attr, CC, FD))
3698    return;
3699
3700  if (!isa<ObjCMethodDecl>(D)) {
3701    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3702      << Attr.getName() << ExpectedFunctionOrMethod;
3703    return;
3704  }
3705
3706  switch (Attr.getKind()) {
3707  case AttributeList::AT_FastCall:
3708    D->addAttr(::new (S.Context)
3709               FastCallAttr(Attr.getRange(), S.Context,
3710                            Attr.getAttributeSpellingListIndex()));
3711    return;
3712  case AttributeList::AT_StdCall:
3713    D->addAttr(::new (S.Context)
3714               StdCallAttr(Attr.getRange(), S.Context,
3715                           Attr.getAttributeSpellingListIndex()));
3716    return;
3717  case AttributeList::AT_ThisCall:
3718    D->addAttr(::new (S.Context)
3719               ThisCallAttr(Attr.getRange(), S.Context,
3720                            Attr.getAttributeSpellingListIndex()));
3721    return;
3722  case AttributeList::AT_CDecl:
3723    D->addAttr(::new (S.Context)
3724               CDeclAttr(Attr.getRange(), S.Context,
3725                         Attr.getAttributeSpellingListIndex()));
3726    return;
3727  case AttributeList::AT_Pascal:
3728    D->addAttr(::new (S.Context)
3729               PascalAttr(Attr.getRange(), S.Context,
3730                          Attr.getAttributeSpellingListIndex()));
3731    return;
3732  case AttributeList::AT_MSABI:
3733    D->addAttr(::new (S.Context)
3734               MSABIAttr(Attr.getRange(), S.Context,
3735                         Attr.getAttributeSpellingListIndex()));
3736    return;
3737  case AttributeList::AT_SysVABI:
3738    D->addAttr(::new (S.Context)
3739               SysVABIAttr(Attr.getRange(), S.Context,
3740                           Attr.getAttributeSpellingListIndex()));
3741    return;
3742  case AttributeList::AT_Pcs: {
3743    PcsAttr::PCSType PCS;
3744    switch (CC) {
3745    case CC_AAPCS:
3746      PCS = PcsAttr::AAPCS;
3747      break;
3748    case CC_AAPCS_VFP:
3749      PCS = PcsAttr::AAPCS_VFP;
3750      break;
3751    default:
3752      llvm_unreachable("unexpected calling convention in pcs attribute");
3753    }
3754
3755    D->addAttr(::new (S.Context)
3756               PcsAttr(Attr.getRange(), S.Context, PCS,
3757                       Attr.getAttributeSpellingListIndex()));
3758    return;
3759  }
3760  case AttributeList::AT_PnaclCall:
3761    D->addAttr(::new (S.Context)
3762               PnaclCallAttr(Attr.getRange(), S.Context,
3763                             Attr.getAttributeSpellingListIndex()));
3764    return;
3765  case AttributeList::AT_IntelOclBicc:
3766    D->addAttr(::new (S.Context)
3767               IntelOclBiccAttr(Attr.getRange(), S.Context,
3768                                Attr.getAttributeSpellingListIndex()));
3769    return;
3770
3771  default:
3772    llvm_unreachable("unexpected attribute kind");
3773  }
3774}
3775
3776static void handleOpenCLKernelAttr(Sema &S, Decl *D, const AttributeList &Attr){
3777  D->addAttr(::new (S.Context) OpenCLKernelAttr(Attr.getRange(), S.Context));
3778}
3779
3780static void handleOpenCLImageAccessAttr(Sema &S, Decl *D, const AttributeList &Attr){
3781  Expr *E = Attr.getArgAsExpr(0);
3782  llvm::APSInt ArgNum(32);
3783  if (E->isTypeDependent() || E->isValueDependent() ||
3784      !E->isIntegerConstantExpr(ArgNum, S.Context)) {
3785    S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3786      << Attr.getName() << AANT_ArgumentIntegerConstant
3787      << E->getSourceRange();
3788    return;
3789  }
3790
3791  D->addAttr(::new (S.Context) OpenCLImageAccessAttr(
3792    Attr.getRange(), S.Context, ArgNum.getZExtValue()));
3793}
3794
3795bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
3796                                const FunctionDecl *FD) {
3797  if (attr.isInvalid())
3798    return true;
3799
3800  unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
3801  if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
3802    attr.setInvalid();
3803    return true;
3804  }
3805
3806  // TODO: diagnose uses of these conventions on the wrong target. Or, better
3807  // move to TargetAttributesSema one day.
3808  switch (attr.getKind()) {
3809  case AttributeList::AT_CDecl: CC = CC_C; break;
3810  case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
3811  case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
3812  case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
3813  case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
3814  case AttributeList::AT_MSABI:
3815    CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
3816                                                             CC_X86_64Win64;
3817    break;
3818  case AttributeList::AT_SysVABI:
3819    CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
3820                                                             CC_C;
3821    break;
3822  case AttributeList::AT_Pcs: {
3823    StringRef StrRef;
3824    if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
3825      attr.setInvalid();
3826      return true;
3827    }
3828    if (StrRef == "aapcs") {
3829      CC = CC_AAPCS;
3830      break;
3831    } else if (StrRef == "aapcs-vfp") {
3832      CC = CC_AAPCS_VFP;
3833      break;
3834    }
3835
3836    attr.setInvalid();
3837    Diag(attr.getLoc(), diag::err_invalid_pcs);
3838    return true;
3839  }
3840  case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break;
3841  case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
3842  default: llvm_unreachable("unexpected attribute kind");
3843  }
3844
3845  const TargetInfo &TI = Context.getTargetInfo();
3846  TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
3847  if (A == TargetInfo::CCCR_Warning) {
3848    Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
3849
3850    TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
3851    if (FD)
3852      MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
3853                                    TargetInfo::CCMT_NonMember;
3854    CC = TI.getDefaultCallingConv(MT);
3855  }
3856
3857  return false;
3858}
3859
3860static void handleRegparmAttr(Sema &S, Decl *D, const AttributeList &Attr) {
3861  if (hasDeclarator(D)) return;
3862
3863  unsigned numParams;
3864  if (S.CheckRegparmAttr(Attr, numParams))
3865    return;
3866
3867  if (!isa<ObjCMethodDecl>(D)) {
3868    S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3869      << Attr.getName() << ExpectedFunctionOrMethod;
3870    return;
3871  }
3872
3873  D->addAttr(::new (S.Context)
3874             RegparmAttr(Attr.getRange(), S.Context, numParams,
3875                         Attr.getAttributeSpellingListIndex()));
3876}
3877
3878/// Checks a regparm attribute, returning true if it is ill-formed and
3879/// otherwise setting numParams to the appropriate value.
3880bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
3881  if (Attr.isInvalid())
3882    return true;
3883
3884  if (!checkAttributeNumArgs(*this, Attr, 1)) {
3885    Attr.setInvalid();
3886    return true;
3887  }
3888
3889  Expr *NumParamsExpr = Attr.getArgAsExpr(0);
3890  llvm::APSInt NumParams(32);
3891  if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() ||
3892      !NumParamsExpr->isIntegerConstantExpr(NumParams, Context)) {
3893    Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3894      << Attr.getName() << AANT_ArgumentIntegerConstant
3895      << NumParamsExpr->getSourceRange();
3896    Attr.setInvalid();
3897    return true;
3898  }
3899
3900  if (Context.getTargetInfo().getRegParmMax() == 0) {
3901    Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
3902      << NumParamsExpr->getSourceRange();
3903    Attr.setInvalid();
3904    return true;
3905  }
3906
3907  numParams = NumParams.getZExtValue();
3908  if (numParams > Context.getTargetInfo().getRegParmMax()) {
3909    Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
3910      << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
3911    Attr.setInvalid();
3912    return true;
3913  }
3914
3915  return false;
3916}
3917
3918static void handleLaunchBoundsAttr(Sema &S, Decl *D, const AttributeList &Attr){
3919  if (S.LangOpts.CUDA) {
3920    // check the attribute arguments.
3921    if (Attr.getNumArgs() != 1 && Attr.getNumArgs() != 2) {
3922      // FIXME: 0 is not okay.
3923      S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) << 2;
3924      return;
3925    }
3926
3927    if (!isFunctionOrMethod(D)) {
3928      S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
3929        << Attr.getName() << ExpectedFunctionOrMethod;
3930      return;
3931    }
3932
3933    Expr *MaxThreadsExpr = Attr.getArgAsExpr(0);
3934    llvm::APSInt MaxThreads(32);
3935    if (MaxThreadsExpr->isTypeDependent() ||
3936        MaxThreadsExpr->isValueDependent() ||
3937        !MaxThreadsExpr->isIntegerConstantExpr(MaxThreads, S.Context)) {
3938      S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3939        << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
3940        << MaxThreadsExpr->getSourceRange();
3941      return;
3942    }
3943
3944    llvm::APSInt MinBlocks(32);
3945    if (Attr.getNumArgs() > 1) {
3946      Expr *MinBlocksExpr = Attr.getArgAsExpr(1);
3947      if (MinBlocksExpr->isTypeDependent() ||
3948          MinBlocksExpr->isValueDependent() ||
3949          !MinBlocksExpr->isIntegerConstantExpr(MinBlocks, S.Context)) {
3950        S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3951          << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
3952          << MinBlocksExpr->getSourceRange();
3953        return;
3954      }
3955    }
3956
3957    D->addAttr(::new (S.Context)
3958               CUDALaunchBoundsAttr(Attr.getRange(), S.Context,
3959                                    MaxThreads.getZExtValue(),
3960                                    MinBlocks.getZExtValue(),
3961                                    Attr.getAttributeSpellingListIndex()));
3962  } else {
3963    S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << "launch_bounds";
3964  }
3965}
3966
3967static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
3968                                          const AttributeList &Attr) {
3969  if (!Attr.isArgIdent(0)) {
3970    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
3971      << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
3972    return;
3973  }
3974
3975  if (!checkAttributeNumArgs(S, Attr, 3))
3976    return;
3977
3978  StringRef AttrName = Attr.getName()->getName();
3979  IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
3980
3981  if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
3982    S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
3983      << Attr.getName() << ExpectedFunctionOrMethod;
3984    return;
3985  }
3986
3987  uint64_t ArgumentIdx;
3988  if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
3989                                          Attr.getLoc(), 2,
3990                                          Attr.getArgAsExpr(1), ArgumentIdx))
3991    return;
3992
3993  uint64_t TypeTagIdx;
3994  if (!checkFunctionOrMethodArgumentIndex(S, D, AttrName,
3995                                          Attr.getLoc(), 3,
3996                                          Attr.getArgAsExpr(2), TypeTagIdx))
3997    return;
3998
3999  bool IsPointer = (AttrName == "pointer_with_type_tag");
4000  if (IsPointer) {
4001    // Ensure that buffer has a pointer type.
4002    QualType BufferTy = getFunctionOrMethodArgType(D, ArgumentIdx);
4003    if (!BufferTy->isPointerType()) {
4004      S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
4005        << Attr.getName();
4006    }
4007  }
4008
4009  D->addAttr(::new (S.Context)
4010             ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
4011                                     ArgumentIdx, TypeTagIdx, IsPointer,
4012                                     Attr.getAttributeSpellingListIndex()));
4013}
4014
4015static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4016                                         const AttributeList &Attr) {
4017  if (!Attr.isArgIdent(0)) {
4018    S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
4019      << Attr.getName() << 1 << AANT_ArgumentIdentifier;
4020    return;
4021  }
4022
4023  if (!checkAttributeNumArgs(S, Attr, 1))
4024    return;
4025
4026  IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
4027  QualType MatchingCType = S.GetTypeFromParser(Attr.getMatchingCType(), NULL);
4028
4029  D->addAttr(::new (S.Context)
4030             TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
4031                                    MatchingCType,
4032                                    Attr.getLayoutCompatible(),
4033                                    Attr.getMustBeNull(),
4034                                    Attr.getAttributeSpellingListIndex()));
4035}
4036
4037//===----------------------------------------------------------------------===//
4038// Checker-specific attribute handlers.
4039//===----------------------------------------------------------------------===//
4040
4041static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
4042  return type->isDependentType() ||
4043         type->isObjCObjectPointerType() ||
4044         S.Context.isObjCNSObjectType(type);
4045}
4046static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
4047  return type->isDependentType() ||
4048         type->isPointerType() ||
4049         isValidSubjectOfNSAttribute(S, type);
4050}
4051
4052static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4053  ParmVarDecl *param = dyn_cast<ParmVarDecl>(D);
4054  if (!param) {
4055    S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4056      << Attr.getRange() << Attr.getName() << ExpectedParameter;
4057    return;
4058  }
4059
4060  bool typeOK, cf;
4061  if (Attr.getKind() == AttributeList::AT_NSConsumed) {
4062    typeOK = isValidSubjectOfNSAttribute(S, param->getType());
4063    cf = false;
4064  } else {
4065    typeOK = isValidSubjectOfCFAttribute(S, param->getType());
4066    cf = true;
4067  }
4068
4069  if (!typeOK) {
4070    S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4071      << Attr.getRange() << Attr.getName() << cf;
4072    return;
4073  }
4074
4075  if (cf)
4076    param->addAttr(::new (S.Context)
4077                   CFConsumedAttr(Attr.getRange(), S.Context,
4078                                  Attr.getAttributeSpellingListIndex()));
4079  else
4080    param->addAttr(::new (S.Context)
4081                   NSConsumedAttr(Attr.getRange(), S.Context,
4082                                  Attr.getAttributeSpellingListIndex()));
4083}
4084
4085static void handleNSConsumesSelfAttr(Sema &S, Decl *D,
4086                                     const AttributeList &Attr) {
4087  if (!isa<ObjCMethodDecl>(D)) {
4088    S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4089      << Attr.getRange() << Attr.getName() << ExpectedMethod;
4090    return;
4091  }
4092
4093  D->addAttr(::new (S.Context)
4094             NSConsumesSelfAttr(Attr.getRange(), S.Context,
4095                                Attr.getAttributeSpellingListIndex()));
4096}
4097
4098static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4099                                        const AttributeList &Attr) {
4100
4101  QualType returnType;
4102
4103  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
4104    returnType = MD->getResultType();
4105  else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4106           (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
4107    return; // ignore: was handled as a type attribute
4108  else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
4109    returnType = PD->getType();
4110  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4111    returnType = FD->getResultType();
4112  else {
4113    S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4114        << Attr.getRange() << Attr.getName()
4115        << ExpectedFunctionOrMethod;
4116    return;
4117  }
4118
4119  bool typeOK;
4120  bool cf;
4121  switch (Attr.getKind()) {
4122  default: llvm_unreachable("invalid ownership attribute");
4123  case AttributeList::AT_NSReturnsAutoreleased:
4124  case AttributeList::AT_NSReturnsRetained:
4125  case AttributeList::AT_NSReturnsNotRetained:
4126    typeOK = isValidSubjectOfNSAttribute(S, returnType);
4127    cf = false;
4128    break;
4129
4130  case AttributeList::AT_CFReturnsRetained:
4131  case AttributeList::AT_CFReturnsNotRetained:
4132    typeOK = isValidSubjectOfCFAttribute(S, returnType);
4133    cf = true;
4134    break;
4135  }
4136
4137  if (!typeOK) {
4138    S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4139      << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf;
4140    return;
4141  }
4142
4143  switch (Attr.getKind()) {
4144    default:
4145      llvm_unreachable("invalid ownership attribute");
4146    case AttributeList::AT_NSReturnsAutoreleased:
4147      D->addAttr(::new (S.Context)
4148                 NSReturnsAutoreleasedAttr(Attr.getRange(), S.Context,
4149                                           Attr.getAttributeSpellingListIndex()));
4150      return;
4151    case AttributeList::AT_CFReturnsNotRetained:
4152      D->addAttr(::new (S.Context)
4153                 CFReturnsNotRetainedAttr(Attr.getRange(), S.Context,
4154                                          Attr.getAttributeSpellingListIndex()));
4155      return;
4156    case AttributeList::AT_NSReturnsNotRetained:
4157      D->addAttr(::new (S.Context)
4158                 NSReturnsNotRetainedAttr(Attr.getRange(), S.Context,
4159                                          Attr.getAttributeSpellingListIndex()));
4160      return;
4161    case AttributeList::AT_CFReturnsRetained:
4162      D->addAttr(::new (S.Context)
4163                 CFReturnsRetainedAttr(Attr.getRange(), S.Context,
4164                                       Attr.getAttributeSpellingListIndex()));
4165      return;
4166    case AttributeList::AT_NSReturnsRetained:
4167      D->addAttr(::new (S.Context)
4168                 NSReturnsRetainedAttr(Attr.getRange(), S.Context,
4169                                       Attr.getAttributeSpellingListIndex()));
4170      return;
4171  };
4172}
4173
4174static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4175                                              const AttributeList &attr) {
4176  const int EP_ObjCMethod = 1;
4177  const int EP_ObjCProperty = 2;
4178
4179  SourceLocation loc = attr.getLoc();
4180  QualType resultType;
4181
4182  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
4183
4184  if (!method) {
4185    ObjCPropertyDecl *property = dyn_cast<ObjCPropertyDecl>(D);
4186    if (!property) {
4187      S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4188        << SourceRange(loc, loc) << attr.getName() << ExpectedMethodOrProperty;
4189      return;
4190    }
4191    resultType = property->getType();
4192  }
4193  else
4194    // Check that the method returns a normal pointer.
4195    resultType = method->getResultType();
4196
4197  if (!resultType->isReferenceType() &&
4198      (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4199    S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4200      << SourceRange(loc)
4201    << attr.getName() << (method ? EP_ObjCMethod : EP_ObjCProperty)
4202    << /*non-retainable pointer*/ 2;
4203
4204    // Drop the attribute.
4205    return;
4206  }
4207
4208  D->addAttr(::new (S.Context)
4209                  ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context,
4210                                              attr.getAttributeSpellingListIndex()));
4211}
4212
4213static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4214                                        const AttributeList &attr) {
4215  SourceLocation loc = attr.getLoc();
4216  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(D);
4217
4218  if (!method) {
4219   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4220   << SourceRange(loc, loc) << attr.getName() << ExpectedMethod;
4221    return;
4222  }
4223  DeclContext *DC = method->getDeclContext();
4224  if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4225    S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4226    << attr.getName() << 0;
4227    S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4228    return;
4229  }
4230  if (method->getMethodFamily() == OMF_dealloc) {
4231    S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4232    << attr.getName() << 1;
4233    return;
4234  }
4235
4236  method->addAttr(::new (S.Context)
4237                  ObjCRequiresSuperAttr(attr.getRange(), S.Context,
4238                                        attr.getAttributeSpellingListIndex()));
4239}
4240
4241/// Handle cf_audited_transfer and cf_unknown_transfer.
4242static void handleCFTransferAttr(Sema &S, Decl *D, const AttributeList &A) {
4243  if (!isa<FunctionDecl>(D)) {
4244    S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4245      << A.getRange() << A.getName() << ExpectedFunction;
4246    return;
4247  }
4248
4249  bool IsAudited = (A.getKind() == AttributeList::AT_CFAuditedTransfer);
4250
4251  // Check whether there's a conflicting attribute already present.
4252  Attr *Existing;
4253  if (IsAudited) {
4254    Existing = D->getAttr<CFUnknownTransferAttr>();
4255  } else {
4256    Existing = D->getAttr<CFAuditedTransferAttr>();
4257  }
4258  if (Existing) {
4259    S.Diag(D->getLocStart(), diag::err_attributes_are_not_compatible)
4260      << A.getName()
4261      << (IsAudited ? "cf_unknown_transfer" : "cf_audited_transfer")
4262      << A.getRange() << Existing->getRange();
4263    return;
4264  }
4265
4266  // All clear;  add the attribute.
4267  if (IsAudited) {
4268    D->addAttr(::new (S.Context)
4269               CFAuditedTransferAttr(A.getRange(), S.Context,
4270                                     A.getAttributeSpellingListIndex()));
4271  } else {
4272    D->addAttr(::new (S.Context)
4273               CFUnknownTransferAttr(A.getRange(), S.Context,
4274                                     A.getAttributeSpellingListIndex()));
4275  }
4276}
4277
4278static void handleNSBridgedAttr(Sema &S, Scope *Sc, Decl *D,
4279                                const AttributeList &Attr) {
4280  RecordDecl *RD = dyn_cast<RecordDecl>(D);
4281  if (!RD || RD->isUnion()) {
4282    S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4283      << Attr.getRange() << Attr.getName() << ExpectedStruct;
4284  }
4285
4286  IdentifierLoc *Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : 0;
4287
4288  // In Objective-C, verify that the type names an Objective-C type.
4289  // We don't want to check this outside of ObjC because people sometimes
4290  // do crazy C declarations of Objective-C types.
4291  if (Parm && S.getLangOpts().ObjC1) {
4292    // Check for an existing type with this name.
4293    LookupResult R(S, DeclarationName(Parm->Ident), Parm->Loc,
4294                   Sema::LookupOrdinaryName);
4295    if (S.LookupName(R, Sc)) {
4296      NamedDecl *Target = R.getFoundDecl();
4297      if (Target && !isa<ObjCInterfaceDecl>(Target)) {
4298        S.Diag(D->getLocStart(), diag::err_ns_bridged_not_interface);
4299        S.Diag(Target->getLocStart(), diag::note_declared_at);
4300      }
4301    }
4302  }
4303
4304  D->addAttr(::new (S.Context)
4305             NSBridgedAttr(Attr.getRange(), S.Context, Parm ? Parm->Ident : 0,
4306                           Attr.getAttributeSpellingListIndex()));
4307}
4308
4309static void handleObjCOwnershipAttr(Sema &S, Decl *D,
4310                                    const AttributeList &Attr) {
4311  if (hasDeclarator(D)) return;
4312
4313  S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4314    << Attr.getRange() << Attr.getName() << ExpectedVariable;
4315}
4316
4317static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4318                                          const AttributeList &Attr) {
4319  if (!isa<VarDecl>(D) && !isa<FieldDecl>(D)) {
4320    S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4321      << Attr.getRange() << Attr.getName() << ExpectedVariable;
4322    return;
4323  }
4324
4325  ValueDecl *vd = cast<ValueDecl>(D);
4326  QualType type = vd->getType();
4327
4328  if (!type->isDependentType() &&
4329      !type->isObjCLifetimeType()) {
4330    S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4331      << type;
4332    return;
4333  }
4334
4335  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4336
4337  // If we have no lifetime yet, check the lifetime we're presumably
4338  // going to infer.
4339  if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
4340    lifetime = type->getObjCARCImplicitLifetime();
4341
4342  switch (lifetime) {
4343  case Qualifiers::OCL_None:
4344    assert(type->isDependentType() &&
4345           "didn't infer lifetime for non-dependent type?");
4346    break;
4347
4348  case Qualifiers::OCL_Weak:   // meaningful
4349  case Qualifiers::OCL_Strong: // meaningful
4350    break;
4351
4352  case Qualifiers::OCL_ExplicitNone:
4353  case Qualifiers::OCL_Autoreleasing:
4354    S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4355      << (lifetime == Qualifiers::OCL_Autoreleasing);
4356    break;
4357  }
4358
4359  D->addAttr(::new (S.Context)
4360             ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
4361                                     Attr.getAttributeSpellingListIndex()));
4362}
4363
4364//===----------------------------------------------------------------------===//
4365// Microsoft specific attribute handlers.
4366//===----------------------------------------------------------------------===//
4367
4368// Check if MS extensions or some other language extensions are enabled.  If
4369// not, issue a diagnostic that the given attribute is unused.
4370static bool checkMicrosoftExt(Sema &S, const AttributeList &Attr,
4371                              bool OtherExtension = false) {
4372  if (S.LangOpts.MicrosoftExt || OtherExtension)
4373    return true;
4374  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
4375  return false;
4376}
4377
4378static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4379  if (!checkMicrosoftExt(S, Attr, S.LangOpts.Borland))
4380    return;
4381
4382  StringRef StrRef;
4383  SourceLocation LiteralLoc;
4384  if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
4385    return;
4386
4387  // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
4388  // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
4389  if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
4390    StrRef = StrRef.drop_front().drop_back();
4391
4392  // Validate GUID length.
4393  if (StrRef.size() != 36) {
4394    S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4395    return;
4396  }
4397
4398  for (unsigned i = 0; i < 36; ++i) {
4399    if (i == 8 || i == 13 || i == 18 || i == 23) {
4400      if (StrRef[i] != '-') {
4401        S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4402        return;
4403      }
4404    } else if (!isHexDigit(StrRef[i])) {
4405      S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
4406      return;
4407    }
4408  }
4409
4410  D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
4411                                        Attr.getAttributeSpellingListIndex()));
4412}
4413
4414static void handleInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4415  if (!checkMicrosoftExt(S, Attr))
4416    return;
4417
4418  AttributeList::Kind Kind = Attr.getKind();
4419  if (Kind == AttributeList::AT_SingleInheritance)
4420    D->addAttr(
4421        ::new (S.Context)
4422               SingleInheritanceAttr(Attr.getRange(), S.Context,
4423                                     Attr.getAttributeSpellingListIndex()));
4424  else if (Kind == AttributeList::AT_MultipleInheritance)
4425    D->addAttr(
4426        ::new (S.Context)
4427               MultipleInheritanceAttr(Attr.getRange(), S.Context,
4428                                       Attr.getAttributeSpellingListIndex()));
4429  else if (Kind == AttributeList::AT_VirtualInheritance)
4430    D->addAttr(
4431        ::new (S.Context)
4432               VirtualInheritanceAttr(Attr.getRange(), S.Context,
4433                                      Attr.getAttributeSpellingListIndex()));
4434}
4435
4436static void handlePortabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4437  if (!checkMicrosoftExt(S, Attr))
4438    return;
4439
4440  AttributeList::Kind Kind = Attr.getKind();
4441    if (Kind == AttributeList::AT_Win64)
4442    D->addAttr(
4443        ::new (S.Context) Win64Attr(Attr.getRange(), S.Context,
4444                                    Attr.getAttributeSpellingListIndex()));
4445}
4446
4447static void handleForceInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4448  if (!checkMicrosoftExt(S, Attr))
4449    return;
4450  D->addAttr(::new (S.Context)
4451             ForceInlineAttr(Attr.getRange(), S.Context,
4452                             Attr.getAttributeSpellingListIndex()));
4453}
4454
4455static void handleSelectAnyAttr(Sema &S, Decl *D, const AttributeList &Attr) {
4456  if (!checkMicrosoftExt(S, Attr))
4457    return;
4458  // Check linkage after possibly merging declaratinos.  See
4459  // checkAttributesAfterMerging().
4460  D->addAttr(::new (S.Context)
4461             SelectAnyAttr(Attr.getRange(), S.Context,
4462                           Attr.getAttributeSpellingListIndex()));
4463}
4464
4465/// Handles semantic checking for features that are common to all attributes,
4466/// such as checking whether a parameter was properly specified, or the correct
4467/// number of arguments were passed, etc.
4468static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D,
4469                                          const AttributeList &Attr) {
4470  // Several attributes carry different semantics than the parsing requires, so
4471  // those are opted out of the common handling.
4472  //
4473  // We also bail on unknown and ignored attributes because those are handled
4474  // as part of the target-specific handling logic.
4475  if (Attr.hasCustomParsing() ||
4476      Attr.getKind() == AttributeList::UnknownAttribute ||
4477      Attr.getKind() == AttributeList::IgnoredAttribute)
4478    return false;
4479
4480  // If there are no optional arguments, then checking for the argument count
4481  // is trivial.
4482  if (Attr.getMinArgs() == Attr.getMaxArgs() &&
4483      !checkAttributeNumArgs(S, Attr, Attr.getMinArgs()))
4484    return true;
4485  return false;
4486}
4487
4488//===----------------------------------------------------------------------===//
4489// Top Level Sema Entry Points
4490//===----------------------------------------------------------------------===//
4491
4492/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
4493/// the attribute applies to decls.  If the attribute is a type attribute, just
4494/// silently ignore it if a GNU attribute.
4495static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
4496                                 const AttributeList &Attr,
4497                                 bool IncludeCXX11Attributes) {
4498  if (Attr.isInvalid())
4499    return;
4500
4501  // Ignore C++11 attributes on declarator chunks: they appertain to the type
4502  // instead.
4503  if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes)
4504    return;
4505
4506  if (handleCommonAttributeFeatures(S, scope, D, Attr))
4507    return;
4508
4509  switch (Attr.getKind()) {
4510  case AttributeList::AT_IBAction:    handleIBAction(S, D, Attr); break;
4511  case AttributeList::AT_IBOutlet:    handleIBOutlet(S, D, Attr); break;
4512  case AttributeList::AT_IBOutletCollection:
4513    handleIBOutletCollection(S, D, Attr); break;
4514  case AttributeList::AT_AddressSpace:
4515  case AttributeList::AT_ObjCGC:
4516  case AttributeList::AT_VectorSize:
4517  case AttributeList::AT_NeonVectorType:
4518  case AttributeList::AT_NeonPolyVectorType:
4519  case AttributeList::AT_Ptr32:
4520  case AttributeList::AT_Ptr64:
4521  case AttributeList::AT_SPtr:
4522  case AttributeList::AT_UPtr:
4523    // Ignore these, these are type attributes, handled by
4524    // ProcessTypeAttributes.
4525    break;
4526  case AttributeList::AT_Alias:       handleAliasAttr       (S, D, Attr); break;
4527  case AttributeList::AT_Aligned:     handleAlignedAttr     (S, D, Attr); break;
4528  case AttributeList::AT_AllocSize:   handleAllocSizeAttr   (S, D, Attr); break;
4529  case AttributeList::AT_AlwaysInline:
4530    handleAlwaysInlineAttr  (S, D, Attr); break;
4531  case AttributeList::AT_AnalyzerNoReturn:
4532    handleAnalyzerNoReturnAttr  (S, D, Attr); break;
4533  case AttributeList::AT_TLSModel:    handleTLSModelAttr    (S, D, Attr); break;
4534  case AttributeList::AT_Annotate:    handleAnnotateAttr    (S, D, Attr); break;
4535  case AttributeList::AT_Availability:handleAvailabilityAttr(S, D, Attr); break;
4536  case AttributeList::AT_CarriesDependency:
4537    handleDependencyAttr(S, scope, D, Attr);
4538    break;
4539  case AttributeList::AT_Common:      handleCommonAttr      (S, D, Attr); break;
4540  case AttributeList::AT_CUDAConstant:handleConstantAttr    (S, D, Attr); break;
4541  case AttributeList::AT_Constructor: handleConstructorAttr (S, D, Attr); break;
4542  case AttributeList::AT_CXX11NoReturn:
4543    handleCXX11NoReturnAttr(S, D, Attr);
4544    break;
4545  case AttributeList::AT_Deprecated:
4546    handleAttrWithMessage<DeprecatedAttr>(S, D, Attr);
4547    break;
4548  case AttributeList::AT_Destructor:  handleDestructorAttr  (S, D, Attr); break;
4549  case AttributeList::AT_ExtVectorType:
4550    handleExtVectorTypeAttr(S, scope, D, Attr);
4551    break;
4552  case AttributeList::AT_MinSize:
4553    handleMinSizeAttr(S, D, Attr);
4554    break;
4555  case AttributeList::AT_Format:      handleFormatAttr      (S, D, Attr); break;
4556  case AttributeList::AT_FormatArg:   handleFormatArgAttr   (S, D, Attr); break;
4557  case AttributeList::AT_CUDAGlobal:  handleGlobalAttr      (S, D, Attr); break;
4558  case AttributeList::AT_CUDADevice:  handleDeviceAttr      (S, D, Attr); break;
4559  case AttributeList::AT_CUDAHost:    handleHostAttr        (S, D, Attr); break;
4560  case AttributeList::AT_GNUInline:   handleGNUInlineAttr   (S, D, Attr); break;
4561  case AttributeList::AT_CUDALaunchBounds:
4562    handleLaunchBoundsAttr(S, D, Attr);
4563    break;
4564  case AttributeList::AT_Malloc:      handleMallocAttr      (S, D, Attr); break;
4565  case AttributeList::AT_MayAlias:    handleMayAliasAttr    (S, D, Attr); break;
4566  case AttributeList::AT_Mode:        handleModeAttr        (S, D, Attr); break;
4567  case AttributeList::AT_NoCommon:    handleNoCommonAttr    (S, D, Attr); break;
4568  case AttributeList::AT_NonNull:     handleNonNullAttr     (S, D, Attr); break;
4569  case AttributeList::AT_Overloadable:handleOverloadableAttr(S, D, Attr); break;
4570  case AttributeList::AT_ownership_returns:
4571  case AttributeList::AT_ownership_takes:
4572  case AttributeList::AT_ownership_holds:
4573      handleOwnershipAttr     (S, D, Attr); break;
4574  case AttributeList::AT_Cold:        handleColdAttr        (S, D, Attr); break;
4575  case AttributeList::AT_Hot:         handleHotAttr         (S, D, Attr); break;
4576  case AttributeList::AT_Naked:       handleNakedAttr       (S, D, Attr); break;
4577  case AttributeList::AT_NoReturn:    handleNoReturnAttr    (S, D, Attr); break;
4578  case AttributeList::AT_NoThrow:     handleNothrowAttr     (S, D, Attr); break;
4579  case AttributeList::AT_CUDAShared:  handleSharedAttr      (S, D, Attr); break;
4580  case AttributeList::AT_VecReturn:   handleVecReturnAttr   (S, D, Attr); break;
4581
4582  case AttributeList::AT_ObjCOwnership:
4583    handleObjCOwnershipAttr(S, D, Attr); break;
4584  case AttributeList::AT_ObjCPreciseLifetime:
4585    handleObjCPreciseLifetimeAttr(S, D, Attr); break;
4586
4587  case AttributeList::AT_ObjCReturnsInnerPointer:
4588    handleObjCReturnsInnerPointerAttr(S, D, Attr); break;
4589
4590  case AttributeList::AT_ObjCRequiresSuper:
4591      handleObjCRequiresSuperAttr(S, D, Attr); break;
4592
4593  case AttributeList::AT_NSBridged:
4594    handleNSBridgedAttr(S, scope, D, Attr); break;
4595
4596  case AttributeList::AT_CFAuditedTransfer:
4597  case AttributeList::AT_CFUnknownTransfer:
4598    handleCFTransferAttr(S, D, Attr); break;
4599
4600  // Checker-specific.
4601  case AttributeList::AT_CFConsumed:
4602  case AttributeList::AT_NSConsumed:  handleNSConsumedAttr  (S, D, Attr); break;
4603  case AttributeList::AT_NSConsumesSelf:
4604    handleNSConsumesSelfAttr(S, D, Attr); break;
4605
4606  case AttributeList::AT_NSReturnsAutoreleased:
4607  case AttributeList::AT_NSReturnsNotRetained:
4608  case AttributeList::AT_CFReturnsNotRetained:
4609  case AttributeList::AT_NSReturnsRetained:
4610  case AttributeList::AT_CFReturnsRetained:
4611    handleNSReturnsRetainedAttr(S, D, Attr); break;
4612
4613  case AttributeList::AT_WorkGroupSizeHint:
4614  case AttributeList::AT_ReqdWorkGroupSize:
4615    handleWorkGroupSize(S, D, Attr); break;
4616
4617  case AttributeList::AT_VecTypeHint:
4618    handleVecTypeHint(S, D, Attr); break;
4619
4620  case AttributeList::AT_InitPriority:
4621      handleInitPriorityAttr(S, D, Attr); break;
4622
4623  case AttributeList::AT_Packed:      handlePackedAttr      (S, D, Attr); break;
4624  case AttributeList::AT_Section:     handleSectionAttr     (S, D, Attr); break;
4625  case AttributeList::AT_Unavailable:
4626    handleAttrWithMessage<UnavailableAttr>(S, D, Attr);
4627    break;
4628  case AttributeList::AT_ArcWeakrefUnavailable:
4629    handleArcWeakrefUnavailableAttr (S, D, Attr);
4630    break;
4631  case AttributeList::AT_ObjCRootClass:
4632    handleObjCRootClassAttr(S, D, Attr);
4633    break;
4634  case AttributeList::AT_ObjCRequiresPropertyDefs:
4635    handleObjCRequiresPropertyDefsAttr (S, D, Attr);
4636    break;
4637  case AttributeList::AT_Unused:      handleUnusedAttr      (S, D, Attr); break;
4638  case AttributeList::AT_ReturnsTwice:
4639    handleReturnsTwiceAttr(S, D, Attr);
4640    break;
4641  case AttributeList::AT_Used:        handleUsedAttr        (S, D, Attr); break;
4642  case AttributeList::AT_Visibility:
4643    handleVisibilityAttr(S, D, Attr, false);
4644    break;
4645  case AttributeList::AT_TypeVisibility:
4646    handleVisibilityAttr(S, D, Attr, true);
4647    break;
4648  case AttributeList::AT_WarnUnused:
4649    handleWarnUnusedAttr(S, D, Attr);
4650    break;
4651  case AttributeList::AT_WarnUnusedResult: handleWarnUnusedResult(S, D, Attr);
4652    break;
4653  case AttributeList::AT_Weak:        handleWeakAttr        (S, D, Attr); break;
4654  case AttributeList::AT_WeakRef:     handleWeakRefAttr     (S, D, Attr); break;
4655  case AttributeList::AT_WeakImport:  handleWeakImportAttr  (S, D, Attr); break;
4656  case AttributeList::AT_TransparentUnion:
4657    handleTransparentUnionAttr(S, D, Attr);
4658    break;
4659  case AttributeList::AT_ObjCException:
4660    handleObjCExceptionAttr(S, D, Attr);
4661    break;
4662  case AttributeList::AT_ObjCMethodFamily:
4663    handleObjCMethodFamilyAttr(S, D, Attr);
4664    break;
4665  case AttributeList::AT_ObjCNSObject:handleObjCNSObject    (S, D, Attr); break;
4666  case AttributeList::AT_Blocks:      handleBlocksAttr      (S, D, Attr); break;
4667  case AttributeList::AT_Sentinel:    handleSentinelAttr    (S, D, Attr); break;
4668  case AttributeList::AT_Const:       handleConstAttr       (S, D, Attr); break;
4669  case AttributeList::AT_Pure:        handlePureAttr        (S, D, Attr); break;
4670  case AttributeList::AT_Cleanup:     handleCleanupAttr     (S, D, Attr); break;
4671  case AttributeList::AT_NoDebug:     handleNoDebugAttr     (S, D, Attr); break;
4672  case AttributeList::AT_NoInline:    handleNoInlineAttr    (S, D, Attr); break;
4673  case AttributeList::AT_Regparm:     handleRegparmAttr     (S, D, Attr); break;
4674  case AttributeList::IgnoredAttribute:
4675    // Just ignore
4676    break;
4677  case AttributeList::AT_NoInstrumentFunction:  // Interacts with -pg.
4678    handleNoInstrumentFunctionAttr(S, D, Attr);
4679    break;
4680  case AttributeList::AT_StdCall:
4681  case AttributeList::AT_CDecl:
4682  case AttributeList::AT_FastCall:
4683  case AttributeList::AT_ThisCall:
4684  case AttributeList::AT_Pascal:
4685  case AttributeList::AT_MSABI:
4686  case AttributeList::AT_SysVABI:
4687  case AttributeList::AT_Pcs:
4688  case AttributeList::AT_PnaclCall:
4689  case AttributeList::AT_IntelOclBicc:
4690    handleCallConvAttr(S, D, Attr);
4691    break;
4692  case AttributeList::AT_OpenCLKernel:
4693    handleOpenCLKernelAttr(S, D, Attr);
4694    break;
4695  case AttributeList::AT_OpenCLImageAccess:
4696    handleOpenCLImageAccessAttr(S, D, Attr);
4697    break;
4698
4699  // Microsoft attributes:
4700  case AttributeList::AT_MsStruct:
4701    handleMsStructAttr(S, D, Attr);
4702    break;
4703  case AttributeList::AT_Uuid:
4704    handleUuidAttr(S, D, Attr);
4705    break;
4706  case AttributeList::AT_SingleInheritance:
4707  case AttributeList::AT_MultipleInheritance:
4708  case AttributeList::AT_VirtualInheritance:
4709    handleInheritanceAttr(S, D, Attr);
4710    break;
4711  case AttributeList::AT_Win64:
4712    handlePortabilityAttr(S, D, Attr);
4713    break;
4714  case AttributeList::AT_ForceInline:
4715    handleForceInlineAttr(S, D, Attr);
4716    break;
4717  case AttributeList::AT_SelectAny:
4718    handleSelectAnyAttr(S, D, Attr);
4719    break;
4720
4721  // Thread safety attributes:
4722  case AttributeList::AT_AssertExclusiveLock:
4723    handleAssertExclusiveLockAttr(S, D, Attr);
4724    break;
4725  case AttributeList::AT_AssertSharedLock:
4726    handleAssertSharedLockAttr(S, D, Attr);
4727    break;
4728  case AttributeList::AT_GuardedVar:
4729    handleGuardedVarAttr(S, D, Attr);
4730    break;
4731  case AttributeList::AT_PtGuardedVar:
4732    handlePtGuardedVarAttr(S, D, Attr);
4733    break;
4734  case AttributeList::AT_ScopedLockable:
4735    handleScopedLockableAttr(S, D, Attr);
4736    break;
4737  case AttributeList::AT_NoSanitizeAddress:
4738    handleNoSanitizeAddressAttr(S, D, Attr);
4739    break;
4740  case AttributeList::AT_NoThreadSafetyAnalysis:
4741    handleNoThreadSafetyAnalysis(S, D, Attr);
4742    break;
4743  case AttributeList::AT_NoSanitizeThread:
4744    handleNoSanitizeThread(S, D, Attr);
4745    break;
4746  case AttributeList::AT_NoSanitizeMemory:
4747    handleNoSanitizeMemory(S, D, Attr);
4748    break;
4749  case AttributeList::AT_Lockable:
4750    handleLockableAttr(S, D, Attr);
4751    break;
4752  case AttributeList::AT_GuardedBy:
4753    handleGuardedByAttr(S, D, Attr);
4754    break;
4755  case AttributeList::AT_PtGuardedBy:
4756    handlePtGuardedByAttr(S, D, Attr);
4757    break;
4758  case AttributeList::AT_ExclusiveLockFunction:
4759    handleExclusiveLockFunctionAttr(S, D, Attr);
4760    break;
4761  case AttributeList::AT_ExclusiveLocksRequired:
4762    handleExclusiveLocksRequiredAttr(S, D, Attr);
4763    break;
4764  case AttributeList::AT_ExclusiveTrylockFunction:
4765    handleExclusiveTrylockFunctionAttr(S, D, Attr);
4766    break;
4767  case AttributeList::AT_LockReturned:
4768    handleLockReturnedAttr(S, D, Attr);
4769    break;
4770  case AttributeList::AT_LocksExcluded:
4771    handleLocksExcludedAttr(S, D, Attr);
4772    break;
4773  case AttributeList::AT_SharedLockFunction:
4774    handleSharedLockFunctionAttr(S, D, Attr);
4775    break;
4776  case AttributeList::AT_SharedLocksRequired:
4777    handleSharedLocksRequiredAttr(S, D, Attr);
4778    break;
4779  case AttributeList::AT_SharedTrylockFunction:
4780    handleSharedTrylockFunctionAttr(S, D, Attr);
4781    break;
4782  case AttributeList::AT_UnlockFunction:
4783    handleUnlockFunAttr(S, D, Attr);
4784    break;
4785  case AttributeList::AT_AcquiredBefore:
4786    handleAcquiredBeforeAttr(S, D, Attr);
4787    break;
4788  case AttributeList::AT_AcquiredAfter:
4789    handleAcquiredAfterAttr(S, D, Attr);
4790    break;
4791
4792  // Consumed analysis attributes.
4793  case AttributeList::AT_Consumable:
4794    handleConsumableAttr(S, D, Attr);
4795    break;
4796  case AttributeList::AT_Consumes:
4797    handleConsumesAttr(S, D, Attr);
4798    break;
4799  case AttributeList::AT_CallableWhen:
4800    handleCallableWhenAttr(S, D, Attr);
4801    break;
4802  case AttributeList::AT_TestsTypestate:
4803    handleTestsTypestateAttr(S, D, Attr);
4804    break;
4805  case AttributeList::AT_ReturnTypestate:
4806    handleReturnTypestateAttr(S, D, Attr);
4807    break;
4808
4809  // Type safety attributes.
4810  case AttributeList::AT_ArgumentWithTypeTag:
4811    handleArgumentWithTypeTagAttr(S, D, Attr);
4812    break;
4813  case AttributeList::AT_TypeTagForDatatype:
4814    handleTypeTagForDatatypeAttr(S, D, Attr);
4815    break;
4816
4817  default:
4818    // Ask target about the attribute.
4819    const TargetAttributesSema &TargetAttrs = S.getTargetAttributesSema();
4820    if (!TargetAttrs.ProcessDeclAttribute(scope, D, Attr, S))
4821      S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() ?
4822             diag::warn_unhandled_ms_attribute_ignored :
4823             diag::warn_unknown_attribute_ignored) << Attr.getName();
4824    break;
4825  }
4826}
4827
4828/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
4829/// attribute list to the specified decl, ignoring any type attributes.
4830void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
4831                                    const AttributeList *AttrList,
4832                                    bool IncludeCXX11Attributes) {
4833  for (const AttributeList* l = AttrList; l; l = l->getNext())
4834    ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes);
4835
4836  // GCC accepts
4837  // static int a9 __attribute__((weakref));
4838  // but that looks really pointless. We reject it.
4839  if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
4840    Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) <<
4841    cast<NamedDecl>(D)->getNameAsString();
4842    D->dropAttr<WeakRefAttr>();
4843    return;
4844  }
4845}
4846
4847// Annotation attributes are the only attributes allowed after an access
4848// specifier.
4849bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4850                                          const AttributeList *AttrList) {
4851  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4852    if (l->getKind() == AttributeList::AT_Annotate) {
4853      handleAnnotateAttr(*this, ASDecl, *l);
4854    } else {
4855      Diag(l->getLoc(), diag::err_only_annotate_after_access_spec);
4856      return true;
4857    }
4858  }
4859
4860  return false;
4861}
4862
4863/// checkUnusedDeclAttributes - Check a list of attributes to see if it
4864/// contains any decl attributes that we should warn about.
4865static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) {
4866  for ( ; A; A = A->getNext()) {
4867    // Only warn if the attribute is an unignored, non-type attribute.
4868    if (A->isUsedAsTypeAttr() || A->isInvalid()) continue;
4869    if (A->getKind() == AttributeList::IgnoredAttribute) continue;
4870
4871    if (A->getKind() == AttributeList::UnknownAttribute) {
4872      S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored)
4873        << A->getName() << A->getRange();
4874    } else {
4875      S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl)
4876        << A->getName() << A->getRange();
4877    }
4878  }
4879}
4880
4881/// checkUnusedDeclAttributes - Given a declarator which is not being
4882/// used to build a declaration, complain about any decl attributes
4883/// which might be lying around on it.
4884void Sema::checkUnusedDeclAttributes(Declarator &D) {
4885  ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList());
4886  ::checkUnusedDeclAttributes(*this, D.getAttributes());
4887  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
4888    ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
4889}
4890
4891/// DeclClonePragmaWeak - clone existing decl (maybe definition),
4892/// \#pragma weak needs a non-definition decl and source may not have one.
4893NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
4894                                      SourceLocation Loc) {
4895  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
4896  NamedDecl *NewD = 0;
4897  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4898    FunctionDecl *NewFD;
4899    // FIXME: Missing call to CheckFunctionDeclaration().
4900    // FIXME: Mangling?
4901    // FIXME: Is the qualifier info correct?
4902    // FIXME: Is the DeclContext correct?
4903    NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(),
4904                                 Loc, Loc, DeclarationName(II),
4905                                 FD->getType(), FD->getTypeSourceInfo(),
4906                                 SC_None, false/*isInlineSpecified*/,
4907                                 FD->hasPrototype(),
4908                                 false/*isConstexprSpecified*/);
4909    NewD = NewFD;
4910
4911    if (FD->getQualifier())
4912      NewFD->setQualifierInfo(FD->getQualifierLoc());
4913
4914    // Fake up parameter variables; they are declared as if this were
4915    // a typedef.
4916    QualType FDTy = FD->getType();
4917    if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) {
4918      SmallVector<ParmVarDecl*, 16> Params;
4919      for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
4920           AE = FT->arg_type_end(); AI != AE; ++AI) {
4921        ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, *AI);
4922        Param->setScopeInfo(0, Params.size());
4923        Params.push_back(Param);
4924      }
4925      NewFD->setParams(Params);
4926    }
4927  } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) {
4928    NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
4929                           VD->getInnerLocStart(), VD->getLocation(), II,
4930                           VD->getType(), VD->getTypeSourceInfo(),
4931                           VD->getStorageClass());
4932    if (VD->getQualifier()) {
4933      VarDecl *NewVD = cast<VarDecl>(NewD);
4934      NewVD->setQualifierInfo(VD->getQualifierLoc());
4935    }
4936  }
4937  return NewD;
4938}
4939
4940/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
4941/// applied to it, possibly with an alias.
4942void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
4943  if (W.getUsed()) return; // only do this once
4944  W.setUsed(true);
4945  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
4946    IdentifierInfo *NDId = ND->getIdentifier();
4947    NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
4948    NewD->addAttr(::new (Context) AliasAttr(W.getLocation(), Context,
4949                                            NDId->getName()));
4950    NewD->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
4951    WeakTopLevelDecl.push_back(NewD);
4952    // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
4953    // to insert Decl at TU scope, sorry.
4954    DeclContext *SavedContext = CurContext;
4955    CurContext = Context.getTranslationUnitDecl();
4956    PushOnScopeChains(NewD, S);
4957    CurContext = SavedContext;
4958  } else { // just add weak to existing
4959    ND->addAttr(::new (Context) WeakAttr(W.getLocation(), Context));
4960  }
4961}
4962
4963void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
4964  // It's valid to "forward-declare" #pragma weak, in which case we
4965  // have to do this.
4966  LoadExternalWeakUndeclaredIdentifiers();
4967  if (!WeakUndeclaredIdentifiers.empty()) {
4968    NamedDecl *ND = NULL;
4969    if (VarDecl *VD = dyn_cast<VarDecl>(D))
4970      if (VD->isExternC())
4971        ND = VD;
4972    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
4973      if (FD->isExternC())
4974        ND = FD;
4975    if (ND) {
4976      if (IdentifierInfo *Id = ND->getIdentifier()) {
4977        llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I
4978          = WeakUndeclaredIdentifiers.find(Id);
4979        if (I != WeakUndeclaredIdentifiers.end()) {
4980          WeakInfo W = I->second;
4981          DeclApplyPragmaWeak(S, ND, W);
4982          WeakUndeclaredIdentifiers[Id] = W;
4983        }
4984      }
4985    }
4986  }
4987}
4988
4989/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
4990/// it, apply them to D.  This is a bit tricky because PD can have attributes
4991/// specified in many different places, and we need to find and apply them all.
4992void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
4993  // Apply decl attributes from the DeclSpec if present.
4994  if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList())
4995    ProcessDeclAttributeList(S, D, Attrs);
4996
4997  // Walk the declarator structure, applying decl attributes that were in a type
4998  // position to the decl itself.  This handles cases like:
4999  //   int *__attr__(x)** D;
5000  // when X is a decl attribute.
5001  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
5002    if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs())
5003      ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false);
5004
5005  // Finally, apply any attributes on the decl itself.
5006  if (const AttributeList *Attrs = PD.getAttributes())
5007    ProcessDeclAttributeList(S, D, Attrs);
5008}
5009
5010/// Is the given declaration allowed to use a forbidden type?
5011static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) {
5012  // Private ivars are always okay.  Unfortunately, people don't
5013  // always properly make their ivars private, even in system headers.
5014  // Plus we need to make fields okay, too.
5015  // Function declarations in sys headers will be marked unavailable.
5016  if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) &&
5017      !isa<FunctionDecl>(decl))
5018    return false;
5019
5020  // Require it to be declared in a system header.
5021  return S.Context.getSourceManager().isInSystemHeader(decl->getLocation());
5022}
5023
5024/// Handle a delayed forbidden-type diagnostic.
5025static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag,
5026                                       Decl *decl) {
5027  if (decl && isForbiddenTypeAllowed(S, decl)) {
5028    decl->addAttr(new (S.Context) UnavailableAttr(diag.Loc, S.Context,
5029                        "this system declaration uses an unsupported type"));
5030    return;
5031  }
5032  if (S.getLangOpts().ObjCAutoRefCount)
5033    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) {
5034      // FIXME: we may want to suppress diagnostics for all
5035      // kind of forbidden type messages on unavailable functions.
5036      if (FD->hasAttr<UnavailableAttr>() &&
5037          diag.getForbiddenTypeDiagnostic() ==
5038          diag::err_arc_array_param_no_ownership) {
5039        diag.Triggered = true;
5040        return;
5041      }
5042    }
5043
5044  S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
5045    << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument();
5046  diag.Triggered = true;
5047}
5048
5049void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
5050  assert(DelayedDiagnostics.getCurrentPool());
5051  DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
5052  DelayedDiagnostics.popWithoutEmitting(state);
5053
5054  // When delaying diagnostics to run in the context of a parsed
5055  // declaration, we only want to actually emit anything if parsing
5056  // succeeds.
5057  if (!decl) return;
5058
5059  // We emit all the active diagnostics in this pool or any of its
5060  // parents.  In general, we'll get one pool for the decl spec
5061  // and a child pool for each declarator; in a decl group like:
5062  //   deprecated_typedef foo, *bar, baz();
5063  // only the declarator pops will be passed decls.  This is correct;
5064  // we really do need to consider delayed diagnostics from the decl spec
5065  // for each of the different declarations.
5066  const DelayedDiagnosticPool *pool = &poppedPool;
5067  do {
5068    for (DelayedDiagnosticPool::pool_iterator
5069           i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
5070      // This const_cast is a bit lame.  Really, Triggered should be mutable.
5071      DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
5072      if (diag.Triggered)
5073        continue;
5074
5075      switch (diag.Kind) {
5076      case DelayedDiagnostic::Deprecation:
5077        // Don't bother giving deprecation diagnostics if the decl is invalid.
5078        if (!decl->isInvalidDecl())
5079          HandleDelayedDeprecationCheck(diag, decl);
5080        break;
5081
5082      case DelayedDiagnostic::Access:
5083        HandleDelayedAccessCheck(diag, decl);
5084        break;
5085
5086      case DelayedDiagnostic::ForbiddenType:
5087        handleDelayedForbiddenType(*this, diag, decl);
5088        break;
5089      }
5090    }
5091  } while ((pool = pool->getParent()));
5092}
5093
5094/// Given a set of delayed diagnostics, re-emit them as if they had
5095/// been delayed in the current context instead of in the given pool.
5096/// Essentially, this just moves them to the current pool.
5097void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
5098  DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
5099  assert(curPool && "re-emitting in undelayed context not supported");
5100  curPool->steal(pool);
5101}
5102
5103static bool isDeclDeprecated(Decl *D) {
5104  do {
5105    if (D->isDeprecated())
5106      return true;
5107    // A category implicitly has the availability of the interface.
5108    if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D))
5109      return CatD->getClassInterface()->isDeprecated();
5110  } while ((D = cast_or_null<Decl>(D->getDeclContext())));
5111  return false;
5112}
5113
5114static void
5115DoEmitDeprecationWarning(Sema &S, const NamedDecl *D, StringRef Message,
5116                         SourceLocation Loc,
5117                         const ObjCInterfaceDecl *UnknownObjCClass,
5118                         const ObjCPropertyDecl *ObjCPropery) {
5119  DeclarationName Name = D->getDeclName();
5120  if (!Message.empty()) {
5121    S.Diag(Loc, diag::warn_deprecated_message) << Name << Message;
5122    S.Diag(D->getLocation(),
5123           isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
5124                                  : diag::note_previous_decl) << Name;
5125    if (ObjCPropery)
5126      S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
5127        << ObjCPropery->getDeclName() << 0;
5128  } else if (!UnknownObjCClass) {
5129    S.Diag(Loc, diag::warn_deprecated) << D->getDeclName();
5130    S.Diag(D->getLocation(),
5131           isa<ObjCMethodDecl>(D) ? diag::note_method_declared_at
5132                                  : diag::note_previous_decl) << Name;
5133    if (ObjCPropery)
5134      S.Diag(ObjCPropery->getLocation(), diag::note_property_attribute)
5135        << ObjCPropery->getDeclName() << 0;
5136  } else {
5137    S.Diag(Loc, diag::warn_deprecated_fwdclass_message) << Name;
5138    S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
5139  }
5140}
5141
5142void Sema::HandleDelayedDeprecationCheck(DelayedDiagnostic &DD,
5143                                         Decl *Ctx) {
5144  if (isDeclDeprecated(Ctx))
5145    return;
5146
5147  DD.Triggered = true;
5148  DoEmitDeprecationWarning(*this, DD.getDeprecationDecl(),
5149                           DD.getDeprecationMessage(), DD.Loc,
5150                           DD.getUnknownObjCClass(),
5151                           DD.getObjCProperty());
5152}
5153
5154void Sema::EmitDeprecationWarning(NamedDecl *D, StringRef Message,
5155                                  SourceLocation Loc,
5156                                  const ObjCInterfaceDecl *UnknownObjCClass,
5157                                  const ObjCPropertyDecl  *ObjCProperty) {
5158  // Delay if we're currently parsing a declaration.
5159  if (DelayedDiagnostics.shouldDelayDiagnostics()) {
5160    DelayedDiagnostics.add(DelayedDiagnostic::makeDeprecation(Loc, D,
5161                                                              UnknownObjCClass,
5162                                                              ObjCProperty,
5163                                                              Message));
5164    return;
5165  }
5166
5167  // Otherwise, don't warn if our current context is deprecated.
5168  if (isDeclDeprecated(cast<Decl>(getCurLexicalContext())))
5169    return;
5170  DoEmitDeprecationWarning(*this, D, Message, Loc, UnknownObjCClass, ObjCProperty);
5171}
5172