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