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