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