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