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