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